Search code examples
node.jsapi-designnestjs

NestJS: Controller function with @UploadedFile or String as a parameter


I am using NestJS (version 6.5, with Express platform) and I need to handle a request with a property that can either be a File or a String.

Here is the code I currently have, but I don't find a clean way to implement this.

MyAwesomeController

@Post()
@UseInterceptors(FileInterceptor('source'))
async handle(@UploadedFile() source, @Body() myDto: MyDto): Promise<any> {
  //do things...
}

Am I missing something obvious or am I supposed to write my own interceptor to handle this case? Design-wise, is this bad?


Solution

  • Based on the fact you're designing a REST API:

    It depends what use case(s) you want to achieve: is your - client-side - flow designed to be performed in 2 steps o not ?
    Can string and file params be both passed at the same time or is there only one of the two on each call ? (like if you want to update a file and its name, or some other non Multer related attributes).
    When you pass a string as parameter to your endpoint call, is a file resource created / updated / deleted ? Or maybe not at all ?

    Depending on the answer and the flow that you thought of, you should split both cases handling within two independent endpoints, or maybe it makes sense to handle both parameters at the same time.

    • If only one of the params can be passed at a time, I'd say go for two independent endpoints; you'll benefit from both maintenance and code readability.

    • If both params can be passed at the same time and they're related to the same resource, then it could make sense to handle both of them at once.

    Hope this helps, don't hesitate to comment ;)