Skip to content

Instantly share code, notes, and snippets.

@richard-flosi
Created April 27, 2020 19:49
Show Gist options
  • Save richard-flosi/18f22bd66bf75c1319b8189c123368e6 to your computer and use it in GitHub Desktop.
Save richard-flosi/18f22bd66bf75c1319b8189c123368e6 to your computer and use it in GitHub Desktop.
serverless express-openapi over netlify functions
const usersApi = require("./users");
module.exports = {
// /users
"post-users": usersApi.post,
"get-users": usersApi.get,
// /users/{userId}
"get-users-userId": usersApi.get,
"patch-users-userId": usersApi.patch,
"delete-users-userId": usersApi.delete,
};
const fs = require("fs");
const path = require("path");
const express = require("express");
const expressOpenAPI = require("express-openapi");
const serverless = require("serverless-http");
const apiDocFilename = "./openapi.yaml";
const apiVersion = process.env._HANDLER ? process.env._HANDLER.split(".")[0] : path.basename(__dirname);
const apiDocPath = process.env.LAMBDA_TASK_ROOT ? process.env.LAMBDA_TASK_ROOT : __dirname;
const apiDoc = fs.readFileSync(path.resolve(apiDocPath, apiDocFilename), "utf8");
const operations = require("./operations");
const app = express();
app.use(express.json());
expressOpenAPI.initialize({
app,
docsPath: "/docs",
apiDoc,
operations,
});
app.use(`/.netlify/functions/${apiVersion}`, app._router);
module.exports = app;
module.exports.handler = serverless(app);
@richard-flosi
Copy link
Author

richard-flosi commented Apr 27, 2020

Here's I'm creating a serverless Express.js API that consumes and implements an OpenAPI 3.0 spec using express-openapi over Netlify Functions with the help of serverless-http.

v1.js is my Netlify Function file.
operations.js is the map of operation ids defined in my OpenAPI spec to the Express.js handler.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment