|
| 1 | +const express = require('express'); |
| 2 | +const path = require('path'); |
| 3 | +const cors = require('cors'); |
| 4 | +const chronos = require('chronos-tracker'); |
| 5 | +require('./chronos-config'); |
| 6 | +const controller = require('./BookController.js'); |
| 7 | +require('dotenv').config(); |
| 8 | + |
| 9 | +// Places a unique header on every req in order to trace the path in the req's life cycle. |
| 10 | +chronos.propagate(); |
| 11 | + |
| 12 | +const app = express(); |
| 13 | + |
| 14 | +app.use(express.json()); |
| 15 | +app.use('/', chronos.track()); |
| 16 | + |
| 17 | +app.use(cors()); |
| 18 | +app.use('/', express.static(path.resolve(__dirname, '../frontend'))); |
| 19 | + |
| 20 | +// CHAOS FLOW - SIMPLY A TEST FOR THE EXPESS SERVER |
| 21 | +app.use((req, res, next) => { |
| 22 | + console.log( |
| 23 | + `*************************************************************************************** |
| 24 | + CHAOS FLOW TEST --- METHOD:${req.method}, |
| 25 | + PATH: ${req.url}, |
| 26 | + BODY: ${JSON.stringify(req.body)}, |
| 27 | + ID: ${req.query.id} |
| 28 | + ***************************************************************************************` |
| 29 | + ); |
| 30 | + next(); |
| 31 | +}); |
| 32 | + |
| 33 | +// This route will create a new book! |
| 34 | +app.post('/books/createbook', controller.createBook, (req, res) => { |
| 35 | + res.status(200).json(res.locals.createBook); |
| 36 | +}); |
| 37 | + |
| 38 | +// This route will delete a book |
| 39 | +app.delete('/books/deletebook:id?', controller.deleteBook, (req, res) => { |
| 40 | + res.status(200).json(res.locals.deleteBook); |
| 41 | +}); |
| 42 | + |
| 43 | +// This route will get all the books in the database |
| 44 | +app.get('/books/getbooks', controller.getBooks, (req, res) => { |
| 45 | + res.status(200).json(res.locals.getBooks); |
| 46 | +}); |
| 47 | + |
| 48 | +// This route gets orders from the Orders application |
| 49 | +app.get('/books/getordersinfo', controller.getorderinfo, (req, res) => { |
| 50 | + res.status(200).json(res.locals.getorderinfo); |
| 51 | +}); |
| 52 | + |
| 53 | +// Global error handler |
| 54 | +app.use((error, req, res, next) => { |
| 55 | + // console.log(err.stack); |
| 56 | + const defaultErr = { |
| 57 | + log: 'Express error handler caught unknown middleware error', |
| 58 | + status: 400, |
| 59 | + message: { err: 'An error occurred' }, |
| 60 | + }; |
| 61 | + const errorObj = Object.assign(defaultErr, error); |
| 62 | + console.log(`Here is the error object's response: ${errorObj.log}`); |
| 63 | + |
| 64 | + res.status(errorObj.status).json(errorObj.message); |
| 65 | +}); |
| 66 | + |
| 67 | +// app.listen(process.env.BOOKS_PORT, () => { |
| 68 | +// console.log(`Book server running on port ${process.env.BOOKS_PORT} ...`); |
| 69 | +// }); |
| 70 | + |
| 71 | +app.listen(8888, () => { |
| 72 | + console.log(`Book server running on port 8888...`); |
| 73 | +}); |
0 commit comments