因此,我正在尝试做一个基本的事情:从我的AWS Lambda脚本连接到外部REST-API。
该API托管假期列表。
但是,每当我尝试执行代码时,它就会超时(达到最大lambda执行时间)。
因此,我创建了此包装器函数,该函数能够处理4种不同的方式来处理GET
请求,但是它们都执行相同的操作。
const request = require('request')
const https = require('https')
const axios = require('axios')
const superagent = require('superagent')
let test = (type = "") => {
return new Promise((resolve, reject) => {
debug("Fetching with: " + type)
const d = new Date()
if(type == "superagent"){
superagent.get('https://holidayapi.pl/v1/holidays?country=DK&year=' + d.getFullYear())
.query({ country: 'DK', year: '2019' })
.end((err, res) => {
if (err) {
console.log(err)
reject(err)
} else {
console.log(res)
resolve(res)
}
})
} else if(type == "axios"){
axios.get('https://holidayapi.pl/v1/holidays?country=DK&year=' + d.getFullYear())
.then(response => {
debug(response)
resolve(response)
})
.catch(error => {
console.log(error)
reject(error)
})
} else if(type == "https"){
const req = https.get("https://holidayapi.pl/v1/holidays?country=DK&year=" + d.getFullYear(), (resp) => {
let data = ''
// A chunk of data has been recieved.
resp.on('data', (chunk) => {
data += chunk
})
// The whole response has been received. Print out the result.
resp.on('end', () => {
console.log(JSON.parse(data).explanation)
resolve([])
})
})
.on('error', (e) => {
debug(e)
reject(e.message)
})
req.end()
} else if(type == "request"){
request('https://holidayapi.pl/v1/holidays?country=DK&year=' + d.getFullYear(), { json: true }, (err, res, body) => {
debug(err)
debug(res)
debug(body)
if (err) reject(err)
else resolve(body.holidays)
})
} else {
reject("Mangler type")
}
})
}
exports.connect_test = (event, context, callback) => {
test(event.pathParameters.type)
.then((rsp) => {
callback(null, JSON.stringify(rsp, null, 2))
})
.catch((err) => {
callback(null, JSON.stringify(err, null, 2))
})
}
debug
函数是console.log的映射,用于检查NODE_ENV是否为“ dev”。
答案 0 :(得分:1)