mrbrianevans / do-functions

Easy development and deployment of Digital Ocean serverless functions in NodeJS.
https://mrbrianevans.github.io/do-functions/
15 stars 0 forks source link

Custom HTTP status code? #3

Open csulit opened 1 year ago

csulit commented 1 year ago

How to return custom status code w/o using external libraries like fastify-error?

mrbrianevans commented 1 year ago

The wrapper accommodates the most common use case of sending a JSON response body with a 200 status code. To send custom headers or status codes, you can just omit using the wrapper and return an object in the form

{body: string, statusCode: number, headers: Record<string,string>}

Eg, if you have a simple function that always returns JSON with a 200 response code, you can do this:

import {wrapFunction} from 'do-functions'

export const main = wrapFunction(args => 'JSON string')

If you wish to make it return an empty body with a 204 status code for example, you can do this:

export const main = async () => ({ body: '', statusCode: 204 })

The wrapper is only designed to simplify the common use case and avoid having to manually add in json content type header.

Hope this answers your question. If it doesn't suit your use case or there is a reason you wish to use the wrapper with a custom status code, let me know. I would be happy to add a feature if it makes sense and it will help you.