@shgysk8zer0/lambda-http
v1.1.22
Published
A collection of node >= 20 utilities for Netlify Functions and AWS Lambda
Downloads
289
Maintainers
Readme
@shgysk8zer0/lambda-http
A collection of node >= 20 utilities for Netlify Functions and AWS Lambda
This package makes use of node >= 20 having support for the familiar Request
& Response
objects to provide easier and more standards-based
way of creating Netlify Functions and (theoretically) AWS Lambda.
Benefits
- Familiar
Request
&Response
objects - Built-in support for
FormData
&File
s &Blob
s - Easy support for CORS while still being customizable
- Convenient
{ [method]: async handler(requset) }
syntax - Constants for HTTP Status Codes & common Mime-Types
- A custom HTTPError class
- Currently weighs in at only 42.5 kB (unpacked size, including ESM & CJS & & README LICENSE & CHANGELOG)
Example
import { createHandler, HTTPError, HTTP_STATUS } from '@shgysk8zer0/lambda-http';
export default createHandler({
async get(req) {
return Response.json({
url: req.url,
method: req.method,
headers: Object.fromEntries(req.headers),
});
},
async post(req) {
const data = await req.formData();
// Or `req.json()`
if (! (data.has('email') && data.has('password'))) {
throw new HTTPError('Email and password are required', HTTP_STATUS.BAD_REQUEST);
} else {
// Sign-in logic here
return Response.json(user);
}
},
async put(req) {
const blob = await req.blob();
// Or use `req.arrayBuffer()`
// Maybe save it as a file...
return new Response(null, { status: HTTP_STATUS.NO_CONTENT });
}
async delete(req) {
const params = new URLSearchParams(req.url);
if (params.has('id')) {
// Handle some delete operation
} else {
throw new HTTPError('Missing required id.', HTTP_STATUS.BAD_REQUEST);
}
}
}, {
allowOrigins: ['https://example.com'],
allowHeaders: ['Authorization'],
exposeHeaders: ['X-Foo'],
allowCredentials: true,
logger(err, req) {
console.error({ err, req });
}
});
CommonJS (require()
) Note
This is primarily intended for use with ES Modules, though CJS files are generated via Rollup.
Because of this, bear in mind that default exports and named exports do not perfectly translate,
and you cannot just use const createHandler = require('@shgysk8zer0/lambda-http')
like you can
with modules. You'll have to use const { createHandler } = require('@shgysk8zer0/lambda-http')
or const { default: createHandler } = require('@shgysk8zer0/lambda-http')
.