Security News
GitHub Removes Malicious Pull Requests Targeting Open Source Repositories
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
lambda-serverless-api
Advanced tools
Middleware for AWS Lambda and Api Gateway.
Provides support for:
header
, json
, query
and context
, parameter positionstext
, json
, and binary
response typescors
$ npm install --save lambda-serverless-api
Define api and handlers in handler.js
as follows:
const api = require('lambda-serverless-api').Api({/* options */});
api.wrap('POST register', [
api.Str('name', 'json', { required: false }),
api.Email('email', 'json'),
api.Str('password', 'json')
], /* options, */ ({ name, email, password }) => {
// handle registration logic here ...
if (new Date().getHours() === 4) {
throw api.ApiError('I am a teapot', 418);
}
return api.JsonResponse({ message: 'Success!' });
});
module.exports = api;
then hook the router endpoint into the Serverless Framework configuration as
functions:
router:
handler: handler.router
events:
- schedule: rate(10 minutes)
- http:
path: /{proxy+}
method: ANY
The api is plugin based and all options are tied to plugins. The following plugins are customizable:
lambda-monitor
robots.txt
responseDate
Please see implementation for details.
Takes the following positional arguments:
string
: The method and the uri of the format ${method} ${uri}
Array<Parameter>
: Parameter definitionsfunction
: The handler using parsed parameters as the first argumentNote: The (slightly modified) original event and context can be accessed as additional handler parameters
There are various pre-defined parameters available
YYYY-MM-DD
There are four types of parameter types:
json
: parsed from the json request bodyquery
: parsed from the query stringheader
: parsed from the header and case insensitivecontext
: parsed from the lambda event context. Useful to e.g. obtain the client IPBelow are the default parameter options. Most parameters have several customization options. Please see implementation for details.
Allow input to be not present
Type: boolean
Default: true
Allow input value to be null
.
Note: Parameter position must be in [json, context]
Type: boolean
Default: false
Experimental
Note: only recommended for advanced use cases.
Optionally asynchronous custom "getting" of variables.
Getter function takes raw input from event, IE a query
parameter will always pass String values into the getter
function.
Warnings:
{ nullable: true }
, if a rawInput is passed as null
, or if a non-required parameter is not sent, the getter
function will not be used.getter
function has returned, and may return inconsistent results. Thorough testing is recommended.Takes unresolved parameters as second parameter. Simple parameters can be accessed directly, unresolved can be resolved by using await
.
Type: Function
Default: null
Example
/* { "name": " John "} */
module.exports = api.wrap('POST name', [
api.Str('name', 'json', true, { getter: (input, params) => input.trim() })
], ({ name }) => {
console.log(name); // "John"
});
Parameter names are converted to camel case when passed into the handler.
E.g. the header X-Custom-Header
would be passed as xCustomHeader
.
There are two types of api responses: Success and error responses. Error responses need to be thrown, while success responses need to be returned from the endpoint handler. The following responses are available:
ApiResponse
(e.g. for plain text), JsonResponse
(for json), BinaryResponse
(e.g. for images)ApiError
Success responses take the positional parameters data
(required), statusCode
(optional) and headers
(optional).
Error responses take the positional parameters message
(required), statusCode
(optional), messageId
(optional) and context
(optional). They are always of Json format. It is recommended that an easily identifiable messageId is set on all error responses.
Please see implementation for details.
Done globally through the API configuration. However can be overwritten on a per-endpoint basis
by specifying limit
as an integer in the endpoint definition option.
Rate limiting uses memory by default, which is not shared across function containers. However one can configure S3 to share the rate limiting (recommended). This will (1) increase latency and (2) increase costs per api call.
By default the client IP (['requestContext.identity.sourceIp']
) is used for rate limiting. However this can be customized.
Each endpoint definition can also be exposed as a separate lambda function. However this is not recommended for larger APIs due to CloudFormation limitations (maximum number of resources and stack invalidation issues).
Consider using yaml-boost for loading Serverless Framework configuration.
Consider using a single router function instead of declaring each function individually.
To generate swagger documentation we can call api.generateSwagger()
after the api is initialized with routes. For merge-overwrite the swagger definition fs.smartWrite() can be used.
Example
const fs = require('smart-fs');
const path = require('path');
const updateSwagger = async () => {
const swaggerFile = path.join(__dirname, '..', 'swagger.yml');
const swaggerContent = await api.generateSwagger();
const result = fs.smartWrite(swaggerFile, swaggerContent);
expect(result, 'Swagger file updated').to.equal(false);
};
updateSwagger();
To monitor api errors and exceptions, lambda-monitor should be configured with rollbar.
FAQs
Basic Api Wrapper for Serverless Framework.
The npm package lambda-serverless-api receives a total of 0 weekly downloads. As such, lambda-serverless-api popularity was classified as not popular.
We found that lambda-serverless-api demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
Security News
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
Security News
Node.js will be enforcing stricter semver-major PR policies a month before major releases to enhance stability and ensure reliable release candidates.