Skip to content

Commit

Permalink
remove unncessary
Browse files Browse the repository at this point in the history
  • Loading branch information
ridwanzal committed Nov 22, 2021
1 parent ebae72e commit 5d3d0b6
Show file tree
Hide file tree
Showing 10 changed files with 335 additions and 2 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
node_modules
package-lock.json
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2021 Alain Perkaz

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
27 changes: 25 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,25 @@
# m2-exhibition-api
m2 public api
# Express OpenAPI

Code for the article: <https://www.freecodecamp.org/news/how-to-build-explicit-apis-with-openapi/>

This codebase shows how to build an [OpenAPI](https://www.openapis.org/)-backed [express](https://expressjs.com/) application.

## How to run

```bash
# Install dependencies
npm i

# Run app
npm run start
```

## Dynamic API documentation

Thanks to its OpenAPI compliance, the app auto-generates the documenation of the API on the fly.

Available in <http://localhost:3030/api-documentation>, while the app is running.

![doc-image](./doc-image.png)

## License
25 changes: 25 additions & 0 deletions api/api-doc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
const apiDoc = {
swagger: "2.0",
basePath: "/",
info: {
title: "Todo app API.",
version: "1.0.0",
},
definitions: {
Todo: {
type: "object",
properties: {
id: {
type: "number",
},
message: {
type: "string",
},
},
required: ["id", "message"],
},
},
paths: {},
};

module.exports = apiDoc;
112 changes: 112 additions & 0 deletions api/paths/todos/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
module.exports = function () {
let operations = {
GET,
POST,
PUT,
DELETE,
};

function GET(req, res, next) {
res.status(200).json([
{ id: 0, message: "First todo" },
{ id: 1, message: "Second todo" },
]);
}

function POST(req, res, next) {
console.log(`About to create todo: ${JSON.stringify(req.body)}`);
res.status(201).send();
}

function PUT(req, res, next) {
console.log(`About to update todo id: ${req.query.id}`);
res.status(200).send();
}

function DELETE(req, res, next) {
console.log(`About to delete todo id: ${req.query.id}`);
res.status(200).send();
}

GET.apiDoc = {
summary: "Fetch todos.",
operationId: "getTodos",
responses: {
200: {
description: "List of todos.",
schema: {
type: "array",
items: {
$ref: "#/definitions/Todo",
},
},
},
},
};

POST.apiDoc = {
summary: "Create todo.",
operationId: "createTodo",
consumes: ["application/json"],
parameters: [
{
in: "body",
name: "todo",
schema: {
$ref: "#/definitions/Todo",
},
},
],
responses: {
201: {
description: "Created",
},
},
};

PUT.apiDoc = {
summary: "Update todo.",
operationId: "updateTodo",
parameters: [
{
in: "query",
name: "id",
required: true,
type: "string",
},
{
in: "body",
name: "todo",
schema: {
$ref: "#/definitions/Todo",
},
},
],
responses: {
200: {
description: "Updated ok",
},
},
};

DELETE.apiDoc = {
summary: "Delete todo.",
operationId: "deleteTodo",
consumes: ["application/json"],
parameters: [
{
in: "query",
name: "id",
required: true,
type: "string",
},
],
responses: {
200: {
description: "Delete",
},
},
};

return operations;
};
39 changes: 39 additions & 0 deletions app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
var express = require("express");
var path = require("path");
var cookieParser = require("cookie-parser");
var logger = require("morgan");
var { initialize } = require("express-openapi");
var swaggerUi = require("swagger-ui-express");

var app = express();

app.listen(3030);
app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());

// OpenAPI routes
initialize({
app,
apiDoc: require("./api/api-doc"),
paths: "./api/paths",
});

// OpenAPI UI
app.use(
"/api-documentation",
swaggerUi.serve,
swaggerUi.setup(null, {
swaggerOptions: {
url: "http://localhost:3030/api-docs",
},
})
);

console.log("App running on port http://localhost:3030");
console.log(
"OpenAPI documentation available in http://localhost:3030/api-documentation"
);

module.exports = app;
90 changes: 90 additions & 0 deletions bin/www
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
#!/usr/bin/env node

/**
* Module dependencies.
*/

var app = require('../app');
var debug = require('debug')('express-open-api:server');
var http = require('http');

/**
* Get port from environment and store in Express.
*/

var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);

/**
* Create HTTP server.
*/

var server = http.createServer(app);

/**
* Listen on provided port, on all network interfaces.
*/

server.listen(port);
server.on('error', onError);
server.on('listening', onListening);

/**
* Normalize a port into a number, string, or false.
*/

function normalizePort(val) {
var port = parseInt(val, 10);

if (isNaN(port)) {
// named pipe
return val;
}

if (port >= 0) {
// port number
return port;
}

return false;
}

/**
* Event listener for HTTP server "error" event.
*/

function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}

var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;

// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}

/**
* Event listener for HTTP server "listening" event.
*/

function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
}
Binary file added doc-image.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions express-open-api
Submodule express-open-api added at 20aecd
20 changes: 20 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
"name": "express-open-api",
"version": "0.0.0",
"engines": {
"node": "12.19.0",
"npm": "6.14.8"
},
"private": true,
"scripts": {
"start": "node app.js"
},
"dependencies": {
"cookie-parser": "~1.4.4",
"debug": "~2.6.9",
"express": "~4.16.1",
"express-openapi": "^7.5.0",
"morgan": "~1.9.1",
"swagger-ui-express": "^4.1.6"
}
}

0 comments on commit 5d3d0b6

Please sign in to comment.