Add upsert functionality to DefaultCrudRepository
Feature proposal
Add upsert functionality to DefaultCrudRepository http://apidocs.loopback.io/loopback/#persistedmodel-upsert
Our GUI team would like the ability to call an API endpoint with POST and either create a new object or update an existing object.
Because of race conditions I think this functionality needs to be pushed into the database layer and have the data connector responsible for find/create/update.
Maybe this should just be handled by implementing repository execute()
Another option would be to check existence of primary key to switch on updateById or create.
I guess this issue is more of a question of if upsert needs to be carried forward to LB4.
@elv1s indeed is a good feature. The legacy-juggler implements the save operation which handles this update/insert functionality, however I think that it needs some fine tuning since error conditions were raised during my tests today, specially when it tries to validate the id name.
Actually the post today inside the controller calls the create repository method, so one work-around is to override it in the repository as follows: (ie: we have a model MyModel and I know that the primary key (aka: ID) is id): It will handle the update/insert while keeping everything intact at the controller level.
async create(record: MyModel): Promise<MyModel> {
try {
await this.replaceById(record.id, record);
} catch {
record = await super.create(record);
}
return record;
}
Thanks for the workaround code @marioestradarosa!
This issue has been marked stale because it has not seen activity within six months. If you believe this to be in error, please contact one of the code owners, listed in the CODEOWNERS file at the top-level of this repository. This issue will be closed within 30 days of being stale.
This issue has been closed due to continued inactivity. Thank you for your understanding. If you believe this to be in error, please contact one of the code owners, listed in the CODEOWNERS file at the top-level of this repository.