|
| 1 | +const serverless = require('serverless-http'); |
| 2 | +const express = require('express'); |
| 3 | +const app = express(); |
| 4 | + |
| 5 | +const bodyParser = require('body-parser'); |
| 6 | +const uuid = require('uuid/v4'); |
| 7 | + |
| 8 | +const dbConnection = require('../dbConfigs'); |
| 9 | +const ProductService = require('../Services/product'); |
| 10 | + |
| 11 | + |
| 12 | +app.use(bodyParser.json()); |
| 13 | +app.use(bodyParser.urlencoded({ extended: true })); |
| 14 | + |
| 15 | + |
| 16 | +// base url to test our API |
| 17 | +app.get('/index', async (req, res) => { |
| 18 | + await res.send("<h3>Welcome to the Product API for LogRocket Blog serverless Example!!</h3>") |
| 19 | +}) |
| 20 | + |
| 21 | +// function for creating a new product |
| 22 | +app.post('/', async (req, res) => { |
| 23 | + |
| 24 | + try { |
| 25 | + |
| 26 | + await dbConnection(); |
| 27 | + |
| 28 | + const data = req.body; |
| 29 | + |
| 30 | + const {name, type, description, cost} = data; |
| 31 | + |
| 32 | + if(!data) { |
| 33 | + return "Please pass all required fields!" |
| 34 | + } |
| 35 | + |
| 36 | + const dataToSave = {name,type,description,cost,productId:uuid()}; |
| 37 | + |
| 38 | + let createProduct = await ProductService.createProduct(dataToSave); |
| 39 | + |
| 40 | + if (createProduct) { |
| 41 | + return res.status(200).send( |
| 42 | + createProduct |
| 43 | + ) |
| 44 | + } |
| 45 | + } catch (error) { |
| 46 | + // handle errors here |
| 47 | + console.log(error, "error!!"); |
| 48 | + } |
| 49 | + |
| 50 | +}) |
| 51 | + |
| 52 | + |
| 53 | +// function for getting all products |
| 54 | +app.get('/', async (req, res) => { |
| 55 | + |
| 56 | + try { |
| 57 | + await dbConnection(); |
| 58 | + |
| 59 | + const allProducts = await ProductService.getAllProduct(); |
| 60 | + |
| 61 | + if (allProducts) { |
| 62 | + return res.status(200).send({ |
| 63 | + data: allProducts |
| 64 | + }) |
| 65 | + } |
| 66 | + } catch (error) { |
| 67 | + // handle errors here |
| 68 | + console.log(error, "error!!"); |
| 69 | + } |
| 70 | +}) |
| 71 | + |
| 72 | + |
| 73 | +// function for getting a product by Id |
| 74 | +app.get('/:productId/', async (req, res) => { |
| 75 | + |
| 76 | + try { |
| 77 | + |
| 78 | + await dbConnection(); |
| 79 | + |
| 80 | + const {productId} = req.params; |
| 81 | + |
| 82 | + const getProduct = await ProductService.getProductById({productId}); |
| 83 | + |
| 84 | + if(getProduct) { |
| 85 | + return res.status(200).send({ |
| 86 | + data: getProduct |
| 87 | + }) |
| 88 | + |
| 89 | + } |
| 90 | + |
| 91 | + } catch (error) { |
| 92 | + // handle errors here |
| 93 | + console.log(error, "error!!"); |
| 94 | + |
| 95 | + } |
| 96 | + |
| 97 | +}); |
| 98 | + |
| 99 | + |
| 100 | +module.exports.handler = serverless(app); |
0 commit comments