Created
April 27, 2020 19:49
-
-
Save richard-flosi/18f22bd66bf75c1319b8189c123368e6 to your computer and use it in GitHub Desktop.
serverless express-openapi over netlify functions
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
| 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, | |
| }; |
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
| 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); |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here's I'm creating a serverless Express.js API that consumes and implements an OpenAPI 3.0 spec using
express-openapiover Netlify Functions with the help ofserverless-http.v1.jsis my Netlify Function file.operations.jsis the map of operation ids defined in my OpenAPI spec to the Express.js handler.