Toolbelt for creating Lambda functions
npm install @genie-solutions/lambda-toolbeltgit checkout master.git pull.npm version patchnpm version minornpm version majortypescript
import { applyMiddleware, httpHandler, withJSONBody, HTTPEvent, HTTPContext } from '@genie-solutions/lambda-toolbelt';const myHelloWorldFunction = async (event: HTTPEvent, context: HTTPContext): Promise
Hello, ${body.name},
};
};export default applyMiddleware(httpHandler, withJSONBody)(myHelloWorldFunction);
`sqsHandler
`typescript
import {
sqsHandler,
SQSCallback,
} from '../src/index';interface MySqsRecordBody {
a: string,
b: number,
c?: number[],
}
const mySuperSweetFunction: SQSCallback = async (sqsRecordBody: MySqsRecordBody, sqsRecord?: AWSLambda.SQSRecord): Promise
export default sqsHandler(mySuperSweetFunction, ['a', 'b']);
`withJWTPayload
Automatically verifies and parses the payload of a JWT token being provided via a HTTP header.Example:
`javascript
import { createParameterStore, applyMiddleware, httpHandler, withJWTPayload } from '@genie-solutions/lambda-toolbelt';const mySuperSecretFunction = async (event: HTTPEvent, context: HTTPContext): Promise
const parameterStore = createParameterStore();
const getPublicKey = () => parameterStore('JWT_PUBLIC_KEY');
export default applyMiddleware(
httpHandler,
withJWTPayload({
getPublicKey,
algorithm: 'RS256',
headerName: 'X-GENIE-ROLES',
payloadKey: 'role',
}),
)(mySuperSecretFunction);
`withParameters
Automatically add parameters into genie context and validate any required params.Example:
`typescript
import {
applyMiddleware,
httpHandler,
withJSONBody,
withParameters,
HTTPEvent,
HTTPContext
} from '@genie-solutions/lambda-toolbelt';// These interfaces should be in type.ts, here is just quick example
interface MyPathParamsContext {
pathParameters: {
pathParam1: string;
}
}
interface MyQueryStringParamsContext {
queryStringParameters: {
qsParam1: string;
qsParam2: string;
}
}
interface MyBodyContext {
body: {
bodyParam1: string;
bodyParam2: number;
}
}
type MyCustomContext = HTTPContext;
const mySuperSweetFunction = async (event: HTTPEvent, context: MyCustomContext): Promise
return {};
};
export default applyMiddleware(
httpHandler,
withJSONBody,
withParameters({
// These fields should be defined when actually required
requiredPathParams: ['pathParam1'],
requiredJsonBodyParams: ['bodyParam1', 'bodyParam2'],
requiredQueryStringParams: ['qsParam1', 'qsParam2'],
}),
)(mySuperSweetFunction);
`withClientId
Automatically validate required clientId and assign to genieExample:
`typescript
import { applyMiddleware, httpHandler, withClientId, withJSONBody, HTTPContext, ClientIdContext } from '@genie-solutions/lambda-toolbelt';// These interfaces should be in type.ts, here is just quick example
type MyCustomContext = HTTPContext;
const mySuperSweetFunction = async (event: HTTPEvent, context: MyCustomContext): Promise
return {};
};
export default applyMiddleware(
httpHandler,
withJSONBody,
withClientId,
)(mySuperSweetFunction);
`withAuthenticationId
Automatically validate required authenticationId and assign to genieExample:
`typescript
import { applyMiddleware, httpHandler, withAuthenticationId, withJSONBody, HTTPContext, AuthenticationIdContext } from '@genie-solutions/lambda-toolbelt';// These interfaces should be in type.ts, here is just quick example
type MyCustomContext = HTTPContext;
const mySuperSweetFunction = async (event: HTTPEvent, context: MyCustomContext): Promise
return {};
};
export default applyMiddleware(
httpHandler,
withJSONBody,
withAuthenticationId,
)(mySuperSweetFunction);
`HOW TO EXTEND HTTPContext
Many times you will want to custom your own HTTPContext and extends it with many other available Context such as ClientIdContext, JwtContext
To do this, you can leverage HTTPContext to mix n-contexts into One Final InterfaceExample:
`typescript
import {
applyMiddleware,
httpHandler,
withClientId,
withJSONBody,
HTTPEvent,
HTTPContext,
JwtContext,
ClientIdContext
} from '@genie-solutions/lambda-toolbelt';interface MyBodyContext {
body: {
bodyParam1: string;
bodyParam2: number;
}
}
type MyCustomContext = HTTPContext;
const mySuperSweetFunction = async (event: HTTPEvent, context: MyCustomContext): Promise
return {};
};
export default applyMiddleware(
httpHandler,
withJSONBody,
withClientId,
)(mySuperSweetFunction);
`HOW TO SET context.callbackWaitsForEmptyEventLoop TO FALSE
In some case, you may want to set context.callbackWaitsForEmptyEventLoop to false to have a shared instance.
e.g. we need this to connect lambda to MongoDb Atlas https://docs.atlas.mongodb.com/best-practices-connecting-to-aws-lambda/To do this, you must import withWaitForEmptyEventLoopDisabled before httpHandler
Example:
`typescript
import {
applyMiddleware,
httpHandler,
withWaitForEmptyEventLoopDisabled,
} from '@genie-solutions/lambda-toolbelt';export default applyMiddleware(
withWaitForEmptyEventLoopDisabled,
httpHandler,
)(mySuperSweetFunction);
`errorTesting4xx5xx method
This method is designed to go on any AWS API Gateway, to allow us to mock 4XX and 5XX errors to testing.
It can be added to the cloudformation code, to allow each API Gateway to have mock errors.
Whatever you send it, it will return.
Example:
`bash
curl -X POST \
https://fake-api.endpoint.com/testing \
-H 'Accept: /' \
-H 'Content-Type: application/json' \
-H 'Host: api.endpoint.com' \
-d '{
"response": 404
}'
`
This would return a 404 error resposne, with some examples, etc..:
`bash
{"code":404,"body":"\"Returning the code of: 404\"","callWith":{"response":"2XX | 4XX | 5XX | Any status code"},"example":{"response":500}}
`withHttpHandler and httpHandler
They are the same functions.
httpHandler is withHttpHandler exported with the default 200 status code to maintain backwards compatibility. This way httpHandler can be used in the same way.$3
This method provides you with the option to return a status code other that
200 with the response. Add this function to applyMiddleware and specify the status code as a number there:`typescript
import {
applyMiddleware,
withHttpHandler,
} from '@genie-solutions/lambda-toolbelt';export default applyMiddleware(
withHttpHandler({ statusCode: 202 }),
)(myLambdaFunction);
`$3
This method returns
200 unless there's an error. If you don't need to return a specific status code, use this method.`typescript
import {
applyMiddleware,
httpHandler,
} from '@genie-solutions/lambda-toolbelt';export default applyMiddleware(
httpHandler,
)(myLambdaFunction);
`$3
Validates that tenantId in the pathParameters is the same as the tenantId in the roles token.
If the roles tenantId is not found a 403 will be thrown. If the pathParameters does not contain a tenantId a 403 will be thrown. If the tenants don't match then a 403 is returned. You need to use the withRoles and withParameters middleware first.
`typescript
import {
applyMiddleware,
httpHandler,
withParameters,
withRoles,
validateTenant,
} from '@genie-solutions/lambda-toolbelt';export default applyMiddleware(
httpHandler,
withParameters({
requiredPathParams: ['tenantId'],
}),
withRoles,
validateTenant,
)(myLambdaFunction);
``