A simple package to offer some quick wins for API devs!
A simple npm package to make API dev easy on AWS Lambda.
We've included a docs
folder with a Best Practices document. Please review this document as well as our CONTRIBUTING document before getting started with development contributions.
To contribute to development you must have NodeJS installed on your system.
Additionally this project uses yarn instead of npm. Please ensure you have yarn installed globally. After you do, simply run yarn install
from the project root to install all dependencies.
To use this package in your work simply run npm install lambda-restful-util
or yarn add lambda-restful-util
then include it in your code as with any other dependency.
Both the validateAndParseRequestHeaders
and validateAndParseRequestBody
operate very similarly. Simply pass the event
from API Gateway and both return a truthy object you can use if they're valid. For example:
exports.handler = async (event: APIGatewayProxyEvent) => {
const requestHeaders = utils.validateAndParseRequestHeaders(event)
const requestBody = utils.validateAndParseRequestBody(event)
if (requestHeaders.Authorization && requestBody) {
const token = requestHeaders.Authorization.replace('Bearer ', '')
...
}
...
}
To use the withStatusCode
you only need to specify the response code when declaring the type of response. It is recommended to pass an approved origin for the request if applicable when calling that function. An example of a simple 200 response is as follows:
import util from 'lambda-restful-util'
...
const ok = util.withStatusCode(200)
exports.handler = async (event: APIGatewayProxyEvent) => {
...
return ok('Hey Buddy!', 'http://localhost:8080')
}
For convenience this package includes every HTTP response for reference. To use the HttpStatusCode
enum you can modify the above example by modifying the var: const ok = util.withStatusCode(util.HttpStatusCode.OK, 'http://localhost:8080)
.
In addition to the HttpStatusCode
you can pass a formatting function as an optional argument to withStatusCode
. To add JSON.stringify
simply modify the var again: const ok = util.withStatusCode(util.HttpStatusCode.OK, 'http://localhost:8080, JSON.stringify)
.
If you know your response is going to be JSON this will simplify converting your Object to JSON. For example:
...
const ok = util.withStatusCode(util.HttpStatusCode.OK, JSON.stringify)
...
const res = {
name: 'Homer Simpson'
employer: 'Springfield Power Plant'
}
...
return ok(res)
The above will correctly return a JSON string as the 200 HTTP response to your API request. Consequently if you send return ok('test')
that will also return a JSON 200 response. If you do not want to return JSON simply don't pass a formatting argument when declaring the ok
response.
Run yarn test
Thanks goes to these wonderful people (emoji key):
Jason Anton 💻 📖 |
suryayelagam 👀 |
This project follows the all-contributors specification. Contributions of any kind welcome!