1.1.0 • Published 1 year ago
@shgysk8zer0/netlify-func-utils v1.1.0
@shgysk8zer0/netlify-func-utils
A collection of helpful functions for building Netlify Functions
!IMPORTANT This package relies on
FormDataandFilesupport, which was added in Node 20 and will be available on Netlify and AWS Lambda sometime after it reaches LTS on or about 2023-10-24. In Node 18,FormDatais supported, but uploads will beBlobs instead ofFiles.
Features
- Custom
NetlifyRequestclass extendingRequest- Created from a
HandlerEventevent - Adds convenient
searchParamsproperty (URLSearchParams) - Adds
cookiesproperty as aMapfrom theCookieheader
- Created from a
A
createHandlerfunction- Accepts an object of HTTP Methods and callbacks
- Automatically handles errors
- Callbacks are passed a
NetlifyRequestobject and must return aResponse - Automatically adds CORS headers (can be disabled)
Example
import { createHandler } from '@shgysk8zer0/netlify-func-utils`;
import { BAD_REQUEST, NOT_AUTHORIZED } from '@shgysk8zer0/http/status';
import { HttpError } from '@shgysk8zer0/http/error';
export const handler = createHandler({
get: async req => {
if (req.searchParams.has('id')) {
return Response.json(await getItem(req.searchParams.get('id)));
}
},
post: async req = {
if (! req.cookies.has('token')) {
throw new HTTPError('You must be signed-in.', { status: NOT_AUTHORIZED });
} else {
const data = await req.formData(); // `FormData`, including `File` objects
if (! data.has('required-field')) {
throw new HTTPError('Missing requied field.', { status: BAD_REQUEST });
} else {
// Maybe save something to a DB.
return Response.json({ created: item.id });
}
}
},
delete: async req => {
//
},
}, {
cors: true,
headers: new Headers({ 'X-UID': crypto.randomUUID() }),
allowHeaders: ['X-Foo', 'X-UID'],
}