openapi-backend
openapi-backend copied to clipboard
AWS Lambda ES module : not working
Hi folks,
I am trying to use "openapi-backend" in my lambda ES module. I did all the necessary to make it run following the tutorial. The problem is that it does not run on my lambda when I deploy it. here is my index.js code :
import {info} from './src/utils/logger.js';
import {OpenAPIBackend} from 'openapi-backend';
const headers = {
'content-type': 'application/json',
'access-control-allow-origin': '*', // lazy cors config
};
// create api with your definition file or object
const api = new OpenAPIBackend({definition: './spec/XXX-api-back.yml'});
// register your framework specific request handlers here
api.register({
notFound: async (c, event, context) => ({
statusCode: 404,
body: JSON.stringify({err: 'not found'}),
headers,
}),
validationFail: async (c, event, context) => ({
statusCode: 400,
body: JSON.stringify({err: c.validation.errors}),
headers,
}),
getPostesRh: async (c, event, context) => ({
statusCode: 200,
body: JSON.stringify({operationId: c.operation.operationId}),
headers,
}),
getPosteRh: async (c, event, context) => ({
statusCode: 200,
body: JSON.stringify({operationId: c.operation.operationId}),
headers,
}),
});
// initalize the backend
api.init();
/**
* Fonction de base attendue par le service AWS Lambda
*
* @param {JSON} event Event AWS Lambda trigger call
* @param {JSON} context Context forwarded by AWS Lambda
* @return {JSON} Dans la réponse : httpCode = 200 | 204 | 500,
* message est non vide si erreur
*/
export async function handler(event, context) {
info(`Start Function name - '${context.functionName}'`);
return api.handleRequest(
{
method: event.httpMethod,
path: event.path,
query: event.queryStringParameters,
body: event.body,
headers: event.headers,
},
event,
context,
);
}
here is the cloudwatch log : { "level": "info", "message": "Start Function name - 'laf-XXX-api-expose'", "timestamp": "2022-07-11T15:31:33.226Z" } END RequestId: 1e7eebd5-1fd6-43ed-b2e3-fbc83ee88fbb
As we can see the lambda didn't run the controller when I called the API. Any idea why it didn't work ?
Regards,
You have to wait for the API to initialize. So for example:
const initedApi = api.init();
export async function handler(event, context) {
await initedApi;
return await api.handleRequest({...});
}
Also I suggest you set the 'quick' parameter in options as true.
Also note that event.queryStringParameters does not work if you have array query parameters in specification. I made a fix for that but not sure if it gets merged: https://github.com/anttiviljami/openapi-backend/pull/444