Description
Ref #445 for the structure of this RFC
Description of the proposal
There should be a consistent way to validate the structures of inputs and outputs for AWS lambdas.
Name of the core utility (and consequently the folders that contain the libraries):
packages/validation
Justification
The "Garbage in, garbage out" principle suggests that we should validate our inputs to prevent "garbage in," and for Lambda, those inputs include events passed to the lambda handler. A short, informal survey of GitHub projects using the CDK's NodejsFunction found that 90% of the studied projects hand-code their validation, indicating little consensus on any singular tool to validate inputs.
Additionally, the Java and Python toolkits saw fit to add validation of not only lambda input but lambda responses.
Validation support should be added to work toward feature parity between the AWS Lambda Powertools libraries and to offer developers a good alternative to hand-coding their validation.
Goals
- Validate incoming events and responses
- Unwrap events before validation applies
- Built-in envelopes to unwrap popular event source payloads
Proposed API
Installation
Yarn
yarn add @aws-lambda-powertools/validation
Npm
npm install @aws-lambda-powertools/validation
Usage
Lambda Handler
import { Validation, Envelope } from "@aws-lambda-powertools/validation";
interface GreetingRequest {
readonly name: string;
}
interface GreetingResponse {
readonly message: string;
}
async function handlerBase(request: GreetingRequest, context: lambda.Context): Promise<GreetingResponse> {
return {
message: `Hello ${request.name}`,
};
}
export const handler = Validation.handler(handlerBase, {
envelope: Envelope.jmesPath("detail"),
// Schemas are JSON Schema
inboundSchema: {
type: "object",
required: ["name"],
properties: {
name: { type: "string" },
},
},
outboundSchema: {
type: "object",
required: ["message"],
properties: {
message: { type: "string" },
},
additionalProperties: false,
},
});
Ad-hoc validation
import { Logger } from "@aws-lambda-powertools/logger";
import { Validator } from "@aws-lambda-powertools/validation";
const logger = new Logger();
interface Person {
readonly name: string;
}
const validator = new Validator<Person>({
schema: {
type: "object",
required: ["name"],
properties: {
name: { type: "string" },
},
},
});
try {
const person: Person = validator.map(JSON.parse(someInput));
logger.info(`Person's name is ${person.name}`);
} catch (e) {
logger.error(`Failure: ${e}`);
}
Survey Results
Obtained by searching GitHub code for NodejsFunction in TypeScript projects. The repositories are from the first twenty results, sorted by "best match." These cases are good enough evidence for me, but perhaps the community can suggest a better way to get this information.
Metadata
Assignees
Labels
Type
Projects
Status
Ideas
Activity