AWS Lambda - обслуживать контент с другого пути сайта - PullRequest
0 голосов
/ 27 марта 2020

Я следовал примеру здесь , чтобы создать триггер запроса источника, который будет обслуживать контент с другого пути сайта.

Например: adoring-elion-23496793.myapp.com обслуживает контент из https://myapp.com/website/BoounXQ6shTNP0cG8Zuk (есть промежуточный поиск для получения идентификатора). Когда веб-сайт не может быть найден, он возвращается к myapp.com.

'use strict';

const remove_suffix = '.myapp.com';
const origin_hostname = 'myapp.com';
const redirect_api = 'us-central1-myapp-dev.cloudfunctions.net'
const https = require('https');

exports.handler = (event, context, callback) => {
    const request = event.Records[0].cf.request;
    const headers = request.headers;
    const host_header = headers.host[0].value;

    if(host_header.endsWith(remove_suffix)) {
        const website_name = host_header.substring(0,host_header.length - remove_suffix.length);
        return httprequest(website_name).then((data) => {
            const response = {
                statusCode: 200,
                body: data
            };
            const website_id = response['body']['websiteId'];
            if (website_id) {
                console.log('Corresponding website id found: ' + website_id);
                request.origin = {
                    custom: {
                        domainName: 'www.myapp.com',
                        port: 443,
                        protocol: 'https',
                        path: '/websites/' + website_id,
                        sslProtocols: ['TLSv1', 'TLSv1.1'],
                        readTimeout: 5,
                        keepaliveTimeout: 5,
                        customHeaders: {}
                    }
                };
                request.headers['host'] = [{ key: 'host', value: 'www.myapp.com'}];
                return callback(null, request);
            } else {
                console.log('Corresponding website id not found');
                request.origin = {
                    custom: {
                        domainName: 'www.myapp.com',
                        port: 443,
                        protocol: 'https',
                        path: '',
                        sslProtocols: ['TLSv1', 'TLSv1.1'],
                        readTimeout: 5,
                        keepaliveTimeout: 5,
                        customHeaders: {}
                    }
                };
                request.headers['host'] = [{ key: 'host', value: 'www.myapp.com'}];
                return callback(null, request);
            }
        });
    } else {
        request.origin = {
            custom: {
                domainName: 'www.myapp.com',
                port: 443,
                protocol: 'https',
                path: '',
                sslProtocols: ['TLSv1', 'TLSv1.1'],
                readTimeout: 5,
                keepaliveTimeout: 5,
                customHeaders: {}
            }
        };
        request.headers['host'] = [{ key: 'host', value: 'www.myapp.com'}];
        return callback(null, request);
    } 
};

function httprequest(website_name) {
     return new Promise((resolve, reject) => {
        const options = {
            host: redirect_api,
            path: '/getWebsiteIdByName/' + website_name,
            port: 443,
            method: 'GET'
        };
        const req = https.request(options, (res) => {
          if (res.statusCode < 200 || res.statusCode >= 300) {
                return reject(new Error('statusCode=' + res.statusCode));
            }
            var body = [];
            res.on('data', function(chunk) {
                body.push(chunk);
            });
            res.on('end', function() {
                try {
                    body = JSON.parse(Buffer.concat(body).toString());
                } catch(e) {
                    reject(e);
                }
                resolve(body);
            });
        });
        req.on('error', (e) => {
          reject(e.message);
        });
       req.end();
    });
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...