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

F Teddy - stock updates #19

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
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
59 changes: 57 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,57 @@
# mongoose-crud
CRUD with Mongoose ODM
# mongodb-crud
CRUD with MongoDB

# Routing
basic routes for this project:

| Route | HTTP | Description |
| -------------- |:------:| ------------:|
| /books/add | POST | add a new book |
| /books/library | GET | get all books |
| /books/library/:_id | GET | Get a single book by ID |
| /books/edit/:id | PUT | Update a book by ID |
| /books/delete/:id | DELETE | Delete a book by ID |

| Route | HTTP | Description |
| -------------- |:------:| ------------:|
| /costumers/add | POST | add a new costumer |
| /costumers | GET | get all costumers |
| /costumers/:_id | GET | Get a single costumer by ID |
| /costumers/edit/:id | PUT | Update a costumer by ID |
| /costumers/delete/:id | DELETE | Delete a costumer by ID |

| Route | HTTP | Description |
| -------------- |:------:| :------------|
| /transactions/add | POST | add a new transaction |
| /transactions | GET | get all transactions |
| /transactions/:_id | GET | Get a single transaction by ID |
| /transactions/edit/:id | PUT | Update a transaction by ID |
| /transactions/delete/:id | DELETE | Delete a transaction by ID |
| /transactions/return/:transID | PATCH | Return the book borrowed at transaction ID and gives fines if applicable |


# Usage

Setting up
```
npm install
```

Starting with npm
```
npm start
```
or
```
npm run dev
```

#Book schema
```
isbn: string
title: string
author: string
category: string
stock : number
```
Access from localhost:3000/books with postman/insomnia
56 changes: 56 additions & 0 deletions app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
const express = require('express');
const path = require('path');
const favicon = require('serve-favicon');
const logger = require('morgan');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');

// require mongoose
const mongoose = require('mongoose')

const index = require('./routes/index');
const books = require('./routes/books');
const costumers = require('./routes/costumers');
const transactions = require('./routes/transactions');

// connect to database
mongoose.connect('mongodb://localhost:27017/mongooseNewb');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', index);
app.use('/books', books);
app.use('/costumers', costumers);
app.use('/transactions', transactions);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});

// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};

// render the error page
res.status(err.status || 500);
res.render('error');
});

module.exports = app;
92 changes: 92 additions & 0 deletions bin/www
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
#!/usr/bin/env node

/**
* Module dependencies.
*/

var app = require('../app');
var debug = require('debug')('mongoose-crud:server');
var http = require('http');

/**
* Get port from environment and store in Express.
*/

var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);

/**
* Create HTTP server.
*/

var server = http.createServer(app);

/**
* Listen on provided port, on all network interfaces.
*/

server.listen(port, ()=>{
console.log(`Listening on PORT ${port}`);
});
server.on('error', onError);
server.on('listening', onListening);

/**
* Normalize a port into a number, string, or false.
*/

function normalizePort(val) {
var port = parseInt(val, 10);

if (isNaN(port)) {
// named pipe
return val;
}

if (port >= 0) {
// port number
return port;
}

return false;
}

/**
* Event listener for HTTP server "error" event.
*/

function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}

var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;

// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}

/**
* Event listener for HTTP server "listening" event.
*/

function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
}
117 changes: 117 additions & 0 deletions controllers/bookController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
'use strict'
const Book = require('../models/Book.js')


class BookController {

static createBook(req, res) {
// return res.send('create book');
let newBook = new Book()
newBook.isbn = req.body.isbn;
newBook.title = req.body.title;
newBook.author = req.body.author;
newBook.category = req.body.category;
newBook.stock = req.body.stock;

// console.log(newBook);
newBook.save()
.then(createdBook => {
res.status(201).json({
message: 'New book created',
createdBook: createdBook
})
})
.catch(err => {
res.status(500).json({
message: err.message
})
})
}

static readBook(req, res) {
// return res.send('read all book');
Book.find()
.limit(10)
.exec()
.then(foundBooks => {
res.status(200).json({
message: 'Showing Books',
foundBooks: foundBooks
})
})
.catch(err => {
res.status(500).json({
message: err.message
})
})
}

static readOneBook(req, res) {
// return res.send('read all book');
Book.findOne({
_id: req.params._id
})
.exec()
.then(foundBook => {
res.status(200).json({
message: 'Showing Books',
foundBook: foundBook
})
})
.catch(err => {
res.status(500).json({
message: err.message
})
})
}

static updateBook(req, res) {
// res.send('update a book');
let id = req.params._id;
let updateData = {}
if (req.body.isbn) {updateData.isbn = req.body.isbn}
if (req.body.title) {updateData.title = req.body.title}
if (req.body.author) {updateData.author = req.body.author}
if (req.body.category) {updateData.category = req.body.category}
if (req.body.stock) {updateData.stock = req.body.stock}

Book.findByIdAndUpdate(id, updateData)
.exec()
.then(updatedBook => {
res.status(200).json({
message: 'Updated Book',
updatedBook: updatedBook,
updateData: updateData
})
})
.catch(err => {
res.status(500).json({
message: err.message
})
})
}

static deleteBook(req, res) {
// res.send('delete a book');
let id = req.params._id;

Book.deleteOne({_id: id})
.exec()
.then(confirm =>{
res.status(200).json({
message: 'Deleted Book',
confirm: confirm
})
})
.catch(err => {
res.status(500).json({
message: err.message
})
})
}

}

module.exports = {
BookController: BookController
};
Loading