nestjsx / crud

NestJs CRUD for RESTful APIs
https://github.com/nestjsx/crud/wiki
MIT License
4.09k stars 541 forks source link

PATCH Method Controller>Service How to get ID of the resource #491

Open dawinter opened 4 years ago

dawinter commented 4 years ago

In the PATCH request the client usually do not the id of the resource as body and send the id as part of the url e.g. /users/:id. But the server need the id to retrieve the resource from the db. The crudservice method for the PATCH action has the following signature: updateOne(req: CrudRequest, dto: T): Promise; Unfortunately the documentation does not describe how the method can access to the id information without manually parsing the search aspect.

Please can you describe how the method can access to the id? Thanks.

michaelyali commented 4 years ago

Sorry, but I didn't understand. You need to do a PATCH request, but you don't know the id of the resource and you want to get this id from the DB before calling a service patch method? Is that correct?

akshay-sf commented 4 years ago

@dawinter Normally the plain Nest will require you to import the param decorator named Param which will solve your issue, but in nestjsx/crud, its being done with the QueryBuilder which is fired using the ParsedRequest param decorator (I think so).

If you want to find out the id from the CrudRequest object, its under req.parsed.search.$and with the array of object. There you will find an object with value id: { $eq: <id> }.

dawinter commented 4 years ago

Thanks @akshay-sourcefuse for the information.May let me explain the background.

I would like use NestJS with NestJSX/Crud controllers and service. The NestJSX typeorm module looks good but we cannot use. Due to typeorm does not support the nosql cloudant database we use, I have to create a custom NestJSX/Crud service.

For this I have to implement the abstract methods of the abstract CrudService. From my understanding each abstract method maps to a HTTP method. As result updateOne maps to PATCH and replaceOne maps to PUT. For PATCH and PUT the service needs the identifier to be able to identiy the resource. In case of PUT, the client sends the full entity as body and could be used to identify the resource. but in case of PATCH the client only sends parts and do not need to send the id as part of the payload. As result, I have to retrieve the identifer from the URL.

I already looked into the provided req object and only only found the information somewhere in the search part, as Akshay mentioned. I get {"$and":[null,{"id":{"$eq":}},{}]}. This is more than Akshay mentioned. I hoped there is a more convenient to get the id.

Are there any how tos / best practices to implement their own Crudservice?

Therefore I asked for recommendations for the ID retrieval.