Skip to content

Instantly share code, notes, and snippets.

@M1ke
Created September 21, 2022 10:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save M1ke/0a3898d81921981af07a053631ad835e to your computer and use it in GitHub Desktop.
Save M1ke/0a3898d81921981af07a053631ad835e to your computer and use it in GitHub Desktop.
Quick helper functions when testing local serverless applications (Typescript + AWS Lambda) to translate `express` req/res objects into the appropriate types for API Gateway
const apiGWEventFromReq = (req: Request): APIGatewayEvent => {
const [headers, multiValueHeaders] = Object.keys(req.headers).reduce((parts, key) => {
const val = req.headers[key]
if (!val) {
return parts
}
const [headers, multiValueHeaders] = parts
if (Array.isArray(val)) {
multiValueHeaders[key] = val;
} else {
headers[key] = val
}
return [headers, multiValueHeaders]
}, [<Record<string, string>>{}, <Record<string, string[]>>{}])
return {
body: req.body,
headers,
multiValueHeaders,
httpMethod: req.method,
isBase64Encoded: false,
path: req.path,
resource: '',
pathParameters: null,
queryStringParameters: null,
multiValueQueryStringParameters: null,
stageVariables: null,
requestContext: {
accountId: '',
apiId: '',
protocol: '',
httpMethod: '',
authorizer: null,
identity: {
accessKey: null,
accountId: null,
apiKey: null,
apiKeyId: null,
caller: null,
clientCert: null,
cognitoAuthenticationProvider: null,
cognitoAuthenticationType: null,
cognitoIdentityId: null,
cognitoIdentityPoolId: null,
principalOrgId: null,
user: null,
userAgent: null,
userArn: null,
sourceIp: '',
},
path: '',
stage: '',
requestId: '',
requestTimeEpoch: 0,
resourceId: '',
resourcePath: '',
},
}
}
export const sendAPIGWResponse = (apiGWResponse: APIGatewayProxyResult, res: Response) => {
return res.status(apiGWResponse.statusCode).send(apiGWResponse.body)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment