Last active
October 29, 2019 07:53
-
-
Save jebai0521/e30b03ee1c90fb37d8913e7059332925 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
const AWS = require('aws-sdk'); | |
const s3 = new AWS.S3(); | |
const locale = require("locale") | |
exports.handler = async (event, context, callback) => { | |
console.log("event ==> ", JSON.stringify(event)); | |
const request = event.Records[0].cf.request; | |
console.log(`<< ${request.origin.s3.domainName}${request.origin.s3.path}${request.uri}`); | |
const s3DomainName = 'micro-site.s3.amazonaws.com'; | |
const locales = new locale.Locales(request.headers['accept-language'][0].value); | |
console.log("Our default is: " + locale.Locale["default"]); | |
const parts = request.uri.split("/"); | |
const prefix = parts[1]; | |
const s3options = {Bucket: 'micro-site', Prefix: prefix}; | |
const supportLanguages = await getSupportLanguages(s3options); | |
// const supportLanguages = ['zh-CN', 'en']; | |
console.log("supportLanguages ==> ", supportLanguages) | |
const supported = new locale.Locales(supportLanguages) | |
language = locales.best(supported) | |
console.log("Our best match is: " + language); | |
parts.splice(2, 0, language); | |
request.uri = parts.join("/"); | |
console.log(`<< ${request.origin.s3.domainName}${request.origin.s3.path}${request.uri}`); | |
request.headers['host'] = [{ key: 'host', value: s3DomainName }]; | |
console.log("request ==> ", JSON.stringify(request)); | |
callback(null, request); | |
}; | |
const getSupportLanguages = async (options) => { | |
const languages = []; | |
// const start = new Date().getTime(); | |
const response = await s3.listObjectsV2(options).promise(); | |
// const end = new Date().getTime(); | |
// console.log("request s3 languages cost ", end - start, "ms"); | |
response.Contents.forEach(obj => { | |
const lang = obj.Key.split('/')[1]; | |
// if (lang.endsWith('(default)')) { | |
// lang = lang.substring(0, lang.length - 9); | |
// defaultLanguage = lang | |
// } | |
languages.push(lang) | |
}) | |
return Array.from(new Set(languages)); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment