aws-lambda#Handler TypeScript Examples
The following examples show how to use
aws-lambda#Handler.
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: getProducts.ts From Stripe-shop-backend with MIT License | 6 votes |
getProducts: Handler = (event: APIGatewayEvent | ScheduledEvent, context: Context, callBack: Callback) => {
const limit: number = 10;
const params = {
TableName: process.env.DYNAMODB_TABLE_PRODUCTS,
Select: 'ALL_ATTRIBUTES',
};
console.log('inside getProducts', params);
dynamoDb.scan(params, (error, result) => {
if (error) {
return errorHandler(callBack, 'ERROR: Couldn\'t fetch the products.', error );
}
return successHandler(callBack, result);
});
}
Example #2
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 #3
Source File: connect.ts From Stripe-shop-backend with MIT License | 6 votes |
createTerminalConnection: Handler = async (event: APIGatewayEvent | ScheduledEvent, context: Context, callBack: Callback) => {
const config: Stripe.StripeConfig = {
apiVersion: process.env.STRIPE_API_VERSION,
typescript: true,
};
const stripe = new Stripe(process.env.STRIPE_API_KEY, config);
console.log('config', process.env);
try {
const terminalToken = await stripe.terminal.connectionTokens.create();
console.log('terminalToken', terminalToken);
return successHandler(callBack, {
success: true,
message: 'Terminal Connection Created!',
terminalToken: terminalToken,
});
} catch (err) {
return errorHandler(callBack, 'Terminal Connection FAILED!', err);
}
}
Example #4
Source File: capture.ts From Stripe-shop-backend with MIT License | 6 votes |
capturePaymentIntent: Handler = async (event: APIGatewayEvent | ScheduledEvent, context: Context, callBack: Callback) => {
const config: Stripe.StripeConfig = {
apiVersion: process.env.STRIPE_API_VERSION,
typescript: true,
};
const stripe = new Stripe(process.env.STRIPE_API_KEY, config);
console.log('config', config);
const data = JSON.parse((event as APIGatewayEvent).body);
try {
const paymentIntent = await stripe.paymentIntents.capture(data.pi_id);
console.log('paymentIntent capture', paymentIntent);
return successHandler(callBack,{
success: true,
message: 'SUCCESS payment intent captured!',
paymentIntent: paymentIntent,
});
} catch (err) {
return errorHandler(callBack, 'FAILURE payment intent not captured!', err);
}
}
Example #5
Source File: getPaymentIntents.ts From Stripe-shop-backend with MIT License | 6 votes |
getPaymentIntents: Handler = async (event: APIGatewayEvent | ScheduledEvent, context: Context, callBack: Callback) => {
const stripe = new Stripe(process.env.STRIPE_API_KEY, {
apiVersion: process.env.STRIPE_API_VERSION,
typescript: true,
});
const limit: number = 10;
const paymentIntents = await stripe.paymentIntents.list(
{
limit,
}
);
return callBack(null, {
statusCode: 200,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': true,
},
body: JSON.stringify({
message: 'List first ' + limit + ' Payment Intents!',
PaymentIntent: paymentIntents,
},
null,
2,
),
});
}
Example #6
Source File: createPaymentIntent.ts From Stripe-shop-backend with MIT License | 6 votes |
createPaymentIntent: Handler = async (event: APIGatewayEvent | ScheduledEvent, context: Context, callBack: Callback) => {
const stripe = new Stripe(process.env.STRIPE_API_KEY, {
apiVersion: process.env.STRIPE_API_VERSION,
typescript: true,
});
const requestData: any = JSON.parse((event as APIGatewayEvent).body);
const results = validatePaymentIntent(requestData);
if (! results.isValid) {
return errorHandler(
callBack,
'ERROR The PaymentIntent contains invalid data!',
results.errors,
);
}
try {
const paymentIntent = await stripe.paymentIntents.create(results.params);
return successHandler(
callBack,
{
message: 'Payment Intent Created!',
PaymentIntent: paymentIntent,
});
}
catch(error) {
return errorHandler(
callBack,
'ERROR Payment Intent Creation FAILED!',
error
);
}
}
Example #7
Source File: getOrder.ts From Stripe-shop-backend with MIT License | 6 votes |
getOrder: Handler = (event: APIGatewayEvent | ScheduledEvent, context: Context, callBack: Callback) => {
const data = JSON.parse((event as APIGatewayEvent).body);
const params = {
TableName: process.env.DYNAMODB_TABLE_ORDERS,
Key: {
orderId: data.orderId,
},
};
dynamoDb.get(params, (error, result) => {
// handle potential errors
if (error) {
console.error(error);
return errorHandler(callBack, 'ERROR: Couldn\'t fetch the order', error );
}
// create a response
return successHandler(callBack, result);
});
}
Example #8
Source File: addOrder.ts From Stripe-shop-backend with MIT License | 6 votes |
addOrder: Handler = (event: APIGatewayEvent | ScheduledEvent, context: Context, callBack: Callback) => {
const data: Order = JSON.parse((event as APIGatewayEvent).body);
const timestamp = new Date().getTime();
const params: OrdersTable = {
TableName: process.env.DYNAMODB_TABLE_ORDERS,
Item: {
orderId: uuid.v1(),
customerId: data.customerId,
products: data.products,
createdAt: timestamp,
updatedAt: timestamp,
status: "ordered",
},
};
dynamoDb.put(params, (error, result) => {
// handle potential errors
if (error) {
return errorHandler(callBack, 'ERROR: Couldn\'t create an order', error );
}
return successHandler(callBack, result);
});
}
Example #9
Source File: importCustomers.ts From Stripe-shop-backend with MIT License | 6 votes |
importCustomers: Handler = (event: APIGatewayEvent | ScheduledEvent, context: Context, callBack: Callback) => {
const data: ImportCustomers = JSON.parse((event as APIGatewayEvent).body);
const params: CustomerTable = {
TableName: process.env.DYNAMODB_TABLE_CUSTOMERS,
};
const errors: string[] = [];
const results: string[] = [];
for(let i = 0; i< data.Count; i++) {
params.Item = data.Items[i];
dynamoDb.put(params, (error, result) => {
if (error) {
errors.push(params.Item.name);
}
else {
results.push(params.Item.name);
}
});
}
return successHandler(callBack, { errors, results });
}
Example #10
Source File: getCustomers.ts From Stripe-shop-backend with MIT License | 6 votes |
getCustomers: Handler = (event: APIGatewayEvent | ScheduledEvent, context: Context, callBack: Callback) => {
const data = JSON.parse((event as APIGatewayEvent).body);
const params = {
TableName: process.env.DYNAMODB_TABLE_CUSTOMERS,
Select: 'ALL_ATTRIBUTES',
};
dynamoDb.scan(params, (error, result) => {
if (error) {
console.error(error);
return errorHandler(callBack, 'ERROR: Couldn\'t fetch the customer', error );
}
return successHandler(callBack, result);
});
}
Example #11
Source File: getCustomer.ts From Stripe-shop-backend with MIT License | 6 votes |
getCustomer: Handler = (event: APIGatewayEvent | ScheduledEvent, context: Context, callBack: Callback) => {
const data = JSON.parse((event as APIGatewayEvent).body);
const params = {
TableName: process.env.DYNAMODB_TABLE_CUSTOMERS,
Key: {
customerId: data.customerId,
},
};
dynamoDb.get(params, (error, result) => {
if (error) {
console.error(error);
return errorHandler(callBack, 'ERROR: Couldn\'t fetch the customer', error );
}
return successHandler(callBack, result);
});
}
Example #12
Source File: addCustomer.ts From Stripe-shop-backend with MIT License | 6 votes |
addCustomer: Handler = async (event: APIGatewayEvent | ScheduledEvent, context: Context, callBack: Callback) => {
const data: CustomerInput & saveCustomer = JSON.parse((event as APIGatewayEvent).body);
console.log('incomming data', data);
const validCustomer: validCustomer = validateCustomer(data);
if (! validCustomer.isValid) {
return errorHandler(callBack, 'ERROR: Customer contains invalid data.', validCustomer.error );
}
try {
const stripeCustomer = (data.isSaveCustomer === 1) && await upsertToStripe(validCustomer);
validCustomer.params.StripeCustomerId = (data.isSaveCustomer) ? stripeCustomer.id : '';
const params: CustomerTable = {
TableName: process.env.DYNAMODB_TABLE_CUSTOMERS,
Item: validCustomer.params,
};
const savedData = await upsert(params);
console.log('savedData', savedData);
return successHandler(
callBack,
{
message: 'Stripe Customer Created!',
id: params.Item.customerId,
stripeCustomer: stripeCustomer,
});
}
catch(error) {
return errorHandler(
callBack,
'ERROR Customer Creation FAILED!',
error
);
}
}
Example #13
Source File: importProducts.ts From Stripe-shop-backend with MIT License | 6 votes |
importProducts: Handler = (event: APIGatewayEvent | ScheduledEvent, context: Context, callBack: Callback) => {
const data: ImportProduct = JSON.parse((event as APIGatewayEvent).body);
const params: ProductTable = {
TableName: process.env.DYNAMODB_TABLE_PRODUCTS,
};
const errors: string[] = [];
const results: string[] = [];
for(let i = 0; i< data.Count; i++) {
params.Item = data.Items[i];
dynamoDb.put(params, (error, result) => {
if (error) {
errors.push(params.Item.name);
}
else {
results.push(params.Item.name);
}
});
}
return successHandler(callBack, { errors, results });
}
Example #14
Source File: bastion.ts From crossfeed with Creative Commons Zero v1.0 Universal | 6 votes |
handler: Handler = async (event) => {
if (event.mode === 'db') {
const connection = await connectToDatabase(true);
const res = await connection.query(event.query);
console.log(res);
} else if (event.mode === 'es') {
if (event.query === 'delete') {
const client = new ESClient();
await client.deleteAll();
console.log('Index successfully deleted');
} else {
console.log('Query not found: ' + event.query);
}
} else {
console.log('Mode not found: ' + event.mode);
}
}
Example #15
Source File: getCarts.ts From Stripe-shop-backend with MIT License | 6 votes |
getCarts: Handler = async (event: APIGatewayEvent | ScheduledEvent, context: Context, callBack: Callback) => {
const data = JSON.parse((event as APIGatewayEvent).body);
const items = await getCustomerItems(data.customerId);
return successHandler(
callBack,
items,
);
}
Example #16
Source File: makeGlobalAdmin.ts From crossfeed with Creative Commons Zero v1.0 Universal | 6 votes |
handler: Handler = async (event) => {
await connectToDatabase(true);
if (event.email) {
const user = await User.findOne({
email: event.email
});
if (user) {
user.userType = event.role || UserType.GLOBAL_ADMIN;
await User.save(user);
}
}
}
Example #17
Source File: updateScanTaskStatus.ts From crossfeed with Creative Commons Zero v1.0 Universal | 6 votes |
handler: Handler<EventBridgeEvent> = async (
event: EventBridgeEvent
) => {
const { taskArn, lastStatus } = event.detail;
await connectToDatabase();
const scanTask = await pRetry(
() =>
ScanTask.findOne({
fargateTaskArn: taskArn
}),
{ retries: 3 }
);
if (!scanTask) {
throw new Error(`Couldn't find scan with task arn ${taskArn}.`);
}
const oldStatus = scanTask.status;
if (lastStatus === 'RUNNING') {
scanTask.status = 'started';
} else if (lastStatus === 'STOPPED') {
if (event.detail.containers![0]?.exitCode === 0) {
scanTask.status = 'finished';
} else {
scanTask.status = 'failed';
}
scanTask.output = `${event.detail.stopCode}: ${event.detail.stoppedReason}`;
scanTask.finishedAt = new Date();
} else {
return;
}
console.log(
`Updating status of ScanTask ${scanTask.id} from ${oldStatus} to ${scanTask.status}.`
);
await scanTask.save();
}
Example #18
Source File: index.ts From aws-nestjs-starter with The Unlicense | 6 votes |
bootstrapServer = async (): Promise<Handler> => {
const expressApp = express();
const app = await NestFactory.create(
AppModule,
new ExpressAdapter(expressApp),
);
app.useGlobalPipes(new ValidationPipe({ forbidUnknownValues: true }));
app.enableCors();
await app.init();
return serverlessExpress({
app: expressApp,
});
}
Example #19
Source File: addBusiness.ts From Stripe-shop-backend with MIT License | 6 votes |
addBusiness: Handler = async (event: APIGatewayEvent | ScheduledEvent, context: Context, callBack: Callback) => {
const stripe = new Stripe(process.env.STRIPE_API_KEY, {
apiVersion: process.env.STRIPE_API_VERSION,
typescript: true,
});
const data: BusinessInput = JSON.parse((event as APIGatewayEvent).body);
const validBusiness: validBusiness = validateBusiness(data);
if (!validBusiness.isValid) {
return errorHandler(callBack, 'ERROR: Business contains invalid data.', validBusiness.errors);
}
try {
// const stripeBusiness: Stripe.Business = await createBusiness(stripe, validBusiness.params);
// validBusiness.params.StripeBusinessId = stripeBusiness.id;
const params: BusinessTable = {
TableName: process.env.DYNAMODB_TABLE_BUSINESSES,
Item: validBusiness.params,
};
const savedData = await upsert(params);
console.log('savedData', savedData);
return successHandler(
callBack,
{
message: 'Stripe Business Created!',
business: params.Item,
});
} catch (error) {
return errorHandler(
callBack,
'ERROR Business Creation FAILED!',
error
);
}
}
Example #20
Source File: getBusiness.ts From Stripe-shop-backend with MIT License | 6 votes |
getBusiness: Handler = (event: APIGatewayEvent | ScheduledEvent, context: Context, callBack: Callback) => {
const data = JSON.parse((event as APIGatewayEvent).body);
const params = {
TableName: process.env.DYNAMODB_TABLE_BUSINESSES,
Key: {
businessId: data.businessId,
},
};
dynamoDb.get(params, (error, result) => {
if (error) {
console.error(error);
return errorHandler(callBack, 'ERROR: Couldn\'t fetch the business', error );
}
return successHandler(callBack, result);
});
}
Example #21
Source File: getBusinesses.ts From Stripe-shop-backend with MIT License | 6 votes |
getBusinesses: Handler = (event: APIGatewayEvent | ScheduledEvent, context: Context, callBack: Callback) => {
const data = JSON.parse((event as APIGatewayEvent).body);
const params = {
TableName: process.env.DYNAMODB_TABLE_BUSINESSES,
Select: 'ALL_ATTRIBUTES',
};
dynamoDb.scan(params, (error, result) => {
if (error) {
console.error(error);
return errorHandler(callBack, 'ERROR: Couldn\'t fetch the business', error );
}
return successHandler(callBack, result);
});
}
Example #22
Source File: importBusinesses.ts From Stripe-shop-backend with MIT License | 6 votes |
importBusinesses: Handler = async (event: APIGatewayEvent | ScheduledEvent, context: Context, callBack: Callback) => {
const data: ImportBusinesses = JSON.parse((event as APIGatewayEvent).body);
const errors: any[] = [];
const results: any[] = [];
data.Items.map(async (business) => {
try {
const validBusiness = validateBusiness(business);
if (!validBusiness.isValid) {
throw (validBusiness.errors);
}
const params: BusinessTable = {
TableName: process.env.DYNAMODB_TABLE_BUSINESSES,
Item: validBusiness.params,
};
const result = upsert(params);
results.push(result);
} catch (e) {
errors.push({
message: 'Failed to insert ' + business.businessName,
error: e,
});
}
});
return successHandler(callBack, {errors, results});
}
Example #23
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 #24
Source File: addProduct.ts From Stripe-shop-backend with MIT License | 6 votes |
addProduct: Handler = (event: APIGatewayEvent | ScheduledEvent, context: Context, callBack: Callback) => {
const data: Product = JSON.parse((event as APIGatewayEvent).body);
const timestamp = new Date().getTime();
const params: ProductTable = {
TableName: process.env.DYNAMODB_TABLE_PRODUCTS,
Item: {
productId: uuid.v1(),
name: data.name,
description: data.description,
amount: data.amount,
currency: 'cad',
createdAt: timestamp,
updatedAt: timestamp,
},
};
dynamoDb.put(params, (error, result) => {
if (error) {
return errorHandler(callBack, 'ERROR: Couldn\'t add the Product.', error );
}
return successHandler(callBack, { productId: params.Item.productId });
});
}
Example #25
Source File: index.ts From aws-nestjs-starter with The Unlicense | 5 votes |
cachedServer: Handler
Example #26
Source File: cancelPaymentIntent.ts From Stripe-shop-backend with MIT License | 5 votes |
cancelPaymentIntent: Handler = async (event: APIGatewayEvent | ScheduledEvent, context: Context, callBack: Callback) => {
const stripe = new Stripe(process.env.STRIPE_API_KEY, {
apiVersion: process.env.STRIPE_API_VERSION,
typescript: true,
});
const requestData: any = JSON.parse((event as APIGatewayEvent).body);
const { piid, cancellation_reason } = requestData;
if (! piid) {
return callBack('Must provide the PaymentIntentID');
}
const reason: Stripe.PaymentIntentCancelParams.CancellationReason = cancellation_reason ?? 'abandoned';
try {
const paymentIntent = await stripe.paymentIntents.cancel(piid, {
cancellation_reason: reason
});
return callBack(null, {
statusCode: 200,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': true,
},
body: JSON.stringify({
message: 'Payment cancelled!',
PaymentIntent: paymentIntent,
},
null,
2,
),
});
}
catch(error) {
return callBack(null, {
statusCode: 500,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': true,
},
body: JSON.stringify({
message: 'ERROR Payment Intent Cancellation FAILED!',
errorDetails: error,
},
null,
2,
),
});
}
}
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: updatePaymentIntent.ts From Stripe-shop-backend with MIT License | 5 votes |
createPaymentIntent: Handler = async (event: APIGatewayEvent | ScheduledEvent, context: Context, callBack: Callback) => {
// @ts-ignore
const stripe = new Stripe(process.env.STRIPE_API_KEY, {
apiVersion: process.env.STRIPE_API_VERSION,
typescript: true,
});
const requestData: any = JSON.parse((event as APIGatewayEvent).body);
// @todo validation on inputs
const {
amount,
currency,
payment_method_types,
capture_method,
off_session,
} = requestData;
const valid_payment_method_types = (payment_method_types) ? payment_method_types : ['card'];
const valid_capture_method = (capture_method == 'manual') ? capture_method : 'automatic';
// const valid_setup_future_usage = (off_session) ? 'off_session' : 'on_session';
try {
const paymentIntent = await stripe.paymentIntents.create({
amount,
currency,
payment_method_types: valid_payment_method_types,
capture_method: valid_capture_method,
// setup_future_usage: valid_setup_future_usage,
});
return callBack(null, {
statusCode: 200,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': true,
},
body: JSON.stringify({
message: 'Payment Intent Created!',
PaymentIntent: paymentIntent,
},
null,
2,
),
});
}
catch(error) {
callBack(null,{
statusCode: 500,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': true,
},
body: JSON.stringify({
message: 'ERROR Payment Intent Creation FAILED!',
errorDetails: error,
},
null,
2,
),
});
}
}
Example #29
Source File: scheduler.ts From crossfeed with Creative Commons Zero v1.0 Universal | 5 votes |
handler: Handler<Event> = async (event) => {
await connectToDatabase();
console.log('Running scheduler...');
const scanIds = event.scanIds || [];
if (event.scanId) {
scanIds.push(event.scanId);
}
const scanWhere = scanIds.length ? { id: In(scanIds) } : {};
const orgWhere = event.organizationIds?.length
? { id: In(event.organizationIds) }
: {};
const scans = await Scan.find({
where: scanWhere,
relations: ['organizations', 'tags', 'tags.organizations']
});
const organizations = await Organization.find({
where: orgWhere
});
const queuedScanTasks = await ScanTask.find({
where: {
scan: scanWhere,
status: 'queued'
},
order: {
queuedAt: 'ASC'
},
relations: ['scan']
});
const scheduler = new Scheduler();
await scheduler.initialize({
scans,
organizations,
queuedScanTasks,
orgsPerScanTask:
event.orgsPerScanTask ||
parseInt(process.env.SCHEDULER_ORGS_PER_SCANTASK || '') ||
1
});
await scheduler.runQueued();
await scheduler.run();
console.log('Finished running scheduler.');
}