|
const { Server } = require('slash-create'); |
|
|
|
class AWSRuntimeServer extends Server { |
|
|
|
/** |
|
* @param opts The server options |
|
*/ |
|
constructor(opts) { |
|
super(opts); |
|
} |
|
|
|
/** |
|
* |
|
* @param {string} path This is not used in AWS Lambda |
|
* @param {ServerRequestHandler} handler The callback that incoming events are passed to |
|
*/ |
|
createEndpoint(path, handler) { |
|
this.handler = handler; |
|
} |
|
|
|
/** @private */ |
|
async listen(port = 8030, host = 'localhost') { |
|
while (true) { |
|
try { |
|
//const res = await axios.get(`http://${process.env.AWS_LAMBDA_RUNTIME_API}/2018-06-01/runtime/invocation/next`, { timeout: 30000 }) |
|
const res= (await fetch(`http://${process.env.AWS_LAMBDA_RUNTIME_API}/2018-06-01/runtime/invocation/next`)); |
|
const invocationID=res.headers.get('lambda-runtime-aws-request-id'); |
|
const data = await res.json(); |
|
console.log("Received message", data.body); |
|
const treq = { |
|
headers: data.headers, |
|
body: JSON.parse(data.body), |
|
rawBody:data.body, |
|
request: {}, |
|
response: {}, |
|
|
|
} |
|
await this.handler(treq, lambdaResponder(invocationID)); |
|
} catch (e) { |
|
console.error("Error in listen", e); |
|
|
|
} |
|
} |
|
} |
|
} |
|
|
|
/** |
|
* Creates a callback function that sends a response to the AWS Lambda Runtime API |
|
* @param {string} invocationID |
|
* @returns |
|
*/ |
|
function lambdaResponder(invocationID) { |
|
return async (response) => { |
|
let d; |
|
if (response.status && response.status !== 200) { |
|
response.body = JSON.stringify(response.body); |
|
response.statusCode = response.status ?? 200; |
|
d=JSON.stringify(response); |
|
}else{ |
|
d=JSON.stringify(response.body); |
|
} |
|
console.log(invocationID + " ::Sending response", d); |
|
await fetch(`http://${process.env.AWS_LAMBDA_RUNTIME_API}/2018-06-01/runtime/invocation/${invocationID}/response`, { method: "POST", body: d }) |
|
|
|
} |
|
} |
|
|
|
module.exports = AWSRuntimeServer; |
|
|
|
/** |
|
* @callback ServerRequestHandler |
|
* @param {TransformedRequest} req The incoming request |
|
* @param {ResponseFunction} res The callback to send the response back to the initial request |
|
* @returns {Promise<void>} |
|
|
|
* @callback ResponseFunction |
|
* @param {Response} response |
|
* @returns {Promise<void>} |
|
|
|
* @typedef {Object} Response |
|
* @property {number} [status] |
|
* @property {Object.<string, string | string[] | undefined>} [headers] |
|
* @property {any} [body] |
|
|
|
* @typedef {Object} TransformedRequest |
|
* @property {Object.<string, string | string[] | undefined>} headers |
|
* @property {any} body |
|
* @property {*} request |
|
* @property {*} response |
|
* @property {string} [rawBody] |
|
*/ |
|
|