diff --git a/app.js b/app.js new file mode 100644 index 0000000..c88d5c4 --- /dev/null +++ b/app.js @@ -0,0 +1,60 @@ +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'); + +const mongoose = require('mongoose'); +const dbUrl = 'mongodb://localhost:27017/library' + +const index = require('./routes/index'); +const users = require('./routes/users'); +const books = require('./routes/books'); +const customers = require('./routes/customers'); +const transactions = require('./routes/transactions'); + +const 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'))); + +mongoose.connect(dbUrl, (err) => { + if(!err) {console.log('Connected to Database');} + else {throw new Error(err);} +}) + +app.use('/', index); +app.use('/users', users); +app.use('/books', books); +app.use('/customers', customers); +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; diff --git a/bin/www b/bin/www new file mode 100755 index 0000000..d664139 --- /dev/null +++ b/bin/www @@ -0,0 +1,90 @@ +#!/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); +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); +} diff --git a/controllers/books.controller.js b/controllers/books.controller.js new file mode 100644 index 0000000..77ed0ff --- /dev/null +++ b/controllers/books.controller.js @@ -0,0 +1,77 @@ +'use strict' +const Book = require('../models/Book'); + +module.exports = { + create: (req,res) => { + const {isbn, title, author, category, stock} = req.body + const newBook = new Book({ + isbn: isbn || '978-1-xxxxxx-xx-x', + title: title || 'Untitled', + author: author || 'Unkown', + category: category || 'Unrated', + stock: stock || 1 + }); + newBook + .save() + .then((response) => { + return res.status(201).json({ + message: "New Book Created!", + response + }) + }) + .catch((err) => { + return res.status(500).json({ + message: err + }) + }) + }, + + readAll: (req, res) => { + Book + .find() + .exec() + .then((books) => { + res.status(200).send(books) + }) + .catch((err) => { + return res.status(500).json({ + message: err + }) + }) + }, + + updateOne: (req, res) => { + Book + .findByIdAndUpdate( + {_id: req.params.id}, + {$set: req.body} + ) + .then((response) => { + return res.status(200).json({ + message: "Book Updated!", + response + }) + }) + .catch((err) => { + return res.status(500).json({ + message: err + }) + }) + }, + + deleteOne: (req, res) => { + Book + .remove({_id: req.params.id}) + .then((response) => { + res.status(200).json({ + message: 'Book Deleted', + response + }) + }) + .catch((err) => { + return res.status(500).json({ + message: err + }) + }) + } +} \ No newline at end of file diff --git a/controllers/customer.controller.js b/controllers/customer.controller.js new file mode 100644 index 0000000..56a2478 --- /dev/null +++ b/controllers/customer.controller.js @@ -0,0 +1,77 @@ +'use strict' +const Customer = require('../models/Customer'); + +module.exports = { + create: (req,res) => { + const {name, memberid, address, zipcode, phone} = req.body + const newCustomer = new Customer({ + name: name || 'No name', + memberid: memberid || 'CLXXX', + address: address || 'Nomad', + zipcode: zipcode || 'xxxxx', + phone: phone || '911' + }); + newCustomer + .save() + .then((response) => { + return res.status(201).json({ + message: "New Customer Created!", + response + }) + }) + .catch((err) => { + return res.status(500).json({ + message: err + }) + }) + }, + + readAll: (req, res) => { + Customer + .find() + .exec() + .then((customers) => { + res.status(200).send(customers) + }) + .catch((err) => { + return res.status(500).json({ + message: err + }) + }) + }, + + updateOne: (req, res) => { + Customer + .findByIdAndUpdate( + {_id: req.params.id}, + {$set: req.body} + ) + .then((response) => { + return res.status(200).json({ + message: "Customer Data Updated!", + response + }) + }) + .catch((err) => { + return res.status(500).json({ + message: err + }) + }) + }, + + deleteOne: (req, res) => { + Customer + .remove({_id: req.params.id}) + .then((response) => { + res.status(200).json({ + message: 'Customer data Deleted', + response + }) + }) + .catch((err) => { + return res.status(500).json({ + message: err + }) + }) + } +} \ No newline at end of file diff --git a/controllers/transaction.controller.js b/controllers/transaction.controller.js new file mode 100644 index 0000000..0a85257 --- /dev/null +++ b/controllers/transaction.controller.js @@ -0,0 +1,96 @@ +'use strict' +const Transaction = require('../models/Transaction'); + +module.exports = { + create: (req,res) => { + const {member, days, out_date, booklist} = req.body; + const newTransaction = new Transaction({ + member: member || '5a9e6edb3320151b49e960b0', + days: days || 3, + out_date: out_date, + booklist: booklist || [] + }); + newTransaction + .save() + .then((response) => { + return res.status(201).json({ + message: "New Transaction Created!", + response + }) + }) + .catch((err) => { + return res.status(500).json({ + message: err + }) + }) + }, + + readAll: (req, res) => { + Transaction + .find() + .populate('member') + .populate('booklist') + .exec() + .then((transactions) => { + res.status(200).send(transactions) + }) + .catch((err) => { + return res.status(500).json({ + message: err + }) + }) + }, + + updateOne: (req, res) => { + Transaction + .findById(req.params.id) + .then((trans) => { + if(trans) { + req.body.due_date = trans.due_date + Transaction + .update( + {_id: req.params.id}, + {$set: req.body} + ) + .then((data) => res.send(trans)) + } else {reject()} + }) + .catch((err) => { + return res.status(500).json({ + message: 'Transaction not exist' + }) + }) + // Transaction + // .findByIdAndUpdate( + // {_id: req.params.id}, + // {$set: req.body} + // ) + // .then((response) => { + // return res.status(200).json({ + // message: "Transaction Data Updated!", + // response + // }) + // }) + // .catch((err) => { + // return res.status(500).json({ + // message: err + // }) + // }) + }, + + deleteOne: (req, res) => { + Transaction + .remove({_id: req.params.id}) + .then((response) => { + res.status(200).json({ + message: 'Transaction data Deleted', + response + }) + }) + .catch((err) => { + return res.status(500).json({ + message: err + }) + }) + } +} \ No newline at end of file diff --git a/models/Book.js b/models/Book.js new file mode 100644 index 0000000..1019ab6 --- /dev/null +++ b/models/Book.js @@ -0,0 +1,12 @@ +'use strict' + +const mongoose = require('mongoose'); +const schema = mongoose.Schema; + +module.exports = mongoose.model('Book', schema({ + isbn: String, + title: String, + author: String, + category: String, + stock: Number +})); \ No newline at end of file diff --git a/models/Customer.js b/models/Customer.js new file mode 100644 index 0000000..a451889 --- /dev/null +++ b/models/Customer.js @@ -0,0 +1,12 @@ +'use strict' + +const mongoose = require('mongoose'); +const schema = mongoose.Schema; + +module.exports = mongoose.model('Customer', schema({ + name: String, + memberid: String, + address: String, + zipcode: String, + phone: String +})) \ No newline at end of file diff --git a/models/Transaction.js b/models/Transaction.js new file mode 100644 index 0000000..c1b31c2 --- /dev/null +++ b/models/Transaction.js @@ -0,0 +1,37 @@ +'use strict' + +const mongoose = require('mongoose'); +const schema = mongoose.Schema; + +module.exports = mongoose.model('Transaction', schema({ + member: { + type: schema.Types.ObjectId, + ref: 'Customer' + }, + days: Number, + out_date : { + type: Date, + default: Date.now + }, + due_date : Date, + in_date : Date, + fine: Number, + booklist: [{ + type: schema.Types.ObjectId, + ref: 'Book' + }]}) + .pre('save', function() { + this.due_date = +new Date(this.out_date) + Number(this.days)*24*60*60*1000; + }) + .pre("update", function() { + console.log('=====>',this._update.$set) + this._update.$set.in_date = new Date(); + let diffDays = this._update.$set.in_date.getDate() - this._update.$set.due_date.getDate(); + console.log(Math.abs(diffDays)) + if(diffDays<0) { + this._update.$set.fine = Math.abs(diffDays)*1000 + } else { + this._update.$set.fine = 0; + } + }) +) \ No newline at end of file diff --git a/package.json b/package.json new file mode 100644 index 0000000..e68bbaa --- /dev/null +++ b/package.json @@ -0,0 +1,18 @@ +{ + "name": "mongoose-crud", + "version": "0.0.0", + "private": true, + "scripts": { + "start": "node ./bin/www" + }, + "dependencies": { + "body-parser": "~1.18.2", + "cookie-parser": "~1.4.3", + "debug": "~2.6.9", + "ejs": "~2.5.7", + "express": "~4.15.5", + "mongoose": "^5.0.9", + "morgan": "~1.9.0", + "serve-favicon": "~2.4.5" + } +} diff --git a/public/stylesheets/style.css b/public/stylesheets/style.css new file mode 100644 index 0000000..9453385 --- /dev/null +++ b/public/stylesheets/style.css @@ -0,0 +1,8 @@ +body { + padding: 50px; + font: 14px "Lucida Grande", Helvetica, Arial, sans-serif; +} + +a { + color: #00B7FF; +} diff --git a/routes/books.js b/routes/books.js new file mode 100644 index 0000000..6e00197 --- /dev/null +++ b/routes/books.js @@ -0,0 +1,11 @@ +'use strict' + +const router = require('express').Router(); +const {create ,readAll, updateOne, deleteOne} = require('../controllers/books.controller'); + +router.post('/', create); +router.get('/', readAll); +router.put('/:id', updateOne); +router.delete('/:id', deleteOne); + +module.exports = router; \ No newline at end of file diff --git a/routes/customers.js b/routes/customers.js new file mode 100644 index 0000000..6735423 --- /dev/null +++ b/routes/customers.js @@ -0,0 +1,11 @@ +'use strict' + +const router = require('express').Router(); +const {create ,readAll, updateOne, deleteOne} = require('../controllers/customer.controller'); + +router.post('/', create); +router.get('/', readAll); +router.put('/:id', updateOne); +router.delete('/:id', deleteOne); + +module.exports = router; \ No newline at end of file diff --git a/routes/index.js b/routes/index.js new file mode 100644 index 0000000..ecca96a --- /dev/null +++ b/routes/index.js @@ -0,0 +1,9 @@ +var express = require('express'); +var router = express.Router(); + +/* GET home page. */ +router.get('/', function(req, res, next) { + res.render('index', { title: 'Express' }); +}); + +module.exports = router; diff --git a/routes/transactions.js b/routes/transactions.js new file mode 100644 index 0000000..d7b3fea --- /dev/null +++ b/routes/transactions.js @@ -0,0 +1,11 @@ +'use strict' + +const router = require('express').Router(); +const {create ,readAll, updateOne, deleteOne} = require('../controllers/transaction.controller'); + +router.post('/', create); +router.get('/', readAll); +router.put('/:id', updateOne); +router.delete('/:id', deleteOne); + +module.exports = router; \ No newline at end of file diff --git a/routes/users.js b/routes/users.js new file mode 100644 index 0000000..623e430 --- /dev/null +++ b/routes/users.js @@ -0,0 +1,9 @@ +var express = require('express'); +var router = express.Router(); + +/* GET users listing. */ +router.get('/', function(req, res, next) { + res.send('respond with a resource'); +}); + +module.exports = router; diff --git a/views/error.ejs b/views/error.ejs new file mode 100644 index 0000000..7cf94ed --- /dev/null +++ b/views/error.ejs @@ -0,0 +1,3 @@ +

<%= message %>

+

<%= error.status %>

+
<%= error.stack %>
diff --git a/views/index.ejs b/views/index.ejs new file mode 100644 index 0000000..7b7a1d6 --- /dev/null +++ b/views/index.ejs @@ -0,0 +1,11 @@ + + + + <%= title %> + + + +

<%= title %>

+

Welcome to <%= title %>

+ +