AWS Lambda 请求应用接口

// dependencies
const AWS = require('aws-sdk');
const util = require('util');
const fs = require('fs');
const readline = require('readline');
const https = require('https');
const http = require('http');
const querystring = require('querystring');

// get reference to S3 client
const s3 = new AWS.S3();
exports.handler = async (event, context, callback) => {
    // Read options from the event parameter.
    console.log("Reading options from event:\n", util.inspect(event, { depth: 5 }));
    const srcBucket = event.Records[0].s3.bucket.name;
    // Object key may have spaces or unicode non-ASCII characters.
    const srcKey = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, " "));
    // Download the  stream file from the S3 source bucket. 
    try {
        const params = {
            Bucket: srcBucket,
            Key: srcKey
        };
        var eventStreamFile = await s3.getObject(params).promise();
        // console.log('WORLDZHY File', eventStreamFile);
    } catch (error) {
        console.log(error);
        return;
    }

    // Upload the thumbnail image to the destination bucket
    try {
        const eventsString = eventStreamFile.Body.toString();
        const eventStrings = eventsString.split('\n');
        // console.log('WORLDZHY Event Array', eventStrings);
        const events = [];
        for (const eventString of eventStrings) {
            if (eventString.length > 0) {
                events.push(JSON.parse(eventString));
            }
        }
        const newEvents = events.map(event => {
            const { event_type } = event;
            if (event_type.startsWith('_email')) {
                return {
                    messageId: event.facets.email_channel.mail_event.mail.message_id,
                    eventType: event.event_type,
                    eventTimestamp: event.event_timestamp,
                    arrivalTimestamp: event.arrival_timestamp,
                    eventVersion: event.event_version,
                    application: event.application,
                    client: event.client,
                    device: event.device,
                    session: event.session,
                    attributes: event.attributes,
                    clientContext: event.client_context,
                    facets: event.facets,
                    awsAccountId: event.awsAccountId,
                };
            } else if (event_type.startsWith('_SMS')) {
                return {
                    messageId: event.attributes.message_id,
                    eventType: event.event_type,
                    eventTimestamp: event.event_timestamp,
                    arrivalTimestamp: event.arrival_timestamp,
                    eventVersion: event.event_version,
                    application: event.application,
                    client: event.client,
                    device: event.device,
                    session: event.session,
                    attributes: event.attributes,
                    metrics: event.metrics,
                    awsAccountId: event.awsAccountId,
                };
            }

        });

        // POST parameters
        const parameters = {
            callbackKey: '128381283jdsjafjsajfjadsjjfsjafdjsdj',
            events: newEvents,
        }

        // POST parameters as query string
        const postData = JSON.stringify(parameters);
        
        const options = {
            hostname: 'ec2-161-19-63-20.cn-northwest-1.compute.amazonaws.com.cn',
            port: 3000,
            path: '/messages/createEvents',
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Content-Length': postData.length
            }
        }

        const result = await httpRequest(options, postData);

    } catch (error) {
        console.log(error);
        return;
    }
};

function httpRequest(params, postData) {
    return new Promise(function (resolve, reject) {
        // var req = https.request(params, function (res) {
        var req = http.request(params, function (res) {
            // reject on bad status
            if (res.statusCode < 200 || res.statusCode >= 300) {
                return reject(new Error('statusCode=' + res.statusCode));
            }
            // cumulate data
            var body = [];
            res.on('data', function (chunk) {
                body.push(chunk);
            });
            // resolve on end
            res.on('end', function () {
                try {
                    body = Buffer.concat(body).toString();
                } catch (e) {
                    reject(e);
                }
                resolve(body);
            });
        });
        // reject on request error
        req.on('error', function (err) {
            // This is not a "Second reject", just a different sort of failure
            reject(err);
        });
        if (postData) {
            req.write(postData);
        }
        // IMPORTANT
        req.end();
    });
}

 

你可能感兴趣的:(AWS,aws,lambda,request)