Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Tim/microservice #3

Merged
merged 21 commits into from
Dec 18, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
node_modules


File renamed without changes.
21 changes: 0 additions & 21 deletions books/Book.js

This file was deleted.

88 changes: 88 additions & 0 deletions books/BookController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
const fetch = require('node-fetch');
const BookModel = require('./BookModel');


const BookController = {};

// This controller creates a book in the book db
BookController.createBook = (req, res, next) => {
const {
title, author, numberOfPages, publisher,
} = req.body;
console.log('This is the title ', req.body.title);
BookModel.create({
title, author, numberOfPages, publisher,
}, (err, result) => {
if (err) {
console.log(`This is the error I am getting back ${err}`);
return res.send(404).json(err);
}

res.locals.createBook = result;
console.log(`Book was successfully stored in db ${res.locals.createBook}`);
return next();
});
};

// This controller creates a book in the book db

BookController.getBooks = (req, res, next) => {
BookModel.find({}, (err, result) => {
if (err) {
return res.status(404).json(err);
}
res.locals.getBooks = result;
return next();
});
};


// This controller deletes books
BookController.deleteBook = (req, res, next) => {
const { id } = req.query;
console.log(`This is the id of the request ${id}`);
BookModel.findOneAndDelete({ _id: id }, (error, result) => {
if (error) {
console.log(`Deletion was not successful ${error}`);
return res.status(404).json(error);
}
res.locals.deleteBook = result;
console.log(`Deletion was successful ${res.locals.deleteBook}`);
return next();
});
};

// This controller gets order info from the order application
BookController.getorderinfo = (req, res, next) => {
// const { body } = req;
fetch('http://localhost:7777/getorders', {
method: 'GET',
headers: {
'Content-Type': 'Application/JSON',
Accept: 'application/json',
},
})
.then((response) => response.json())
.then((results) => {
// const info = results.forEach((curr) => JSON.stringify((curr)));
res.locals.getorderinfo = results;
return next();
})
.catch((error) => {
console.log(`There was an error in getting customers data ${error}`);
});
};
module.exports = BookController;


// app.delete('/book/:id', (req, res, next) => {
// Book.findOneAndRemove(req.params.id)
// .then(() => {
// res.send('Book successfully deleted');
// next();
// }).catch((err) => {
// if (err) {
// throw err;
// }
// });
// });
41 changes: 41 additions & 0 deletions books/BookModel.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
const mongoose = require('mongoose');

// pull schema from the mongoose object
const { Schema } = mongoose;

// database link
// can change but woun't advice that because the book application database lives here
const myURI = 'mongodb+srv://tim:tim@cluster0-khxef.mongodb.net/test?retryWrites=true&w=majority';

const URI = process.env.MONGO_URI || myURI;

// connect the database, if error, log will be sent to the terminal
mongoose.connect(URI, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('Connected!!!********* Books Database is live!!!'))
.catch((err) => console.log('Connection Error ', err));


// Schema for the database
const BooksSchema = new Schema({
title: {
type: String,
required: true,
},
author: {
type: String,
required: true,
},
numberOfPages: {
type: Number,
required: false,
},
publisher: {
type: String,
required: false,
},
});

// Database Model
const BookModel = mongoose.model('BookModel', BooksSchema);

module.exports = BookModel;
67 changes: 67 additions & 0 deletions books/BookServer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
const PORT = 4545;
const express = require('express');

const app = express();
const bodyParser = require('body-parser');
const controller = require('./BookController.js');


app.use(bodyParser.json());

// ********** I PROBABLY STILL NEED THIS PART FOR CHRONOS TO WORK AND DEBUG MY MICOSERVICE *************
// This requires the chronos middleware into the server ***Tim's comment
// const mw = require('../mwMongo.js');

// app.use('/', mw.microCom(path.basename(__filename)));

// CHAOS FLOW - SIMPLY A TEST FOR THE EXPESS SERVER
// app.use((req, res, next) => {
// console.log(
// `***************************************************************************************
// CHAOS FLOW TEST --- METHOD:${req.method}, PATH: ${
// req.url
// }, BODY: ${JSON.stringify(req.body)}, ID: ${req.query.id}
// ***************************************************************************************`,
// );
// next();
// });

// This route will create a new book!
app.post('/createbook', controller.createBook, (req, res) => {
console.log('Book creation was successfull!');
res.status(200).json(res.locals.createBook);
});

// This route will delete a book
app.delete('/deletebook:id?', controller.deleteBook, (req, res) => {
res.status(200).json(res.locals.deleteBook);
});

// This route will get all the books in the database
app.get('/getbooks', controller.getBooks, (req, res) => res.status(200).json(res.locals.getBooks));


// This route gets orders from the Orders application
app.get('/getordersinfo', controller.getorderinfo, (req, res) => {
res.status(200).json(res.locals.getorderinfo);
});


// This is my global error handler - isn't being used right now and it's not breaking anything so...
function errorHandler(error, req, res, next) {
// console.log(err.stack);
const defaultErr = {
log: 'Express error handler caught unknown middleware error',
status: 400,
message: { err: 'An error occurred' },
};
const errorObj = Object.assign(defaultErr, error);
console.log(`Here is the error object's response: ${errorObj.log}`);

res.status(errorObj.status).json(errorObj.message);
}

// Open an express server
app.listen(PORT, () => {
console.log(`Book server running on port ${PORT} ...`);
});
89 changes: 0 additions & 89 deletions books/books.js

This file was deleted.

Loading