Search This Blog

2023/05/06

Swagger: Express.js Integration

install npm package swagger-ui-express

and

npm i --save-dev @types/swagger-ui-express


in app.ts

add

import swaggerUi from 'swagger-ui-express';
import swaggerDocument from '../swagger.json';


then add in app.ts

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


for user route

import express from 'express';
import { getLogger } from '@/utils/loggers';
const router = express.Router();
const logger = getLogger('USER_ROUTE');
import { User } from '../models';
import bcrypt from "bcrypt";
import jsonwebtoken from 'jsonwebtoken';
import passport from 'passport';
import { upload } from '../utils/upload'


router.post('/signup', upload.single('profilePic'),
async function (req, res, next) {
if (!req.body.email || !req.body.password) {
res.status(400).send({
msg: 'Please enter email and password.'
});
} else {
try {
var foundUser = await User.findOne({
where: { email: req.body.email }
})
if (foundUser) {
res.status(400).send({
msg: 'Email ' + foundUser.email + ' already taken ,please login'
});
} else {


let hashedPassword = await bcrypt.hash(req.body.password,
bcrypt.genSaltSync(8))
let user = await User.create({
email: req.body.email,
password: hashedPassword,
firstName: req.body.firstName,
lastName: req.body.lastName,
relationWith: req.body.relationWith,
profilePic: req.file?.filename
})

var returnValue = JSON.parse(JSON.stringify(user))
delete returnValue.password;

res.status(201).send({
msg: 'User created successfully',
data: returnValue
});
}
} catch (exp: any) {
res.status(201).send({
msg: 'Error Occured while creating User:' + exp.toString()
});
}

}


});

router.post("/login", async function (req, res) {
if (req.body.email && req.body.password) {
var email = req.body.email
var password = req.body.password;
}
// usually this would be a database call:
var user = await User.findOne({
where: { email: email }
})

if (!user) {
res.status(401).json({ message: "no such user found" });
} else {
var re = await bcrypt.compare(req.body.password, user.password)
if (re) {
var payload = { id: user.id };
var secretKey = process.env.SECRET_KEY || 'abcd1234'
var token = jsonwebtoken.sign(payload, secretKey);
res.json({ message: "ok", token: token });
} else {
res.status(401).json({ message: "passwords did not match" });
}
}
});

router.get("/secret", passport.authenticate('jwt', { session: false }),
function (req, res) {
res.json("Success! You can not see this without a token");
});


router.get("/sample1/:param", function (req, res) {
res.json({ "param": req.params.param });
});

router.get("/sample2", function (req, res) {
res.json({ "param": req.query.param });
});


export default router;


create swagger.json as

{
"swagger": "2.0",
"info": {
"version": "1.0.0",
"title": "My User Project CRUD",
"description": "My User Project Application API",
"license": {
"name": "MIT",
"url": "https://opensource.org/licenses/MIT"
}
},
"host": "localhost:3000",
"basePath": "/",
"tags": [
{
"name": "Users",
"description": "API for users in the system"
}
],
"schemes": [
"http"
],
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"paths": {
"/users/signup": {
"post": {
"tags": [
"Users"
],
"description": "Create new user in system",
"parameters": [
{
"name": "email",
"in": "formData",
"description": "email of user",
"required": true,
"type": "string"
},
{
"name": "firstName",
"in": "formData",
"description": "firstName of user",
"required": true,
"type": "string"
},
{
"name": "lastName",
"in": "formData",
"description": "lastName of user",
"required": true,
"type": "string"
},
{
"name": "password",
"in": "formData",
"description": "password of user",
"required": true,
"type": "string"
},
{
"name": "relationWith",
"in": "formData",
"description": "relation with bride or groom",
"required": true,
"type": "integer",
"enum": [
1,
2,
3
],
"format": "int64"
},
{
"name": "profilePic",
"in": "formData",
"description": "profile picture",
"required": true,
"type": "file"
}
],
"consumes": [
"multipart/form-data"
],
"produces": [
"application/json"
],
"responses": {
"200": {
"description": "New user is created"
}
}
}
},
"/users/login": {
"post": {
"tags": [
"Users"
],
"description": "Login user in system",
"parameters": [
{
"name": "body",
"in": "body",
"required": true,
"type": "string",
"schema": {
"$ref": "#/definitions/loginRequest"
}
}
],
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"responses": {
"200": {
"description": "sign in to user"
}
}
}
},
"/users/secret": {
"get": {
"tags": [
"Users"
],
"description": "Login user in system",
"parameters": [
{
"name": "Authorization",
"in": "header",
"required": true,
"type": "string"
}
],
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"responses": {
"200": {
"description": "sign in to user"
}
}
}
},
"/users/sample1/{param}": {
"get": {
"tags": [
"Users"
],
"description": "Login user in system",
"parameters": [
{
"name": "param",
"in": "path",
"required": true,
"type": "string"
}
],
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"responses": {
"200": {
"description": "sign in to user"
}
}
}
},
"/users/sample2": {
"get": {
"tags": [
"Users"
],
"description": "Login user in system",
"parameters": [
{
"name": "param",
"in": "query",
"required": true,
"type": "string"
}
],
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"responses": {
"200": {
"description": "sign in to user"
}
}
}
}
},
"definitions": {
"loginRequest": {
"required": [
"email",
"password"
],
"properties": {
"email": {
"type": "string"
},
"password": {
"type": "string"
}
}
}
}
}

you can visit http://localhost:3000/api-docs to see swagger in action

No comments:

Post a Comment