Moving common logic into middleware
Let's see how we can improve our code further. If you examine our Create User endpoint handler, you may notice that its logic could be applied to all requests. For example, if a request comes in carrying a payload, we expect the value of its Content-Type
header to include the string application/json
, regardless of which endpoint it is hitting. Therefore, we should pull that piece of logic out into middleware functions to maximize reusability. Specifically, these middleware should perform the following checks:
- If a request uses the method
POST
,PUT
orPATCH
, it must carry a non-empty payload. - If a request contains a non-empty payload, it should have its
Content-Type
header set. If it doesn't, respond with the400 Bad Request
status code. - If a request has set its
Content-Type
header, it must contain the stringapplication/json
. If it doesn't, respond with the415 Unsupported Media Type
status code.
Let's translate these criteria into Cucumber/Gherkin specifications...