aws-lambda#APIGatewayProxyEvent TypeScript Examples
The following examples show how to use
aws-lambda#APIGatewayProxyEvent.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: auth_get.ts From roamjs-com with MIT License | 6 votes |
handler = async (
event: APIGatewayProxyEvent
): Promise<APIGatewayProxyResult> => {
const S = event.queryStringParameters?.state || '';
const key = {
TableName: "RoamJSAuth",
Key: { id: { S } },
};
return dynamo
.getItem(key)
.promise()
.then((r) => {
if (r.Item) {
if (isAfter(new Date(), addMinutes(new Date(r.Item.date.S), 10))) {
return dynamo
.deleteItem(key)
.promise()
.then(() => bareSuccessResponse(event));
} else {
return {
statusCode: 200,
body: JSON.stringify({ success: false }),
headers: headers(event),
};
}
} else {
return bareSuccessResponse(event);
}
})
.catch((e) => ({
statusCode: 500,
body: e.message,
headers: headers(event),
}));
}
Example #2
Source File: auth.ts From crossfeed with Creative Commons Zero v1.0 Universal | 6 votes |
getTagOrganizations = async (
event: APIGatewayProxyEvent,
id: string
): Promise<string[]> => {
if (!isGlobalViewAdmin(event)) return [];
const tag = await OrganizationTag.findOne(
{ id },
{ relations: ['organizations'] }
);
if (tag) return tag?.organizations.map((org) => org.id);
return [];
}
Example #3
Source File: role-controller.ts From ddd-cqrs-es-aws-sam with MIT License | 6 votes |
listHandler = async (event: APIGatewayProxyEvent, context: Context): Promise<APIGatewayProxyResult> => {
initApplication();
try {
_applicationContainer.logger.debug('Role List Handler Event: %o', event);
const roleListDto = Object.assign(new RoleListDto(), event.queryStringParameters) as RoleListDto;
await validateOrReject(plainToClass(RoleListDto, roleListDto));
const repository = _applicationContainer.get<ProjectionRepository<RoleProjection>>(DynamoProjectionRepository);
const roleProjections = await repository.list(process.env.projectionRolesTable, roleListDto);
return { statusCode: HttpStatus.OK, body: JSON.stringify(roleProjections) };
} catch (error) {
return ApplicationController.handleError(_applicationContainer, error);
}
}
Example #4
Source File: handler.test.ts From serverless-SAM-typescript-boilerplate with Apache License 2.0 | 6 votes |
beforeEach(() => {
/** Create a mock event body */
mockEvent = ({
body: JSON.stringify({
firstName: `John`,
lastName: `Doe`,
email: `[email protected]`,
password: `Abcd1234`,
}),
} as unknown) as APIGatewayProxyEvent;
});
Example #5
Source File: auth_post.ts From roamjs-com with MIT License | 6 votes |
handler = async (
event: APIGatewayProxyEvent
): Promise<APIGatewayProxyResult> => {
const { service, otp, auth } = JSON.parse(event.body);
return dynamo
.putItem({
TableName: "RoamJSAuth",
Item: {
id: { S: `${service}_${otp}` },
auth: { S: auth },
date: { S: new Date().toJSON() },
},
})
.promise()
.then(() => emptyResponse(event));
}
Example #6
Source File: lambda.ts From iplocate with MIT License | 6 votes |
handler = (
event: APIGatewayProxyEvent,
context: Context,
cb: Callback
) => {
context.callbackWaitsForEmptyEventLoop = false;
app.ready((e) => {
if (e) return console.error(e.stack || e);
awsServerlessExpress.proxy(server, event, context, "CALLBACK", cb);
});
}
Example #7
Source File: getPhoto.ts From dynamodb-instagram with MIT License | 6 votes |
main: APIGatewayProxyHandler = async (event: APIGatewayProxyEvent) => {
const { username, photoId } = event.pathParameters
const photo = await getPhoto(username, photoId)
const response = {
statusCode: 200,
body: JSON.stringify({
photo
})
}
return response
}
Example #8
Source File: controller.ts From serverless-dynamodb-api-boilerplate with MIT License | 6 votes |
deleteController = async (
event: APIGatewayProxyEvent,
documentClient: DynamoDB.DocumentClient
) => {
let item = {
id: event.queryStringParameters.id,
status: event.queryStringParameters.status,
date_added: event.queryStringParameters.date_added,
}
const params = ThingModel.delete(item)
const response = await documentClient.delete(params).promise()
return ThingModel.parse(response);
}
Example #9
Source File: helpers.ts From cookiecutter-aws-sam-typescript-layers with MIT License | 6 votes |
export function constructAPIGwEvent(message: any, options: Record<string, any> = {}): APIGatewayProxyEvent {
return {
httpMethod: options.method || 'GET',
path: options.path || '/',
queryStringParameters: options.query || {},
headers: options.headers || {},
body: options.rawBody || JSON.stringify(message),
multiValueHeaders: {},
multiValueQueryStringParameters: {},
isBase64Encoded: false,
pathParameters: options.pathParameters || {},
stageVariables: options.stageVariables || {},
requestContext: options.requestContext || {},
resource: options.resource || '',
}
}
Example #10
Source File: put-item.ts From aws-sam-typescript-layers-example with MIT License | 6 votes |
putItemHandler = async (
event: APIGatewayProxyEvent,
): Promise<APIGatewayProxyResult> => {
if (event.httpMethod !== 'POST') {
throw new Error(`postMethod only accepts POST method, you tried: ${event.httpMethod} method.`);
}
// All log statements are written to CloudWatch
console.info('received:', event);
// Get id and name from the body of the request
const body = JSON.parse(event.body)
const id = body.id;
const name = body.name;
const client = new CustomSqsClient();
const result = await client.send({ id, name });
const response = {
statusCode: 201,
body: JSON.stringify({ MessageId: result.MessageId })
};
// All log statements are written to CloudWatch
console.info(`response from: ${event.path} statusCode: ${response.statusCode} body: ${response.body}`);
return response;
}
Example #11
Source File: controller.ts From serverless-dynamodb-api-boilerplate with MIT License | 6 votes |
getController = async (
event: APIGatewayProxyEvent,
documentClient: DynamoDB.DocumentClient
) => {
let item = {
id: event.queryStringParameters.id,
status: event.queryStringParameters.status,
date_added: event.queryStringParameters.date_added,
}
const params = ThingModel.get(item)
const response = await documentClient.get(params).promise()
return ThingModel.parse(response);
}
Example #12
Source File: get-by-id.ts From aws-sam-typescript-layers-example with MIT License | 6 votes |
getByIdHandler = async (
event: APIGatewayProxyEvent,
): Promise<APIGatewayProxyResult> => {
if (event.httpMethod !== 'GET') {
throw new Error(`getMethod only accept GET method, you tried: ${event.httpMethod}`);
}
// All log statements are written to CloudWatch
console.info('received:', event);
// Get id from pathParameters from APIGateway because of `/{id}` at template.yml
const id = event.pathParameters.id;
const client = new CustomDynamoClient();
const item = await client.read(id);
const response = {
statusCode: 200,
body: JSON.stringify(item)
};
// All log statements are written to CloudWatch
console.info(`response from: ${event.path} statusCode: ${response.statusCode} body: ${response.body}`);
return response;
}
Example #13
Source File: example.ts From cookiecutter-aws-sam-typescript-layers with MIT License | 6 votes |
exampleHandler = async (
event: APIGatewayProxyEvent,
): Promise<APIGatewayProxyResult> => {
// All log statements are written to CloudWatch
console.debug('Received event:', event);
return {
statusCode: 200,
body: JSON.stringify({
message: 'Hello world!',
})
};
}
Example #14
Source File: controller.ts From serverless-dynamodb-api-boilerplate with MIT License | 6 votes |
createController = async (
event: APIGatewayProxyEvent,
documentClient: DynamoDB.DocumentClient
) => {
// Parse string to verified request schema model
const input: Thing = JSON.parse(event.body);
const item = {
id: uuid(),
status: input.status || 'OK',
date_added: (+new Date()).toString(),
name: input.name,
};
const params = ThingModel.put(item);
await documentClient.put(params).promise();
return item;
}
Example #15
Source File: commentOnPhoto.ts From dynamodb-instagram with MIT License | 6 votes |
main: APIGatewayProxyHandler = async (event: APIGatewayProxyEvent) => {
const { username, photoId } = event.pathParameters
const photo = new Photo(username, "", photoId)
const { commentingUsername, content } = JSON.parse(event.body)
const comment = await commentOnPhoto(photo, commentingUsername, content)
const response = {
statusCode: 200,
body: JSON.stringify({
comment
})
}
return response
}
Example #16
Source File: APIGatewayProxyEventSample.ts From serverless-dynamodb-api-boilerplate with MIT License | 6 votes |
APIGatewayProxyEventSample: APIGatewayProxyEvent = {
body: ``,
headers: {},
httpMethod: "POST",
isBase64Encoded: false,
path: "/",
queryStringParameters: {},
pathParameters: {},
stageVariables: {},
multiValueHeaders: {},
requestContext: null,
resource: "/",
multiValueQueryStringParameters: {}
}
Example #17
Source File: helpers.ts From aws-sam-typescript-layers-example with MIT License | 6 votes |
export function constructAPIGwEvent(message: any, options: any = DEFAULT_OPTIONS): APIGatewayProxyEvent {
const opts = Object.assign({}, DEFAULT_OPTIONS, options);
return {
httpMethod: opts.method,
path: opts.path,
queryStringParameters: opts.query,
headers: opts.headers,
body: opts.rawBody || JSON.stringify(message),
multiValueHeaders: {},
multiValueQueryStringParameters: {},
isBase64Encoded: false,
pathParameters: opts.pathParameters || {},
stageVariables: {},
requestContext: null,
resource: null,
}
}
Example #18
Source File: auth.ts From crossfeed with Creative Commons Zero v1.0 Universal | 6 votes |
isOrgAdmin = (
event: APIGatewayProxyEvent,
organizationId?: string
) => {
if (!organizationId || !event.requestContext.authorizer) return false;
for (const role of event.requestContext.authorizer.roles) {
if (role.org === organizationId && role.role === 'admin') return true;
}
return isGlobalWriteAdmin(event);
}
Example #19
Source File: subscriptions_get.ts From roamjs-com with MIT License | 5 votes |
handler = async (
event: APIGatewayProxyEvent
): Promise<APIGatewayProxyResult> =>
getClerkUser(event).then(async (user) => {
if (!user) {
return {
statusCode: 401,
body: "No Active Session",
headers: headers(event),
};
}
const customer = user.privateMetadata?.stripeId as string;
const subs = await stripe.subscriptions
.list({
customer,
})
.then((r) =>
Promise.all(
r.data.map((s) =>
stripe.invoices
.retrieveUpcoming({ subscription: s.id })
.then((i) => ({
invoiceAmountsByPrice: Object.fromEntries(
i.lines.data.map((l) => [l.price.id, l.amount])
),
items: s.items,
date: i.period_end * 1000,
}))
)
)
);
const productIds = subs.flatMap((s) =>
s.items.data.map((i) => i.price.product as string)
);
return stripe.products
.list({ ids: productIds })
.then((products) =>
Object.fromEntries(
products.data.map(({ id, name, description }) => [
id,
{ name, description },
])
)
)
.then((productMap) =>
subs.flatMap((s) => {
return s.items.data.map((i) => ({
...productMap[i.price.product as string],
id: i.id,
amount: s.invoiceAmountsByPrice[i.price.id] / 100,
date: s.date,
}));
})
)
.then((subscriptions) => ({
statusCode: 200,
body: JSON.stringify({
subscriptions,
}),
headers: headers(event),
}))
.catch((e) => ({
statusCode: 500,
body: e.message,
headers: headers(event),
}));
})
Example #20
Source File: index.ts From exevo-pan with The Unlicense | 5 votes |
filterCurrentAuctions = async (
event: APIGatewayProxyEvent,
): Promise<APIGatewayProxyResult> => {
if (!event.body) {
return {
statusCode: 400,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': '*',
'Access-Control-Allow-Credentials': true,
},
body: JSON.stringify({ error: 'empty body' }),
}
}
const currentAuctions = filterOldAuctions(auctions)
const serializedBody: SerializedFilterBody = JSON.parse(event.body as string)
const { filterOptions, sortOptions, paginationOptions } =
deserializeBody(serializedBody)
const filteredAuctions = filterCharacters({
auctions: currentAuctions,
filters: filterOptions,
})
const sortedAuctions = applySort(filteredAuctions, sortOptions)
const paginatedData = paginateData(sortedAuctions, paginationOptions)
const responseBody = {
...paginatedData,
...sortOptions,
}
return {
statusCode: 200,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': '*',
'Access-Control-Allow-Credentials': true,
},
body: JSON.stringify(responseBody),
}
}
Example #21
Source File: lambda-helpers.ts From roamjs-com with MIT License | 5 votes |
userError = (
body: string,
event: APIGatewayProxyEvent
): APIGatewayProxyResult => ({
statusCode: 400,
body,
headers: headers(event),
})
Example #22
Source File: handler.test.ts From serverless-SAM-typescript-boilerplate with Apache License 2.0 | 5 votes |
mockEvent: APIGatewayProxyEvent
Example #23
Source File: auth.ts From crossfeed with Creative Commons Zero v1.0 Universal | 5 votes |
getOrgMemberships = (event: APIGatewayProxyEvent): string[] => {
if (!event.requestContext.authorizer) return [];
return event.requestContext.authorizer.roles.map((role) => role.org);
}
Example #24
Source File: payment-methods_put.ts From roamjs-com with MIT License | 5 votes |
handler = async (
event: APIGatewayProxyEvent
): Promise<APIGatewayProxyResult> =>
getClerkUser(event).then((user) => {
if (!user) {
return {
statusCode: 401,
body: "No Active Session",
headers: headers(event),
};
}
const customer = user?.privateMetadata?.stripeId as string;
const { id } = JSON.parse(event.body || "{}");
if (!id) {
return {
statusCode: 400,
body: "id is required",
headers: headers(event),
};
}
return stripe.paymentMethods.retrieve(id).then((pm) => {
if (!pm.customer) {
return {
statusCode: 400,
body: "No customer attached to payment method",
headers: headers(event),
};
}
if (pm.customer !== customer) {
return {
statusCode: 400,
body: "Payment method not attached to the current user",
headers: headers(event),
};
}
return stripe.customers
.update(pm.customer as string, {
invoice_settings: {
default_payment_method: pm.id,
},
})
.then(() => ({
statusCode: 200,
body: JSON.stringify({ success: true }),
headers: headers(event),
}));
});
})
Example #25
Source File: auth.ts From crossfeed with Creative Commons Zero v1.0 Universal | 5 votes |
isGlobalWriteAdmin = (event: APIGatewayProxyEvent) => {
return event.requestContext.authorizer &&
event.requestContext.authorizer.userType === UserType.GLOBAL_ADMIN
? true
: false;
}
Example #26
Source File: start-service_post.ts From roamjs-com with MIT License | 4 votes |
handler = async (
event: APIGatewayProxyEvent
): Promise<APIGatewayProxyResult> => {
const user = await getClerkUser(event);
if (!user) {
return {
statusCode: 401,
body: "No Active Session",
headers: headers(event),
};
}
const { service = '', extension = service, quantity = 1 } = JSON.parse(event.body || "{}") as {
extension?: string;
service?: string;
quantity?: number;
};
const extensionField = extension
.split("-")
.map((s, i) =>
i == 0 ? s : `${s.substring(0, 1).toUpperCase()}${s.substring(1)}`
)
.join("");
const priceId = await getStripePriceId(extension);
const customer = user.privateMetadata?.stripeId as string;
const usage = await stripe.prices
.retrieve(priceId)
.then((p) => p.recurring?.usage_type);
const line_items = [
usage === "metered"
? { price: priceId }
: { price: priceId, quantity },
];
const finishSubscription = () =>
users
.updateUser(user.id, {
publicMetadata: {
...user.publicMetadata,
[extensionField]: {},
},
})
.then(() => ({
statusCode: 200,
body: JSON.stringify({ success: true }),
headers: headers(event),
}));
const roamjsSubscription = await stripe.subscriptions
.list({ customer })
.then((all) => all.data.find((s) => s.metadata.project === "RoamJS"));
if (roamjsSubscription) {
return stripe.subscriptionItems
.create({
subscription: roamjsSubscription.id,
...line_items[0],
})
.then(finishSubscription);
}
const paymentMethod = await stripe.customers
.retrieve(customer)
.then((c) => c as Stripe.Customer)
.then((c) => c.invoice_settings?.default_payment_method);
const origin = event.headers.Origin || event.headers.origin;
const { active, id, error } = paymentMethod
? await stripe.subscriptions
.create({
customer,
items: line_items,
metadata: {
project: "RoamJS",
},
})
.then((s) => ({ active: true, id: s.id, error: undefined }))
.catch((error) => ({ active: false, id: undefined, error }))
: await stripe.checkout.sessions
.create({
customer,
payment_method_types: ["card"],
line_items,
mode: "subscription",
success_url: `${origin}/extensions/${extension}?success=true`,
cancel_url: `${origin}/extensions/${extension}?cancel=true`,
subscription_data: {
metadata: {
project: "RoamJS",
},
},
metadata: {
extension: extensionField,
userId: user.id,
callback: `${process.env.API_URL}/finish-start-service`,
},
})
.then((session) => ({ id: session.id, active: false, error: undefined }))
.catch((error) => ({ active: false, id: undefined, error }));
if (!active) {
if (id) {
return {
statusCode: 200,
body: JSON.stringify({ sessionId: id }),
headers: headers(event),
};
} else {
console.log(error);
return {
statusCode: 500,
body: "Failed to subscribe to RoamJS extension. Contact [email protected] for help!",
headers: headers(event),
};
}
}
return finishSubscription();
}