Lopoback4 HasOneRepository
interface implements create
function. Suppose I have a User
model and a Profile
model where User
hasOne Profile
. In the controller:
@post('/users/{id}/profile', {
responses: {
'200': {
description: 'User model instance',
content: {'application/json': {schema: getModelSchemaRef(Profile)}},
},
},
})
async create(
@param.path.number('id') id: typeof User.prototype.id,
@requestBody({
content: {
'application/json': {
schema: getModelSchemaRef(Profile, {
title: 'NewProfileInUser',
exclude: ['id'],
optional: ['userId']
}),
},
},
}) profile: Omit<Profile, 'id'>,
): Promise<Profile> {
return this.userRepository.profile(id).create(profile);
}
Testing this endpoint, there are a couple of unexpected result:
- Providing an
id
for non-existenceUser
would still create an entry in theProfile
table. - Calling this endpoint multiple times would create multiple entries in the
Profile
table for the same user which meanshasOne
is no longer true.
Is this the expected behaviour or am I missing something?. I'm using mariaDB
and "@loopback/core": "^5.1.1"
and "@loopback/repository": "^6.1.3"
,
- Create a new loopback4 application using
lb4
cli. - Create a mysql datasource
- Create a new
User
andProfile
models and repositories. - Create a
HasOne
relation betweenUser
andProfile
. - Create the controllers.
- Test POST:
/users/{id}/profile
with validid
and randomid
Expect:
- Throw ENTITY_NOT_FOUND error if user with
id
do not exists - Throw DUPLICATE error id
profile
for user withid
alreadt exists.
Result:
- The
profile
is created regardless if user withid
exists or not - Multiple
profile
foruser
with the sameid
are created violating 'hasOne' relation - The this.userRepository.profile(id).get() would only return the first instance found