Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: allow serialize callback in hasOne and hasMany #875

Open
wants to merge 6 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
14 changes: 14 additions & 0 deletions adonis-typings/relations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,12 @@ declare module '@ioc:Adonis/Lucid/Orm' {
foreignKey?: string
serializeAs?: string | null
onQuery?(query: Related['builder'] | Related['subQuery']): void
serialize?: (
value: Related['instance'] | null,
attribute: string,
model: LucidRow,
cherryPickRelations?: CherryPick
) => any
}

/**
Expand Down Expand Up @@ -260,6 +266,14 @@ declare module '@ioc:Adonis/Lucid/Orm' {
readonly serializeAs: string | null
readonly booted: boolean
readonly model: ParentModel

readonly serialize?: (
value: LucidRow,
attribute: string,
model: LucidRow,
cherryPickRelations?: CherryPick
) => any

relatedModel(): RelatedModel
boot(): void
clone(parent: LucidModel): this
Expand Down
13 changes: 13 additions & 0 deletions src/Orm/BaseModel/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1886,6 +1886,19 @@ export class BaseModel implements LucidRow {
* to the relationships
*/
const relationOptions = cherryPick ? cherryPick[relation.serializeAs] : undefined

if (typeof relation.serialize === 'function') {
if (Array.isArray(value)) {
result[relation.serializeAs] = value.map((one) =>
relation.serialize?.(one, key, this, relationOptions)
)
return result
}

result[relation.serializeAs] = relation.serialize(value, key, this, relationOptions)
Sebastien-Ahkrin marked this conversation as resolved.
Show resolved Hide resolved
return result
}

result[relation.serializeAs] = Array.isArray(value)
? value.map((one) => one.serialize(relationOptions))
: value === null
Expand Down
2 changes: 2 additions & 0 deletions src/Orm/Relations/HasMany/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ export class HasMany implements HasManyRelationContract<LucidModel, LucidModel>
public serializeAs =
this.options.serializeAs === undefined ? this.relationName : this.options.serializeAs

public serialize = this.options.serialize

/**
* Local key is reference to the primary key in the self table
* @note: Available after boot is invoked
Expand Down
2 changes: 2 additions & 0 deletions src/Orm/Relations/HasOne/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ export class HasOne implements HasOneRelationContract<LucidModel, LucidModel> {
public serializeAs =
this.options.serializeAs === undefined ? this.relationName : this.options.serializeAs

public serialize = this.options.serialize

/**
* Local key is reference to the primary key in the self table
* @note: Available after boot is invoked
Expand Down
67 changes: 67 additions & 0 deletions test/orm/model-has-many.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5424,4 +5424,71 @@ test.group('Model | HasMany | delete', (group) => {
assert.deepEqual(bindings, rawBindings)
assert.deepEqual(sql, rawSql)
})

test('add hasMany with serialize', async ({ assert }) => {
class Profile extends BaseModel {
@column({ isPrimary: true })
public id: number

@column()
public userId: number

@column()
public displayName: string
}

class User extends BaseModel {
@column({ isPrimary: true })
public id: number

@column()
public username: string

@hasMany(() => Profile, {
serialize: (value) => {
if (value === null) {
return { type: 'profile', displayable: '---' }
}

return {
type: 'profile',
displayable: `${value.userId} - ${value.displayName}`,
}
},
})
public profile: HasMany<typeof Profile>
}

const user = new User()
user.username = 'virk'
await user.save()

await user.load('profile')

assert.deepEqual(user.serialize(), {
username: 'virk',
id: 1,
profile: [],
})

const firstProfile = new Profile()
firstProfile.displayName = 'Hvirk 1'

const secondProfile = new Profile()
secondProfile.displayName = 'Hvirk 2'

await user.related('profile').save(firstProfile)
await user.related('profile').save(secondProfile)

await user.load('profile')

assert.deepEqual(user.serialize(), {
username: 'virk',
id: 1,
profile: [
{ type: 'profile', displayable: '1 - Hvirk 1' },
{ type: 'profile', displayable: '1 - Hvirk 2' },
],
})
})
})
59 changes: 59 additions & 0 deletions test/orm/model-has-one.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2864,4 +2864,63 @@ test.group('Model | HasOne | delete', (group) => {
assert.deepEqual(bindings, rawBindings)
assert.deepEqual(sql, rawSql)
})

test('add hasOne with serialize', async ({ assert }) => {
class Profile extends BaseModel {
@column({ isPrimary: true })
public id: number

@column()
public userId: number

@column()
public displayName: string
}

class User extends BaseModel {
@column({ isPrimary: true })
public id: number

@column()
public username: string

@hasOne(() => Profile, {
serialize: (value) => {
if (value === null) {
return { type: 'profile', displayable: '---' }
}

return {
type: 'profile',
displayable: `${value.userId} - ${value.displayName}`,
}
},
})
public profile: HasOne<typeof Profile>
}

const user = new User()
user.username = 'virk'
await user.save()

await user.load('profile')

assert.deepEqual(user.serialize(), {
username: 'virk',
id: 1,
profile: { type: 'profile', displayable: '---' },
})

const profile = new Profile()
profile.displayName = 'Hvirk'

await user.related('profile').save(profile)
await user.load('profile')

assert.deepEqual(user.serialize(), {
username: 'virk',
id: 1,
profile: { type: 'profile', displayable: '1 - Hvirk' },
})
})
})