aws-lambda#APIGatewayEvent TypeScript Examples
The following examples show how to use
aws-lambda#APIGatewayEvent.
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: addCartItem.ts From Stripe-shop-backend with MIT License | 6 votes |
addCartItem: Handler = (event: APIGatewayEvent | ScheduledEvent, context: Context, callBack: Callback) => {
const uuid = require('uuid');
const data: PostCartItem = JSON.parse((event as APIGatewayEvent).body);
const timestamp = new Date().getTime();
const params: CartTable = {
TableName: process.env.DYNAMODB_TABLE_CARTITEMS,
Item: {
cartItemId: uuid.v1(),
customerId: (data.customer) ?? uuid.v1(),
productId: data.item,
quantity: 1,
createdAt: timestamp,
updatedAt: timestamp,
},
};
dynamoDb.put(params, (error, result) => {
if (error) {
return errorHandler(callBack, 'ERROR: Couldn\'t add the Cart Item.', error );
}
return successHandler(callBack, {
cartItemId: params.Item.cartItemId,
customerId: params.Item.customerId,
});
});
}
Example #2
Source File: handler.test.ts From serverless-typescript-starter with MIT License | 6 votes |
test("hello", async () => {
const event = { body: "Test Body" } as APIGatewayEvent;
const context = {} as Context;
const response = await handler.hello(event, context);
expect(response.statusCode).toEqual(200);
expect(typeof response.body).toBe("string");
});
Example #3
Source File: handler.ts From antibody-web with MIT License | 6 votes |
baseHandler = async (event: APIGatewayEvent) : Promise<APIGatewayProxyResult> => {
const UPLOAD_BUCKET: string = process.env.UPLOAD_BUCKET as string;
const response = await getNextResult();
// Return empty success if no images in queue
if (!response) {
return {
statusCode: 204,
body: "",
headers: config.defaultHeaders
};
}
let { nextResultId, receiptHandle } = response as NextResultResponse;
const { downloadUrl } = await getUrls(UPLOAD_BUCKET, nextResultId, { download: true, upload: false });
return {
statusCode: 200,
body: JSON.stringify({
url: downloadUrl,
guid: nextResultId,
receiptHandle
}),
headers: config.defaultHeaders
};
}
Example #4
Source File: token.ts From tokenlog with MIT License | 6 votes |
export async function handler(event: APIGatewayEvent, context: Context) {
if (event.httpMethod !== 'GET') return { statusCode: 405, body: 'Method Not Allowed' };
const address = event.queryStringParameters?.address ?? '';
if (!address) return { statusCode: 400, body: 'Bad Request' };
const repository = new TokenRepository();
const data = await repository.GetTokenInfo(address);
return {
statusCode: 200,
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
};
}
Example #5
Source File: poll.ts From serverless-typescript-monorepo-example with MIT License | 6 votes |
vote = async (event: APIGatewayEvent): Promise<Response> => {
if (!event.body) {
return response(failure("Please provide an answer id"));
}
if (!event.pathParameters?.id) {
return response(failure("Please provide a poll id"));
}
const { option } = JSON.parse(event.body);
const result = await countVote(event.pathParameters.id, Number(option));
return response(result);
}
Example #6
Source File: cancel.ts From ethgaswatch with MIT License | 6 votes |
export async function handler(event: APIGatewayEvent, context: Context) {
context.callbackWaitsForEmptyEventLoop = false;
const data = event.queryStringParameters;
console.log(data);
if (!data.email || !data.id)
return { statusCode: 400, body: "Bad Request" };
const result = await UpdateUserAlert(data.id, { disabled: true });
if (!result) return { statusCode: 500, body: "Error updating user" };
return {
statusCode: 200,
body: `Ok. Email removed`
}
}
Example #7
Source File: repos.ts From tokenlog with MIT License | 6 votes |
export async function handler(event: APIGatewayEvent, context: Context) {
if (event.httpMethod !== 'GET') return { statusCode: 405, body: 'Method Not Allowed' };
context.callbackWaitsForEmptyEventLoop = false;
const data = await repository.GetReposWithVotes();
return {
statusCode: 200,
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
};
}
Example #8
Source File: trend.ts From ethgaswatch with MIT License | 6 votes |
export async function handler(event: APIGatewayEvent, context: Context) {
context.callbackWaitsForEmptyEventLoop = false;
const qs = event.queryStringParameters;
let data: TrendChartData = null;
const days = parseInt(qs.days);
if (!isNaN(days)) {
data = await GetDailyAverageGasData(days);
}
const hours = parseInt(qs.hours);
if (!isNaN(hours)) {
data = await GetHourlyAverageGasData(hours);
}
if (isNaN(days) && isNaN(hours))
return { statusCode: 400, body: "Bad Request" };
return {
statusCode: 200,
body: JSON.stringify(data),
}
}
Example #9
Source File: votes.ts From tokenlog with MIT License | 6 votes |
export async function handler(event: APIGatewayEvent, context: Context) {
if (event.httpMethod !== 'GET') return { statusCode: 405, body: 'Method Not Allowed' };
const org = event.queryStringParameters?.org ?? '';
const repo = event.queryStringParameters?.repo ?? '';
if (!org || !repo) return { statusCode: 400, body: 'Bad Request' };
let since: number | undefined;
if (event.queryStringParameters?.days) {
const days = parseInt(event.queryStringParameters?.days);
if (!isNaN(days)) {
since = moment().subtract(days, 'days').valueOf();
}
}
context.callbackWaitsForEmptyEventLoop = false;
const data = await repository.GetVotes(org, repo, since);
return {
statusCode: 200,
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
};
}
Example #10
Source File: alerts.ts From ethgaswatch with MIT License | 6 votes |
export async function handler(event: APIGatewayEvent, context: Context) {
context.callbackWaitsForEmptyEventLoop = false;
const data = await GetUserAlertsData();
return {
statusCode: 200,
body: JSON.stringify(data),
headers: {
'Cache-Control': 'public, max-age=1800',
}
}
}
Example #11
Source File: helpers.ts From sleekypay with MIT License | 6 votes |
export function getResultPayload(
event: APIGatewayEvent,
fallbackBody: {}): APIGatewayProxyResult {
const statusCodeString = event.queryStringParameters['statusCode'];
if (statusCodeString) {
const statusCode = parseInt(statusCodeString, 10)
if (statusCode > 299) {
return {
statusCode,
body: ''
}
}
}
return {
statusCode: 200,
body: JSON.stringify(fallbackBody)
}
}
Example #12
Source File: listener.ts From Stripe-shop-backend with MIT License | 6 votes |
webhookListener: Handler = async (event: APIGatewayEvent | ScheduledEvent, context: Context, callBack: Callback) => {
const data = JSON.parse((event as APIGatewayEvent).body);
console.log({ "Webhook data": data })
return successHandler(callBack, {
received: true,
});
}
Example #13
Source File: unit.ts From cdk-cognito-idp with MIT No Attribution | 6 votes |
/**
* The event handler.
*/
public async handle(event: APIGatewayEvent): Promise<APIEventResponse> {
try {
if (event.path === 'succeed') {
return this.success('Ok');
} else {
throw Error('fail');
}
} catch (ex) {
return this.failure(ex);
}
}
Example #14
Source File: forgot-password.ts From midway with MIT License | 6 votes |
handler = async (event: APIGatewayEvent): Promise<any> => {
if (event.httpMethod !== "POST" || !event.body) return statusReturn(400, '')
try {
data = JSON.parse(event.body)
} catch (error) {
console.log('JSON parsing error:', error);
return statusReturn(400, { error: 'Bad Request Body' })
}
const payload = preparePayload(CUSTOMER_RECOVERY_QUERY, {
email: data.email
})
try {
const customer = await axios({
url: SHOPIFY_GRAPHQL_URL,
method: 'POST',
headers: shopifyConfig,
data: JSON.stringify(payload)
})
const {
data,
errors
} = customer.data
const { customerRecover } = data
if (customerRecover && customerRecover.userErrors.length > 0) {
throw customerRecover.userErrors
} else if (errors && errors.length > 0) {
throw errors
} else {
return statusReturn(200, { customerRecover })
}
} catch (err) {
return statusReturn(500, { error: err[0].message })
}
}
Example #15
Source File: user-get.ts From cdk-cognito-idp with MIT No Attribution | 6 votes |
/**
* The event handler.
*/
public async handle(event: APIGatewayEvent): Promise<APIEventResponse> {
try {
const userId = event.pathParameters?.userId;
if (!userId) {
return this.failure(null, 400, 'No userId provided');
}
// Make sure user is logged in as super user
if (!this.isSuperAdmin(event)) {
return this.failure(null, 403, 'Not authorized!');
}
const user = await this.db.userGet(userId);
if (!user) {
return this.failure(null, 404, 'No such user');
}
return this.success(user);
} catch (ex) {
return this.failure(ex);
}
}
Example #16
Source File: activate.ts From midway with MIT License | 6 votes |
handler = async (event: APIGatewayEvent): Promise<any> => {
if (event.httpMethod !== 'POST' || !event.body) return statusReturn(400, '')
try {
data = JSON.parse(event.body)
} catch (error) {
console.log('JSON parsing error:', error);
return statusReturn(400, { error: 'Bady Request Body' })
}
const payload = preparePayload(CUSTOMER_ACTIVATE_QUERY, {
id: data.id,
input: data.input
})
try {
const customer = await axios({
url: SHOPIFY_GRAPHQL_URL,
method: 'POST',
headers: shopifyConfig,
data: JSON.stringify(payload)
})
if (customer.data.data.customerActivate.userErrors.length > 0) {
throw customer.data.data.customerActivate.userErrors
} else {
const cusRes = customer.data.data.customerActivate
return statusReturn(200, { data: cusRes })
}
} catch (err) {
return statusReturn(500, { error: err[0].message })
}
}
Example #17
Source File: iframely_post.ts From roamjs-com with MIT License | 6 votes |
handler = async (
event: APIGatewayEvent
): Promise<APIGatewayProxyResult> => {
const { url, iframe = 'card-small' } = JSON.parse(event.body);
return axios
.get(
`http://iframe.ly/api/oembed?url=${url}&api_key=${process.env.IFRAMELY_API_KEY}&iframe=${iframe}`
)
.then((r) => ({
statusCode: 200,
body: JSON.stringify(r.data),
headers,
}))
.catch((e: Error & AxiosError) => ({
statusCode: e.response?.status || 500,
body: e.response?.data ? JSON.stringify(e.response.data) : e.message,
headers,
}));
}
Example #18
Source File: unit.test.ts From cdk-cognito-idp with MIT No Attribution | 6 votes |
test('Lambda handler works', async () => {
let resp = await handler({
path: 'succeed',
httpMethod: 'GET',
queryStringParameters: null,
body: 'abc'
} as APIGatewayEvent);
expect(resp.statusCode).toBe(200);
resp = await handler({
path: 'fail',
httpMethod: 'GET',
queryStringParameters: null,
body: 'abc'
} as APIGatewayEvent);
expect(resp.statusCode).toBeGreaterThanOrEqual(400);
});
Example #19
Source File: iframely_post.ts From roamjs-com with MIT License | 6 votes |
handler = async (
event: APIGatewayEvent
): Promise<APIGatewayProxyResult> => {
const { url, iframe = 'card-small' } = JSON.parse(event.body);
return axios
.get(
`http://iframe.ly/api/oembed?url=${url}&api_key=${process.env.IFRAMELY_API_KEY}&iframe=${iframe}`
)
.then((r) => ({
statusCode: 200,
body: JSON.stringify(r.data),
headers: headers(event),
}))
.catch((e: Error & AxiosError) => ({
statusCode: e.response?.status || 500,
body: e.response?.data ? JSON.stringify(e.response.data) : e.message,
headers: headers(event),
}));
}
Example #20
Source File: handler.ts From cdk-cognito-idp with MIT No Attribution | 6 votes |
/**
*
*/
public async getLoggedInUser(event:APIGatewayEvent): Promise<User | null> {
const claims = event.requestContext?.authorizer?.claims;
if (!claims) {
throw new Error('Missing claims from event');
}
console.info({claims});
let username = claims['cognito:username'] as string;
username = username.replace('AmazonFederate_', '');
const user = await this.db.userGetByUsername(username);
if (!user) {
return null;
}
// For some reason we don't get the name and email when we validate the token in decode-verify-jwt.
if (user.emailAddress !== claims.email || user.firstName !== claims.given_name || user.lastName !== claims.family_name) {
console.log('Fixing user info');
// Update anything that changed, ignore anything that is blank
user.emailAddress = claims.email || user.emailAddress;
user.firstName = claims.given_name || user.firstName;
user.lastName = claims.family_name || user.lastName;
await this.db.userSave(user);
}
return user;
}
Example #21
Source File: creator.ts From serverless-typescript-monorepo-example with MIT License | 6 votes |
toPoll = (event: APIGatewayEvent): Poll | string => {
if (!event.body) {
return "Please provide data.";
}
const poll = JSON.parse(event.body) as Poll;
if (!poll.topic) {
return "Please provide a topic.";
}
if (!poll.options || poll.options.length <= 1) {
return "Please provide more than one answer";
}
return poll;
}
Example #22
Source File: userbyusername-get.ts From cdk-cognito-idp with MIT No Attribution | 6 votes |
/**
* The event handler.
*/
public async handle(event: APIGatewayEvent): Promise<APIEventResponse> {
try {
const username = event?.pathParameters?.username;
if (!username) {
return this.failure(null, 400, 'No username provided');
}
// Make sure user is logged in as super user
if (!this.isSuperAdmin(event)) {
return this.failure(null, 403, 'Not authorized!');
}
const user = await this.db.userGetByUsername(username);
return this.success(user);
} catch (ex) {
return this.failure(ex);
}
}
Example #23
Source File: slack.ts From flect-chime-sdk-demo with Apache License 2.0 | 5 votes |
module.exports.handler = (event: APIGatewayEvent, context: LambdaContext, callback: any) => {
console.log("⚡️ Bolt app is running!");
console.log("Event", JSON.stringify(event));
console.log("Context", JSON.stringify(context));
console.log(`resource: ${event.resource}`);
if (event.resource === "/slack/api/{operation}") {
const operation = event.pathParameters["operation"];
console.log(`resource: ${operation}`);
if (operation === "decodeInformation") {
console.log(`body: ${event.body}`);
const token = JSON.parse(event.body)["token"];
console.log(`token: ${token}`);
const urlEncrypter = new Encrypter<UserInformation>({
password: process.env.SLACK_APP_DB_PASSWORD || "pass",
salt: process.env.SLACK_APP_DB_SALT || "salt",
secret: process.env.SLACK_APP_DB_SECRET || "secret",
expireSec: 60 * 60, // 60min
});
const userInfo = urlEncrypter.decodeInformation(token);
console.log(`userInfo: ${JSON.stringify(userInfo)}`);
var response = {
statusCode: 200,
headers: {
"Access-Control-Allow-Headers": "Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token",
"Access-Control-Allow-Methods": "*",
"Access-Control-Allow-Origin": "*",
},
body: JSON.stringify({
success: true,
code: "SUCCESS",
data: userInfo,
}),
isBase64Encoded: false,
};
callback(null, response);
}
} else {
awsServerlessExpress.proxy(server, event, context);
}
};
Example #24
Source File: user-post.ts From cdk-cognito-idp with MIT No Attribution | 5 votes |
/**
* The event handler.
*/
public async handle(event: APIGatewayEvent): Promise<APIEventResponse> {
try {
const loggedInUser = await this.getLoggedInUser(event);
console.info({loggedInUser});
if (event.body) {
const user = JSON.parse(event.body) as User;
// Make sure user is logged in as super user or this is the user being edited
if (!(loggedInUser?.isSuperAdmin || loggedInUser?.username === user.username)) {
return this.failure(null, 403, 'Not authorized!');
}
let priorUser;
if (user.id) {
priorUser = await this.db.userGet(user.id);
}
// Super admin can only be done manually in DynamoDB.
// This isn't technically necessary since db does not update this field
if ( (!priorUser && user.isSuperAdmin) ||
(user.isSuperAdmin && !priorUser?.isSuperAdmin) ) {
util.Log.Error(`User ${loggedInUser.username} trying to set super admin`);
return this.failure(null, 403, 'Not Authorized');
}
// Save the user
return this.success(await this.db.userSave(user));
} else {
return this.failure(null, 400, 'No user submitted');
}
} catch (ex) {
return this.failure(ex);
}
}
Example #25
Source File: average.ts From ethgaswatch with MIT License | 5 votes |
export async function handler(event: APIGatewayEvent, context: Context) {
context.callbackWaitsForEmptyEventLoop = false;
const days = 7
const hours = 24
const total = days * hours
const gasData = await GetHourlyAverage(total)
const xDayOfTheWeek = new Array(days).fill(0).map((_, i) => moment().subtract(i, 'd').format('dddd')).reverse()
const weekDays = xDayOfTheWeek.map((i) => moment().day(i).weekday())
const yHoursInTheDay = new Array(hours).fill(0).map((_, i) => `${i}:00`)
const hoursInTheDay = new Array(hours).fill(0).map((_, i) => i)
// mongo days = 1-7 (starting at Sunday)
// moment days = 0-6 (starting at Sunday)
const current = moment()
const data = hoursInTheDay
.map((hourOfTheDay) => {
return weekDays
.map((weekDay) => {
// timezones? GMT ?
if (weekDay === current.weekday() && hourOfTheDay > current.hour() - 1) {
return null
}
const value = gasData.find(i => i.day === (weekDay + 1) && i.hour === hourOfTheDay)
return value ? Math.floor(value.avg) : undefined
})
}
)
const response = {
x: xDayOfTheWeek,
y: yHoursInTheDay,
data
}
return {
statusCode: 200,
body: JSON.stringify(response),
}
}
Example #26
Source File: user-get.ts From cdk-cognito-idp with MIT No Attribution | 5 votes |
handler = async (event: APIGatewayEvent) => {
const h = new UserGetHandler();
return h.handle(event);
}
Example #27
Source File: startPayment.ts From Stripe-shop-backend with MIT License | 5 votes |
startPayment: Handler = async (event: APIGatewayEvent | ScheduledEvent, context: Context, callBack: Callback) => {
const {
customerId,
payment_method_types,
capture_method = 'automatic',
billing_details=undefined,
saveCustomer=false,
}: any = JSON.parse((event as APIGatewayEvent).body);
try {
const items = await getCustomerItems(customerId);
if (! items.length) {
return errorHandler(
callBack,
'ERROR startPayment FAILED!',
'Your Cart is Empty',
);
};
const products = await getItemProductAmounts(items);
const total: number = products.reduce((acc, prod) => acc += prod.amount, 0);
const stripePI: PaymentInput = {
amount: total,
currency: 'usd',
}
if (payment_method_types) {
stripePI.payment_method_types = payment_method_types;
}
if (capture_method) {
stripePI.capture_method = capture_method;
}
const results: Validation = validatePaymentIntent(stripePI);
if (!results.isValid) {
return errorHandler(
callBack,
'ERROR The PaymentIntent contains invalid data!',
results.errors,
);
};
const stripe = new Stripe(process.env.STRIPE_API_KEY, {
apiVersion: process.env.STRIPE_API_VERSION,
typescript: true,
});
if (saveCustomer) {
if(billing_details) {
const stripeCustomer = await createCustomer(billing_details);
results.params.customer = stripeCustomer.id;
}
}
const paymentIntent = await stripe.paymentIntents.create(results.params);
return successHandler(
callBack,
{
message: 'startPayment Created!',
paymentIntent,
});
}
catch(error) {
return errorHandler(
callBack,
'ERROR startPayment FAILED!',
error
);
}
}
Example #28
Source File: unit.ts From cdk-cognito-idp with MIT No Attribution | 5 votes |
handler = async (event: APIGatewayEvent) => {
const h = new UnitHandler();
return h.handle(event);
}
Example #29
Source File: settings.ts From tokenlog with MIT License | 5 votes |
export async function handler(event: APIGatewayEvent, context: Context) {
if (event.httpMethod !== 'GET') return { statusCode: 405, body: 'Method Not Allowed' };
context.callbackWaitsForEmptyEventLoop = false;
const owner = event.queryStringParameters?.owner ?? '';
const repo = event.queryStringParameters?.repo ?? '';
if (!owner || !repo) return { statusCode: 400, body: 'Bad Request' };
let chainId = 1;
if (event.queryStringParameters?.chainId && !isNaN(Number(event.queryStringParameters?.chainId))) {
chainId = Number(event.queryStringParameters?.chainId);
}
const cacheKey = `repoSettings::${owner}-${repo}-${chainId}`;
console.log('GET RepositorySettings', owner, repo);
if (repositorySettings[cacheKey]) {
console.log('RETURN Cached settings');
return {
statusCode: 200,
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(repositorySettings[cacheKey]),
};
}
let settings = RepoConfigs.find((i) => i.org === owner && i.repo === repo) as RepositorySettings;
if (!settings) {
try {
const octokit = new Octokit({
auth: AppConfig.GITHUB_ACCESS_TOKEN,
});
const result: any = await octokit.repos.getContent({ owner, repo, path: 'tokenlog.json' });
if (result.status !== 200) throw new Error("Couldn't retrieve tokenlog config");
const content = Buffer.from(result.data.content, 'base64').toString();
settings = JSON.parse(content) as RepositorySettings;
} catch {
console.error("Couldn't retrieve tokenlog config. The file likely doesn't exist at the requested repository.");
}
}
if (settings) {
const chain = settings.chainId || chainId;
if (settings.tokenAddress) {
console.log('GET TokenInfo', settings.tokenAddress, chain);
settings.token = await VotingService.GetTokenInfo(settings.tokenAddress, chain);
} else if (settings.tokenAddresses) {
const tokens = new Array<Token>();
for (let index = 0; index < settings.tokenAddresses.length; index++) {
const address = settings.tokenAddresses[index];
console.log('GET TokenInfo', address, chain);
const token = await VotingService.GetTokenInfo(address, chain);
if (token) {
tokens.push(token);
}
}
settings.tokens = tokens;
}
}
repositorySettings[cacheKey] = settings;
console.log('CACHE RepositorySettings', cacheKey, repositorySettings[cacheKey]);
return {
statusCode: 200,
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(settings),
};
}