Showing posts with label swagger. Show all posts
Showing posts with label swagger. Show all posts

Monday, November 2, 2020

 NodeJeando, con swagger.


en esta oportunidad, nos toca ver como una simple app, con una API minimal, de una estructura mockeada, nos puede servir para alimentar swagger.


para esto, tenemos que tener los modulos


npm install express swagger swagger-ui swagger-ui-express body-parser 


La página de donde saqué todo esto es


https://medium.com/bb-tutorials-and-thoughts/how-to-add-swagger-to-nodejs-rest-api-7a542cfdc5e1


y lo que sigue ahora es , la app, y la llamada a swagger.

comenté en un primer paso, el tema de los css.

 const express = require('express');

const randomId = require('random-id');

const app = express(),

    bodyParser = require("body-parser"),

    fs = require('fs'),

    port = 3080;


const swaggerUi = require('swagger-ui-express');

const swaggerDocument = require('./swagger.json');

//const customCss = fs.readFileSync((process.cwd() + "/swagger.css"), 'utf8');


// place holder for the data

let tasks = [

    {

        id: 1,

        task: 'task1',

        assignee: 'assignee1000',

        status: 'completed'

    },

    {

        id: 2,

        task: 'task2',

        assignee: 'assignee1001',

        status: 'completed'

    },

    {

        id: 3,

        task: 'task3',

        assignee: 'assignee1002',

        status: 'completed'

    },

    {

        id: 4,

        task: 'task4',

        assignee: 'assignee1000',

        status: 'completed'

    },


];


app.use(bodyParser.json());

app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument, { customCss }));


app.get('/api/todos', (req, res) => {

    console.log('api/todos called!!!!!')

    res.json(tasks);

});


app.post('/api/todo', (req, res) => {

    const task = req.body.task;

    task.id = randomId(10);

    tasks.push(task);

    res.json(tasks);

})


app.delete('/api/todo/:id', (req, res) => {

    console.log("Id to delete:::::", req.params.id)

    tasks = tasks.filter(task => task.id != req.params.id);

    res.json(tasks);

})


app.put('/api/todos/:id', (req, res) => {

    console.log("Id to update:::::", req.params.id)

    const taskToUpdate = req.body.task;

    tasks = tasks.map(task => {

        if (task.id == req.params.id) {

            task = taskToUpdate;

            task.id = parseInt(req.params.id);

        }

        return task;

    });

    res.json(tasks);

});


app.get('/', (req, res) => {

    res.send(`<h1>API Running on port ${port}</h1>`);

});


app.listen(port, () => {

    console.log(`Server listening on the port::::::${port}`);

});



y la llamada a swagger.json

 {

    "swagger": "2.0",

        "info": {

        "description": "This is a simple example NodeJS API project to demonstrate Swagger Documentation",

            "version": "1.0.0",

                "title": "Tasks API",

                    "contact": {

            "email": "abc@gmail.com"

        },

        "license": {

            "name": "Apache 2.0",

                "url": "http://www.apache.org/licenses/LICENSE-2.0.html"

        }

    },

    "schemes": ["http"],

        "host": "localhost:3080",

            "basePath": "/api",

                "paths" : {

        "/todos" : {

            "get" : {

                "summary" : "Get all the tasks",

                    "description": "Get all the tasks",

                        "produces": ["application/json"],

                            "parameters": [],

                                "responses": {

                    "200": {

                        "description": "successful operation",

                            "schema": {

                            "type": "array",

                                "items": {

                                "$ref": "#/definitions/todosResponse"

                            }

                        }

                    },

                    "400": {

                        "description": "Invalid status value",

                            "schema": {

                            "$ref": "#/definitions/InvalidResponse"

                        }

                    }

                }

            }

        },

        "/todo" : {

            "post" : {

                "summary" : "Save the task",

                    "description": "Save the task",

                        "produces": ["application/json"],

                            "consumes": ["application/json"],

                                "parameters": [

                                    {

                                        "in": "body",

                                        "name": "body",

                                        "description": "task object",

                                        "required": true,

                                        "schema": {

                                            "type": "object",

                                            "properties": {

                                                "task": {

                                                    "type": "object",

                                                    "$ref": "#/definitions/Task"

                                                }

                                            }

                                        }

                                    }

                                ],

                                    "responses": {

                    "200": {

                        "description": "successful operation",

                            "schema": {

                            "type": "array",

                                "items": {

                                "$ref": "#/definitions/todosResponse"

                            }

                        }

                    },

                    "400": {

                        "description": "Invalid status value",

                            "schema": {

                            "$ref": "#/definitions/InvalidResponse"

                        }

                    }

                }

            }

        },

        "/todos/{id}" : {

            "put" : {

                "summary" : "Update the tasks",

                    "description": "Update the tasks",

                        "produces": ["application/json"],

                            "parameters": [

                                {

                                    "name": "id",

                                    "in": "path",

                                    "description": "task id that needs to be deleted",

                                    "required": true,

                                    "type": "string"

                                },

                                {

                                    "in": "body",

                                    "name": "body",

                                    "description": "task object",

                                    "required": true,

                                    "schema": {

                                        "type": "object",

                                        "properties": {

                                            "task": {

                                                "type": "object",

                                                "$ref": "#/definitions/Task"

                                            }

                                        }

                                    }

                                }

                            ],

                                "responses": {

                    "200": {

                        "description": "successful operation",

                            "schema": {

                            "type": "array",

                                "items": {

                                "$ref": "#/definitions/todosResponse"

                            }

                        }

                    },

                    "400": {

                        "description": "Invalid status value",

                            "schema": {

                            "$ref": "#/definitions/InvalidResponse"

                        }

                    }

                }

            }

        },

        "/todo/{id}" : {

            "delete" : {

                "summary" : "Delete the task",

                    "description": "Delete the task",

                        "produces": ["application/json"],

                            "parameters": [

                                {

                                    "name": "id",

                                    "in": "path",

                                    "description": "task id that needs to be deleted",

                                    "required": true,

                                    "type": "string"

                                }

                            ],

                                "responses": {

                    "200": {

                        "description": "successful operation",

                            "schema": {

                            "type": "array",

                                "items": {

                                "$ref": "#/definitions/todosResponse"

                            }

                        }

                    },

                    "400": {

                        "description": "Invalid status value",

                            "schema": {

                            "$ref": "#/definitions/InvalidResponse"

                        }

                    }

                }

            }

        }

    },

    "definitions": {

        "todosResponse": {

            "type": "object",

                "properties": {

                "id": {

                    "type": "integer"

                },

                "task": {

                    "type": "string"

                },

                "assignee": {

                    "type": "string"

                },

                "status": {

                    "type": "string"

                }

            }

        },

        "Task": {

            "type": "object",

                "properties": {

                "task": {

                    "type": "string"

                },

                "assignee": {

                    "type": "string"

                },

                "status": {

                    "type": "string"

                }

            }

        },

        "InvalidResponse": {

            "type": "object",

                "properties": {

                "statusCode": {

                    "type": "string"

                },

                "message": {

                    "type": "string"

                }

            }


        }

    }