From 4c4eccc65a82d61abb5189fd2f6db90dd978128b Mon Sep 17 00:00:00 2001 From: FTeddy Date: Tue, 6 Mar 2018 16:27:18 +0700 Subject: [PATCH 1/7] set up controller and models --- app.js | 49 +++ bin/www | 92 +++++ controllers/bookController.js | 36 ++ controllers/costumerController.js | 36 ++ models/Book.js | 17 + models/Costumer.js | 17 + models/Transaction.js | 28 ++ package-lock.json | 557 ++++++++++++++++++++++++++++++ package.json | 19 + public/stylesheets/style.css | 8 + routes/books.js | 15 + routes/costumers.js | 15 + routes/index.js | 9 + views/error.ejs | 3 + views/index.ejs | 11 + 15 files changed, 912 insertions(+) create mode 100644 app.js create mode 100644 bin/www create mode 100644 controllers/bookController.js create mode 100644 controllers/costumerController.js create mode 100644 models/Book.js create mode 100644 models/Costumer.js create mode 100644 models/Transaction.js create mode 100644 package-lock.json create mode 100644 package.json create mode 100644 public/stylesheets/style.css create mode 100644 routes/books.js create mode 100644 routes/costumers.js create mode 100644 routes/index.js create mode 100644 views/error.ejs create mode 100644 views/index.ejs diff --git a/app.js b/app.js new file mode 100644 index 0000000..82538e1 --- /dev/null +++ b/app.js @@ -0,0 +1,49 @@ +var express = require('express'); +var path = require('path'); +var favicon = require('serve-favicon'); +var logger = require('morgan'); +var cookieParser = require('cookie-parser'); +var bodyParser = require('body-parser'); + +var index = require('./routes/index'); +var books = require('./routes/books'); +var costumers = require('./routes/costumers'); + + +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); + +// 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 100644 index 0000000..5673eff --- /dev/null +++ b/bin/www @@ -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); +} diff --git a/controllers/bookController.js b/controllers/bookController.js new file mode 100644 index 0000000..6ecfb0c --- /dev/null +++ b/controllers/bookController.js @@ -0,0 +1,36 @@ +'use strict' + + +class BookController { + + static createBook(req, res) { + return res.send('create book'); + + } + + static readBook(req, res) { + return res.send('read all book'); + + } + + static readOneBook(req, res) { + return res.send('read all book'); + + } + + static updateBook(req, res) { + res.send('update a book'); + + + } + + static deleteBook(req, res) { + res.send('delete a book'); + + } + +} + +module.exports = { + BookController: BookController +}; diff --git a/controllers/costumerController.js b/controllers/costumerController.js new file mode 100644 index 0000000..40c6f0d --- /dev/null +++ b/controllers/costumerController.js @@ -0,0 +1,36 @@ +'use strict' + + +class CostumerController { + + static createCostumer(req, res) { + // return res.send('create book'); + + } + + static readCostumer(req, res) { + // return res.send('read all book'); + + } + + static readOneCostumer(req, res) { + // return res.send('read all book'); + + } + + static updateCostumer(req, res) { + // res.send('update a book'); + + + } + + static deleteCostumer(req, res) { + // res.send('delete a book'); + + } + +} + +module.exports = { + CostumerController: CostumerController +}; diff --git a/models/Book.js b/models/Book.js new file mode 100644 index 0000000..ff0744d --- /dev/null +++ b/models/Book.js @@ -0,0 +1,17 @@ +const mongoose = require('mongoose'); +const Schema = mongoose.Schema + +const BookSchema = new Schema ({ + isbn: String, + title: String, + author: String, + category: String, + stock: Number, + createdAt: { + type: Date, + default: Date.now + } +}) + + +module.exports = mongoose.model('Book', BookSchema); diff --git a/models/Costumer.js b/models/Costumer.js new file mode 100644 index 0000000..08d7623 --- /dev/null +++ b/models/Costumer.js @@ -0,0 +1,17 @@ +const mongoose = require('mongoose'); +const Schema = mongoose.Schema + +const CostumerSchema = new Schema ({ + name: String, + memberId: String, + address: String, + zipcode: String, + phone: String, + createdAt: { + type: Date, + default: Date.now + } +}) + + +module.exports = mongoose.model('Costumer', CostumerSchema); diff --git a/models/Transaction.js b/models/Transaction.js new file mode 100644 index 0000000..5812445 --- /dev/null +++ b/models/Transaction.js @@ -0,0 +1,28 @@ +const mongoose = require('mongoose'); +const Schema = mongoose.Schema + +const TransactionSchema = new Schema ({ + member: { + type: Schema.Types.ObjectId, + ref: 'Costumer' + }, + days: Number, + out_date: { + type: Date, + default: Date.now + }, + due_date: Date, + in_date: Date, + fine: Number, + booklist: [{ + type: Schema.Types.ObjectId, + ref: 'Book' + }] + createdAt: { + type: Date, + default: Date.now + } +}) + + +module.exports = mongoose.model('Transaction', TransactionSchema); diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..02424ad --- /dev/null +++ b/package-lock.json @@ -0,0 +1,557 @@ +{ + "name": "mongoose-crud", + "version": "0.0.0", + "lockfileVersion": 1, + "requires": true, + "dependencies": { + "accepts": { + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.5.tgz", + "integrity": "sha1-63d99gEXI6OxTopywIBcjoZ0a9I=", + "requires": { + "mime-types": "2.1.18", + "negotiator": "0.6.1" + } + }, + "array-flatten": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", + "integrity": "sha1-ml9pkFGx5wczKPKgCJaLZOopVdI=" + }, + "async": { + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/async/-/async-2.1.4.tgz", + "integrity": "sha1-LSFgx3iAMuTdbL4lAvH5osj2zeQ=", + "requires": { + "lodash": "4.17.5" + } + }, + "basic-auth": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/basic-auth/-/basic-auth-2.0.0.tgz", + "integrity": "sha1-AV2z81PgLlY3d1X5YnQuiYHnu7o=", + "requires": { + "safe-buffer": "5.1.1" + } + }, + "bluebird": { + "version": "3.5.0", + "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.5.0.tgz", + "integrity": "sha1-eRQg1/VR7qKJdFOop3ZT+WYG1nw=" + }, + "body-parser": { + "version": "1.18.2", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.18.2.tgz", + "integrity": "sha1-h2eKGdhLR9hZuDGZvVm84iKxBFQ=", + "requires": { + "bytes": "3.0.0", + "content-type": "1.0.4", + "debug": "2.6.9", + "depd": "1.1.2", + "http-errors": "1.6.2", + "iconv-lite": "0.4.19", + "on-finished": "2.3.0", + "qs": "6.5.1", + "raw-body": "2.3.2", + "type-is": "1.6.16" + } + }, + "bson": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/bson/-/bson-1.0.5.tgz", + "integrity": "sha512-D4SCtud6mlEb48kXdTHU31DRU0bsgOJ+4St1Dcx30uYNnf/aGc+hC9gHB/z0Eth8HYYs/hr0SFdyZViht19SwA==" + }, + "bytes": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.0.0.tgz", + "integrity": "sha1-0ygVQE1olpn4Wk6k+odV3ROpYEg=" + }, + "content-disposition": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.2.tgz", + "integrity": "sha1-DPaLud318r55YcOoUXjLhdunjLQ=" + }, + "content-type": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.4.tgz", + "integrity": "sha512-hIP3EEPs8tB9AT1L+NUqtwOAps4mk2Zob89MWXMHjHWg9milF/j4osnnQLXBCBFBk/tvIG/tUc9mOUJiPBhPXA==" + }, + "cookie": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.3.1.tgz", + "integrity": "sha1-5+Ch+e9DtMi6klxcWpboBtFoc7s=" + }, + "cookie-parser": { + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/cookie-parser/-/cookie-parser-1.4.3.tgz", + "integrity": "sha1-D+MfoZ0AC5X0qt8fU/3CuKIDuqU=", + "requires": { + "cookie": "0.3.1", + "cookie-signature": "1.0.6" + } + }, + "cookie-signature": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz", + "integrity": "sha1-4wOogrNCzD7oylE6eZmXNNqzriw=" + }, + "debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "requires": { + "ms": "2.0.0" + } + }, + "depd": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz", + "integrity": "sha1-m81S4UwJd2PnSbJ0xDRu0uVgtak=" + }, + "destroy": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.0.4.tgz", + "integrity": "sha1-l4hXRCxEdJ5CBmE+N5RiBYJqvYA=" + }, + "ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha1-WQxhFWsK4vTwJVcyoViyZrxWsh0=" + }, + "ejs": { + "version": "2.5.7", + "resolved": "https://registry.npmjs.org/ejs/-/ejs-2.5.7.tgz", + "integrity": "sha1-zIcsFoiArjxxiXYv1f/ACJbJUYo=" + }, + "encodeurl": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz", + "integrity": "sha1-rT/0yG7C0CkyL1oCw6mmBslbP1k=" + }, + "escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha1-Aljq5NPQwJdN4cFpGI7wBR0dGYg=" + }, + "etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha1-Qa4u62XvpiJorr/qg6x9eSmbCIc=" + }, + "express": { + "version": "4.15.5", + "resolved": "https://registry.npmjs.org/express/-/express-4.15.5.tgz", + "integrity": "sha1-ZwI1ypWYiQpa6BcLg9tyK4Qu2Sc=", + "requires": { + "accepts": "1.3.5", + "array-flatten": "1.1.1", + "content-disposition": "0.5.2", + "content-type": "1.0.4", + "cookie": "0.3.1", + "cookie-signature": "1.0.6", + "debug": "2.6.9", + "depd": "1.1.2", + "encodeurl": "1.0.2", + "escape-html": "1.0.3", + "etag": "1.8.1", + "finalhandler": "1.0.6", + "fresh": "0.5.2", + "merge-descriptors": "1.0.1", + "methods": "1.1.2", + "on-finished": "2.3.0", + "parseurl": "1.3.2", + "path-to-regexp": "0.1.7", + "proxy-addr": "1.1.5", + "qs": "6.5.0", + "range-parser": "1.2.0", + "send": "0.15.6", + "serve-static": "1.12.6", + "setprototypeof": "1.0.3", + "statuses": "1.3.1", + "type-is": "1.6.16", + "utils-merge": "1.0.0", + "vary": "1.1.2" + }, + "dependencies": { + "qs": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.5.0.tgz", + "integrity": "sha512-fjVFjW9yhqMhVGwRExCXLhJKrLlkYSaxNWdyc9rmHlrVZbk35YHH312dFd7191uQeXkI3mKLZTIbSvIeFwFemg==" + }, + "statuses": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-1.3.1.tgz", + "integrity": "sha1-+vUbnrdKrvOzrPStX2Gr8ky3uT4=" + } + } + }, + "finalhandler": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.0.6.tgz", + "integrity": "sha1-AHrqM9Gk0+QgF/YkhIrVjSEvgU8=", + "requires": { + "debug": "2.6.9", + "encodeurl": "1.0.2", + "escape-html": "1.0.3", + "on-finished": "2.3.0", + "parseurl": "1.3.2", + "statuses": "1.3.1", + "unpipe": "1.0.0" + }, + "dependencies": { + "statuses": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-1.3.1.tgz", + "integrity": "sha1-+vUbnrdKrvOzrPStX2Gr8ky3uT4=" + } + } + }, + "forwarded": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.1.2.tgz", + "integrity": "sha1-mMI9qxF1ZXuMBXPozszZGw/xjIQ=" + }, + "fresh": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", + "integrity": "sha1-PYyt2Q2XZWn6g1qx+OSyOhBWBac=" + }, + "http-errors": { + "version": "1.6.2", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-1.6.2.tgz", + "integrity": "sha1-CgAsyFcHGSp+eUbO7cERVfYOxzY=", + "requires": { + "depd": "1.1.1", + "inherits": "2.0.3", + "setprototypeof": "1.0.3", + "statuses": "1.4.0" + }, + "dependencies": { + "depd": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/depd/-/depd-1.1.1.tgz", + "integrity": "sha1-V4O04cRZ8G+lyif5kfPQbnoxA1k=" + } + } + }, + "iconv-lite": { + "version": "0.4.19", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.19.tgz", + "integrity": "sha512-oTZqweIP51xaGPI4uPa56/Pri/480R+mo7SeU+YETByQNhDG55ycFyNLIgta9vXhILrxXDmF7ZGhqZIcuN0gJQ==" + }, + "inherits": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", + "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=" + }, + "ipaddr.js": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.4.0.tgz", + "integrity": "sha1-KWrKh4qCGBbluF0KKFqZvP9FgvA=" + }, + "kareem": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/kareem/-/kareem-2.0.5.tgz", + "integrity": "sha512-dfvpj3mCGJLZuADInhYrKaXkGarJxDqnTEiF91wK6fqwdCRmN+O4aEp8575UjZlQzDkzLI1WDL1uU7vyupURqw==" + }, + "lodash": { + "version": "4.17.5", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.5.tgz", + "integrity": "sha512-svL3uiZf1RwhH+cWrfZn3A4+U58wbP0tGVTLQPbjplZxZ8ROD9VLuNgsRniTlLe7OlSqR79RUehXgpBW/s0IQw==" + }, + "lodash.get": { + "version": "4.4.2", + "resolved": "https://registry.npmjs.org/lodash.get/-/lodash.get-4.4.2.tgz", + "integrity": "sha1-LRd/ZS+jHpObRDjVNBSZ36OCXpk=" + }, + "media-typer": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", + "integrity": "sha1-hxDXrwqmJvj/+hzgAWhUUmMlV0g=" + }, + "merge-descriptors": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.1.tgz", + "integrity": "sha1-sAqqVW3YtEVoFQ7J0blT8/kMu2E=" + }, + "methods": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", + "integrity": "sha1-VSmk1nZUE07cxSZmVoNbD4Ua/O4=" + }, + "mime": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/mime/-/mime-1.3.4.tgz", + "integrity": "sha1-EV+eO2s9rylZmDyzjxSaLUDrXVM=" + }, + "mime-db": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.33.0.tgz", + "integrity": "sha512-BHJ/EKruNIqJf/QahvxwQZXKygOQ256myeN/Ew+THcAa5q+PjyTTMMeNQC4DZw5AwfvelsUrA6B67NKMqXDbzQ==" + }, + "mime-types": { + "version": "2.1.18", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.18.tgz", + "integrity": "sha512-lc/aahn+t4/SWV/qcmumYjymLsWfN3ELhpmVuUFjgsORruuZPVSwAQryq+HHGvO/SI2KVX26bx+En+zhM8g8hQ==", + "requires": { + "mime-db": "1.33.0" + } + }, + "mongodb": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/mongodb/-/mongodb-3.0.4.tgz", + "integrity": "sha512-90YIIs7A4ko4kCGafxxXj3foexCAlJBC0YLwwIKgSLoE7Vni2IqUMz6HSsZ3zbXOfR1KWtxfnc0RyAMAY/ViLg==", + "requires": { + "mongodb-core": "3.0.4" + } + }, + "mongodb-core": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/mongodb-core/-/mongodb-core-3.0.4.tgz", + "integrity": "sha512-OTH267FjfwBdEufSnrgd+u8HuLWRuQ6p8DR0XirPl2BdlLEMh4XwjJf1RTlruILp5p2m1w8dDC8rCxibC3W8qQ==", + "requires": { + "bson": "1.0.5", + "require_optional": "1.0.1" + } + }, + "mongoose": { + "version": "5.0.9", + "resolved": "https://registry.npmjs.org/mongoose/-/mongoose-5.0.9.tgz", + "integrity": "sha512-utGA97zd1R5NwRcqjhyPZP7sSExLQv9/KYAgFqtl6SRfp9vJXu5VPGwf6NdDRqUeh6e5v/tXVomkS2IPiSezxg==", + "requires": { + "async": "2.1.4", + "bson": "1.0.5", + "kareem": "2.0.5", + "lodash.get": "4.4.2", + "mongodb": "3.0.4", + "mongoose-legacy-pluralize": "1.0.2", + "mpath": "0.3.0", + "mquery": "3.0.0", + "ms": "2.0.0", + "regexp-clone": "0.0.1", + "sliced": "1.0.1" + } + }, + "mongoose-legacy-pluralize": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/mongoose-legacy-pluralize/-/mongoose-legacy-pluralize-1.0.2.tgz", + "integrity": "sha512-Yo/7qQU4/EyIS8YDFSeenIvXxZN+ld7YdV9LqFVQJzTLye8unujAWPZ4NWKfFA+RNjh+wvTWKY9Z3E5XM6ZZiQ==" + }, + "morgan": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/morgan/-/morgan-1.9.0.tgz", + "integrity": "sha1-0B+mxlhZt2/PMbPLU6OCGjEdgFE=", + "requires": { + "basic-auth": "2.0.0", + "debug": "2.6.9", + "depd": "1.1.2", + "on-finished": "2.3.0", + "on-headers": "1.0.1" + } + }, + "mpath": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/mpath/-/mpath-0.3.0.tgz", + "integrity": "sha1-elj3iem1/TyUUgY0FXlg8mvV70Q=" + }, + "mquery": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/mquery/-/mquery-3.0.0.tgz", + "integrity": "sha512-WL1Lk8v4l8VFSSwN3yCzY9TXw+fKVYKn6f+w86TRzOLSE8k1yTgGaLBPUByJQi8VcLbOdnUneFV/y3Kv874pnQ==", + "requires": { + "bluebird": "3.5.0", + "debug": "2.6.9", + "regexp-clone": "0.0.1", + "sliced": "0.0.5" + }, + "dependencies": { + "sliced": { + "version": "0.0.5", + "resolved": "https://registry.npmjs.org/sliced/-/sliced-0.0.5.tgz", + "integrity": "sha1-XtwETKTrb3gW1Qui/GPiXY/kcH8=" + } + } + }, + "ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=" + }, + "negotiator": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.1.tgz", + "integrity": "sha1-KzJxhOiZIQEXeyhWP7XnECrNDKk=" + }, + "on-finished": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.3.0.tgz", + "integrity": "sha1-IPEzZIGwg811M3mSoWlxqi2QaUc=", + "requires": { + "ee-first": "1.1.1" + } + }, + "on-headers": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/on-headers/-/on-headers-1.0.1.tgz", + "integrity": "sha1-ko9dD0cNSTQmUepnlLCFfBAGk/c=" + }, + "parseurl": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.2.tgz", + "integrity": "sha1-/CidTtiZMRlGDBViUyYs3I3mW/M=" + }, + "path-to-regexp": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.7.tgz", + "integrity": "sha1-32BBeABfUi8V60SQ5yR6G/qmf4w=" + }, + "proxy-addr": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-1.1.5.tgz", + "integrity": "sha1-ccDuOxAt4/IC87ZPYI0XP8uhqRg=", + "requires": { + "forwarded": "0.1.2", + "ipaddr.js": "1.4.0" + } + }, + "qs": { + "version": "6.5.1", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.5.1.tgz", + "integrity": "sha512-eRzhrN1WSINYCDCbrz796z37LOe3m5tmW7RQf6oBntukAG1nmovJvhnwHHRMAfeoItc1m2Hk02WER2aQ/iqs+A==" + }, + "range-parser": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.0.tgz", + "integrity": "sha1-9JvmtIeJTdxA3MlKMi9hEJLgDV4=" + }, + "raw-body": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.3.2.tgz", + "integrity": "sha1-vNYMd9Prk83gBQKVw/N5OJvIj4k=", + "requires": { + "bytes": "3.0.0", + "http-errors": "1.6.2", + "iconv-lite": "0.4.19", + "unpipe": "1.0.0" + } + }, + "regexp-clone": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/regexp-clone/-/regexp-clone-0.0.1.tgz", + "integrity": "sha1-p8LgmJH9vzj7sQ03b7cwA+aKxYk=" + }, + "require_optional": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/require_optional/-/require_optional-1.0.1.tgz", + "integrity": "sha512-qhM/y57enGWHAe3v/NcwML6a3/vfESLe/sGM2dII+gEO0BpKRUkWZow/tyloNqJyN6kXSl3RyyM8Ll5D/sJP8g==", + "requires": { + "resolve-from": "2.0.0", + "semver": "5.5.0" + } + }, + "resolve-from": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-2.0.0.tgz", + "integrity": "sha1-lICrIOlP+h2egKgEx+oUdhGWa1c=" + }, + "safe-buffer": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.1.tgz", + "integrity": "sha512-kKvNJn6Mm93gAczWVJg7wH+wGYWNrDHdWvpUmHyEsgCtIwwo3bqPtV4tR5tuPaUhTOo/kvhVwd8XwwOllGYkbg==" + }, + "semver": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.5.0.tgz", + "integrity": "sha512-4SJ3dm0WAwWy/NVeioZh5AntkdJoWKxHxcmyP622fOkgHa4z3R0TdBJICINyaSDE6uNwVc8gZr+ZinwZAH4xIA==" + }, + "send": { + "version": "0.15.6", + "resolved": "https://registry.npmjs.org/send/-/send-0.15.6.tgz", + "integrity": "sha1-IPI6nJJbdiq4JwX+L52yUqzkfjQ=", + "requires": { + "debug": "2.6.9", + "depd": "1.1.2", + "destroy": "1.0.4", + "encodeurl": "1.0.2", + "escape-html": "1.0.3", + "etag": "1.8.1", + "fresh": "0.5.2", + "http-errors": "1.6.2", + "mime": "1.3.4", + "ms": "2.0.0", + "on-finished": "2.3.0", + "range-parser": "1.2.0", + "statuses": "1.3.1" + }, + "dependencies": { + "statuses": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-1.3.1.tgz", + "integrity": "sha1-+vUbnrdKrvOzrPStX2Gr8ky3uT4=" + } + } + }, + "serve-favicon": { + "version": "2.4.5", + "resolved": "https://registry.npmjs.org/serve-favicon/-/serve-favicon-2.4.5.tgz", + "integrity": "sha512-s7F8h2NrslMkG50KxvlGdj+ApSwaLex0vexuJ9iFf3GLTIp1ph/l1qZvRe9T9TJEYZgmq72ZwJ2VYiAEtChknw==", + "requires": { + "etag": "1.8.1", + "fresh": "0.5.2", + "ms": "2.0.0", + "parseurl": "1.3.2", + "safe-buffer": "5.1.1" + } + }, + "serve-static": { + "version": "1.12.6", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.12.6.tgz", + "integrity": "sha1-uXN3P2NEmTTaVOW+ul4x2fQhFXc=", + "requires": { + "encodeurl": "1.0.2", + "escape-html": "1.0.3", + "parseurl": "1.3.2", + "send": "0.15.6" + } + }, + "setprototypeof": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.0.3.tgz", + "integrity": "sha1-ZlZ+NwQ+608E2RvWWMDL77VbjgQ=" + }, + "sliced": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/sliced/-/sliced-1.0.1.tgz", + "integrity": "sha1-CzpmK10Ewxd7GSa+qCsD+Dei70E=" + }, + "statuses": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-1.4.0.tgz", + "integrity": "sha512-zhSCtt8v2NDrRlPQpCNtw/heZLtfUDqxBM1udqikb/Hbk52LK4nQSwr10u77iopCW5LsyHpuXS0GnEc48mLeew==" + }, + "type-is": { + "version": "1.6.16", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.16.tgz", + "integrity": "sha512-HRkVv/5qY2G6I8iab9cI7v1bOIdhm94dVjQCPFElW9W+3GeDOSHmy2EBYe4VTApuzolPcmgFTN3ftVJRKR2J9Q==", + "requires": { + "media-typer": "0.3.0", + "mime-types": "2.1.18" + } + }, + "unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha1-sr9O6FFKrmFltIF4KdIbLvSZBOw=" + }, + "utils-merge": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.0.tgz", + "integrity": "sha1-ApT7kiu5N1FTVBxPcJYjHyh8ivg=" + }, + "vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha1-IpnwLG3tMNSllhsLn3RSShj2NPw=" + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..66b6135 --- /dev/null +++ b/package.json @@ -0,0 +1,19 @@ +{ + "name": "mongoose-crud", + "version": "0.0.0", + "private": true, + "scripts": { + "start": "node ./bin/www", + "dev": "nodemon ./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..dd7aa9c --- /dev/null +++ b/routes/books.js @@ -0,0 +1,15 @@ +var express = require('express'); +const BookController = require('../controllers/bookController.js').BookController +var router = express.Router(); + + +/* GET users listing. */ +router.post('/add', BookController.createBook); + +router.get('/library', BookController.readBook); +router.get('/library/:_id', BookController.readOneBook); + +router.put('/edit/:_id', BookController.updateBook); +router.delete('/delete/:_id', BookController.deleteBook); + +module.exports = router; diff --git a/routes/costumers.js b/routes/costumers.js new file mode 100644 index 0000000..3b21659 --- /dev/null +++ b/routes/costumers.js @@ -0,0 +1,15 @@ +var express = require('express'); +const CostumerController = require('../controllers/costumerController.js').CostumerController +var router = express.Router(); + + +/* GET users listing. */ +router.post('/add', CostumerController.createCostumer); + +router.get('/library', CostumerController.readCostumer); +router.get('/library/:_id', CostumerController.readOneCostumer); + +router.put('/edit/:_id', CostumerController.updateCostumer); +router.delete('/delete/:_id', CostumerController.deleteCostumer); + +module.exports = router; 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/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 %>

+ + From 96b6d921f43c46960fd8fea50f74b2b140b23d6b Mon Sep 17 00:00:00 2001 From: FTeddy Date: Tue, 6 Mar 2018 17:35:41 +0700 Subject: [PATCH 2/7] release 1 books CRUD --- app.js | 27 ++++++---- controllers/bookController.js | 97 ++++++++++++++++++++++++++++++++--- 2 files changed, 105 insertions(+), 19 deletions(-) diff --git a/app.js b/app.js index 82538e1..e1ad41f 100644 --- a/app.js +++ b/app.js @@ -1,14 +1,19 @@ -var express = require('express'); -var path = require('path'); -var favicon = require('serve-favicon'); -var logger = require('morgan'); -var cookieParser = require('cookie-parser'); -var bodyParser = require('body-parser'); - -var index = require('./routes/index'); -var books = require('./routes/books'); -var costumers = require('./routes/costumers'); - +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'); + +// connect to database +mongoose.connect('mongodb://localhost:27017/mongooseNewb'); var app = express(); diff --git a/controllers/bookController.js b/controllers/bookController.js index 6ecfb0c..5b12be0 100644 --- a/controllers/bookController.js +++ b/controllers/bookController.js @@ -1,32 +1,113 @@ 'use strict' +const Book = require('../models/Book.js') class BookController { static createBook(req, res) { - return res.send('create book'); + // 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'); - + // 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'); - + // 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'); - + // 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'); + // 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 + }) + }) } } From c4f888baf6548140df42dab7399c1513cba128a1 Mon Sep 17 00:00:00 2001 From: FTeddy Date: Tue, 6 Mar 2018 18:31:04 +0700 Subject: [PATCH 3/7] release 3 transaction basic --- app.js | 2 + controllers/costumerController.js | 97 ++++++++++++++++++++-- controllers/transactionController.js | 116 +++++++++++++++++++++++++++ models/Transaction.js | 12 ++- routes/books.js | 1 - routes/costumers.js | 5 +- routes/transactions.js | 17 ++++ 7 files changed, 236 insertions(+), 14 deletions(-) create mode 100644 controllers/transactionController.js create mode 100644 routes/transactions.js diff --git a/app.js b/app.js index e1ad41f..432fd65 100644 --- a/app.js +++ b/app.js @@ -11,6 +11,7 @@ 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'); @@ -32,6 +33,7 @@ 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) { diff --git a/controllers/costumerController.js b/controllers/costumerController.js index 40c6f0d..05e819d 100644 --- a/controllers/costumerController.js +++ b/controllers/costumerController.js @@ -1,32 +1,115 @@ 'use strict' +const Costumer = require('../models/Costumer.js') + class CostumerController { static createCostumer(req, res) { - // return res.send('create book'); + // return res.send('create costumer'); + let newCostumer = new Costumer() + newCostumer.name = req.body.name; + newCostumer.memberId = req.body.memberId; + newCostumer.address = req.body.address; + newCostumer.zipcode = req.body.zipcode; + newCostumer.phone = req.body.phone; + // console.log(newCostumer); + newCostumer.save() + .then(createdCostumer => { + res.status(201).json({ + message: 'New costumer created', + createdCostumer: createdCostumer + }) + }) + .catch(err => { + res.status(500).json({ + message: err.message + }) + }) } static readCostumer(req, res) { - // return res.send('read all book'); - + // return res.send('read all costumer'); + Costumer.find() + .limit(10) + .exec() + .then(foundCostumers => { + res.status(200).json({ + message: 'Showing Costumers', + foundCostumers: foundCostumers + }) + }) + .catch(err => { + res.status(500).json({ + message: err.message + }) + }) } static readOneCostumer(req, res) { - // return res.send('read all book'); - + // return res.send('read all costumer'); + Costumer.findOne({ + _id: req.params._id + }) + .exec() + .then(foundCostumer => { + res.status(200).json({ + message: 'Showing Costumers', + foundCostumer: foundCostumer + }) + }) + .catch(err => { + res.status(500).json({ + message: err.message + }) + }) } static updateCostumer(req, res) { - // res.send('update a book'); + // res.send('update a costumer'); + let id = req.params._id; + let updateData = {} + if (req.body.name) {updateData.name = req.body.name} + if (req.body.memberId) {updateData.memberId = req.body.memberId} + if (req.body.address) {updateData.address = req.body.address} + if (req.body.zipcode) {updateData.zipcode = req.body.zipcode} + if (req.body.phone) {updateData.phone = req.body.phone} + Costumer.findByIdAndUpdate(id, updateData) + .exec() + .then(updatedCostumer => { + res.status(200).json({ + message: 'Updated Costumer', + updatedCostumer: updatedCostumer, + updateData: updateData + }) + }) + .catch(err => { + res.status(500).json({ + message: err.message + }) + }) } static deleteCostumer(req, res) { - // res.send('delete a book'); + // res.send('delete a costumer'); + let id = req.params._id; + Costumer.deleteOne({_id: id}) + .exec() + .then(confirm =>{ + res.status(200).json({ + message: 'Deleted Costumer', + confirm: confirm + }) + }) + .catch(err => { + res.status(500).json({ + message: err.message + }) + }) } } diff --git a/controllers/transactionController.js b/controllers/transactionController.js new file mode 100644 index 0000000..926754b --- /dev/null +++ b/controllers/transactionController.js @@ -0,0 +1,116 @@ +'use strict' +const Transaction = require('../models/Transaction.js') + + +class TransactionController { + + static createTransaction(req, res) { + // return res.send('create transaction'); + let days = Number(req.body.days) + + let newTransaction = new Transaction() + newTransaction.member = req.body.memberId; + newTransaction.days = days; + newTransaction.due_date = +new Date()+days*24*60*60*1000 + + // console.log(newTransaction); + newTransaction.save() + .then(createdTransaction => { + res.status(201).json({ + message: 'New transaction created', + createdTransaction: createdTransaction + }) + }) + .catch(err => { + res.status(500).json({ + message: err.message + }) + }) + } + + static readTransaction(req, res) { + // return res.send('read all transaction'); + Transaction.find() + .limit(10) + // .populate('Costumer') + .exec() + .then(foundTransactions => { + res.status(200).json({ + message: 'Showing Transactions', + foundTransactions: foundTransactions + }) + }) + .catch(err => { + res.status(500).json({ + message: err.message + }) + }) + } + + static readOneTransaction(req, res) { + // return res.send('read all transaction'); + Transaction.findOne({ + _id: req.params._id + }) + .exec() + .then(foundTransaction => { + res.status(200).json({ + message: 'Showing Transactions', + foundTransaction: foundTransaction + }) + }) + .catch(err => { + res.status(500).json({ + message: err.message + }) + }) + } + + static updateTransaction(req, res) { + // res.send('update a transaction'); + let id = req.params._id; + let updateData = {} + if (req.body.member) {updateData.member = req.body.memberId} + if (req.body.days) {updateData.days = req.body.days} + if (req.body.due_date) {updateData.due_date = req.body.due_date} + + Transaction.findByIdAndUpdate(id, updateData) + .exec() + .then(updatedTransaction => { + res.status(200).json({ + message: 'Updated Transaction', + updatedTransaction: updatedTransaction, + updateData: updateData + }) + }) + .catch(err => { + res.status(500).json({ + message: err.message + }) + }) + } + + static deleteTransaction(req, res) { + // res.send('delete a transaction'); + let id = req.params._id; + + Transaction.deleteOne({_id: id}) + .exec() + .then(confirm =>{ + res.status(200).json({ + message: 'Deleted Transaction', + confirm: confirm + }) + }) + .catch(err => { + res.status(500).json({ + message: err.message + }) + }) + } + +} + +module.exports = { + TransactionController: TransactionController +}; diff --git a/models/Transaction.js b/models/Transaction.js index 5812445..d8bfdfe 100644 --- a/models/Transaction.js +++ b/models/Transaction.js @@ -12,12 +12,18 @@ const TransactionSchema = new Schema ({ default: Date.now }, due_date: Date, - in_date: Date, - fine: Number, + in_date: { + type: Date, + default: null + }, + fine: { + type: Number, + default: 0 + }, booklist: [{ type: Schema.Types.ObjectId, ref: 'Book' - }] + }], createdAt: { type: Date, default: Date.now diff --git a/routes/books.js b/routes/books.js index dd7aa9c..f87171d 100644 --- a/routes/books.js +++ b/routes/books.js @@ -3,7 +3,6 @@ const BookController = require('../controllers/bookController.js').BookControlle var router = express.Router(); -/* GET users listing. */ router.post('/add', BookController.createBook); router.get('/library', BookController.readBook); diff --git a/routes/costumers.js b/routes/costumers.js index 3b21659..1a59b7f 100644 --- a/routes/costumers.js +++ b/routes/costumers.js @@ -3,11 +3,10 @@ const CostumerController = require('../controllers/costumerController.js').Costu var router = express.Router(); -/* GET users listing. */ router.post('/add', CostumerController.createCostumer); -router.get('/library', CostumerController.readCostumer); -router.get('/library/:_id', CostumerController.readOneCostumer); +router.get('/', CostumerController.readCostumer); +router.get('/:_id', CostumerController.readOneCostumer); router.put('/edit/:_id', CostumerController.updateCostumer); router.delete('/delete/:_id', CostumerController.deleteCostumer); diff --git a/routes/transactions.js b/routes/transactions.js new file mode 100644 index 0000000..15a11b4 --- /dev/null +++ b/routes/transactions.js @@ -0,0 +1,17 @@ +var express = require('express'); +const TransactionController = require('../controllers/transactionController.js').TransactionController +var router = express.Router(); + + +router.post('/add', TransactionController.createTransaction); + +router.get('/', TransactionController.readTransaction); +router.get('/:_id', TransactionController.readOneTransaction); + +router.put('/edit/:_id', TransactionController.updateTransaction); +router.delete('/delete/:_id', TransactionController.deleteTransaction); + +// router.patch('/', TransactionController.createTransaction); + + +module.exports = router; From 9da77061a90567383f0b35ab31129c90aafe8c8a Mon Sep 17 00:00:00 2001 From: FTeddy Date: Tue, 6 Mar 2018 19:53:50 +0700 Subject: [PATCH 4/7] updated readme --- README.md | 59 +++++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 57 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 047fea0..f9ced75 100644 --- a/README.md +++ b/README.md @@ -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 From b897422b8f9caf70e8ffa1cfa1301b350c32f3ec Mon Sep 17 00:00:00 2001 From: FTeddy Date: Tue, 6 Mar 2018 19:54:11 +0700 Subject: [PATCH 5/7] added a return book API on Transaction --- controllers/transactionController.js | 100 ++++++++++++++++++++++----- routes/transactions.js | 3 +- 2 files changed, 85 insertions(+), 18 deletions(-) diff --git a/controllers/transactionController.js b/controllers/transactionController.js index 926754b..b94322b 100644 --- a/controllers/transactionController.js +++ b/controllers/transactionController.js @@ -11,7 +11,12 @@ class TransactionController { let newTransaction = new Transaction() newTransaction.member = req.body.memberId; newTransaction.days = days; - newTransaction.due_date = +new Date()+days*24*60*60*1000 + + let dueDate= new Date(); + dueDate.setDate(dueDate.getDate()+days); + + newTransaction.due_date = dueDate; + newTransaction.booklist = req.body.booklist; // console.log(newTransaction); newTransaction.save() @@ -32,7 +37,8 @@ class TransactionController { // return res.send('read all transaction'); Transaction.find() .limit(10) - // .populate('Costumer') + .populate('member') + .populate('booklist') .exec() .then(foundTransactions => { res.status(200).json({ @@ -52,6 +58,8 @@ class TransactionController { Transaction.findOne({ _id: req.params._id }) + .populate('member') + .populate('booklist') .exec() .then(foundTransaction => { res.status(200).json({ @@ -70,24 +78,36 @@ class TransactionController { // res.send('update a transaction'); let id = req.params._id; let updateData = {} - if (req.body.member) {updateData.member = req.body.memberId} - if (req.body.days) {updateData.days = req.body.days} - if (req.body.due_date) {updateData.due_date = req.body.due_date} - Transaction.findByIdAndUpdate(id, updateData) + Transaction.findById(id) .exec() - .then(updatedTransaction => { - res.status(200).json({ - message: 'Updated Transaction', - updatedTransaction: updatedTransaction, - updateData: updateData - }) - }) - .catch(err => { - res.status(500).json({ - message: err.message - }) + .then(foundTransaction => { + if (req.body.member) {updateData.member = req.body.memberId} + if (req.body.days) { + updateData.days = Number(req.body.days); + let due_date_new = new Date(foundTransaction.out_date); + due_date_new.setDate(due_date_new.getDate()+Number(req.body.days)); + updateData.due_date = due_date_new; + } + // console.log(updateData); + + Transaction.findOneAndUpdate(id, updateData) + .exec() + .then(updatedTransaction => { + res.status(200).json({ + message: 'Updated Transaction', + updatedTransaction: updatedTransaction, + updateData: updateData + }) + }) + .catch(err => { + res.status(500).json({ + message: err.message + }) + }) + }) + } static deleteTransaction(req, res) { @@ -109,6 +129,52 @@ class TransactionController { }) } + + static returnBooks(req, res) { + let id = req.params.transID; + let updateData = {}; + let inDate = new Date() + // inDate.setDate(20) + + updateData.in_date = inDate; + + Transaction.findById(id) + .exec() + .then(foundTransaction => { + // console.log(foundTransaction); + let dateDiff = function (dateA, dateB){ + let utc1 = Date.UTC(dateA.getFullYear(), dateA.getMonth(), dateA.getDate()); + let utc2 = Date.UTC(dateB.getFullYear(), dateB.getMonth(), dateB.getDate()); + return Math.floor((utc1 - utc2) / (1000 * 60 * 60 * 24)); + } + // console.log(dateDiff(inDate, foundTransaction.due_date)); + let fine = 0 + let dateGap = dateDiff(inDate,foundTransaction.due_date) + if (dateGap > 0) { + fine = dateGap * 3000 + } + + updateData.fine = fine; + // console.log(updateData); + + Transaction.findOneAndUpdate(id, updateData) + .exec() + .then(updatedTransaction => { + res.status(200).json({ + message: 'Returned the books', + updatedTransaction: updatedTransaction, + updateData: updateData + }) + }) + .catch(err => { + res.status(500).json({ + message: err.message + }) + }) + + }) + } + } module.exports = { diff --git a/routes/transactions.js b/routes/transactions.js index 15a11b4..40c94d4 100644 --- a/routes/transactions.js +++ b/routes/transactions.js @@ -11,7 +11,8 @@ router.get('/:_id', TransactionController.readOneTransaction); router.put('/edit/:_id', TransactionController.updateTransaction); router.delete('/delete/:_id', TransactionController.deleteTransaction); -// router.patch('/', TransactionController.createTransaction); +// return the books +router.patch('/return/:transID', TransactionController.returnBooks); module.exports = router; From 4f9ef39b4cb7c6f624d4dbf51831822d294be996 Mon Sep 17 00:00:00 2001 From: FTeddy Date: Tue, 6 Mar 2018 20:00:41 +0700 Subject: [PATCH 6/7] added error handling for creating transaction --- controllers/transactionController.js | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/controllers/transactionController.js b/controllers/transactionController.js index b94322b..046058d 100644 --- a/controllers/transactionController.js +++ b/controllers/transactionController.js @@ -6,8 +6,26 @@ class TransactionController { static createTransaction(req, res) { // return res.send('create transaction'); - let days = Number(req.body.days) + if (!req.body.days) { + return res.status(400).json({ + message: 'days borrowed not defined' + }) + } + + if (!req.body.memberId) { + return res.status(400).json({ + message: 'memberId cannot be empty. Who is borrowing?' + }) + } + + if (!req.body.booklist) { + return res.status(400).json({ + message: 'booklist cannot be empty. What are you borrowing?' + }) + } + + let days = Number(req.body.days) let newTransaction = new Transaction() newTransaction.member = req.body.memberId; newTransaction.days = days; From a875d4d5ba4e5a390f9515ab2c1a994010c625d8 Mon Sep 17 00:00:00 2001 From: FTeddy Date: Tue, 6 Mar 2018 22:15:57 +0700 Subject: [PATCH 7/7] stock update on transaction create. broken, need async await --- controllers/transactionController.js | 58 ++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) diff --git a/controllers/transactionController.js b/controllers/transactionController.js index 046058d..2f80b5f 100644 --- a/controllers/transactionController.js +++ b/controllers/transactionController.js @@ -1,10 +1,12 @@ 'use strict' const Transaction = require('../models/Transaction.js') +const Book = require('../models/Book.js') class TransactionController { static createTransaction(req, res) { + // console.log(req.body); // return res.send('create transaction'); if (!req.body.days) { @@ -23,6 +25,62 @@ class TransactionController { return res.status(400).json({ message: 'booklist cannot be empty. What are you borrowing?' }) + } else { + if (req.body.booklist.constructor === Array) { + // I CANT DO THIS I NEED ASYNC AWAIT HERE + for (let i = 0; i < req.body.booklist.length; i++) { + let bookId = req.body.booklist[i] + console.log(bookId); + Book.findById(bookId) + .exec() + .then(foundBook => { + console.log(foundBook); + if (foundBook.stock < 1) { + return res.status(400).json({ + message: `Cannot borrow. book ${foundBook.title} does not have enough stock` + }) + } else { + let updatedStock = {stock : foundBook.stock - 1} + console.log(updatedStock); + Book.findOneAndUpdate(bookId, updatedStock) + .exec() + .then(updatedBook => { + console.log('book stock updated'); + }) + .catch(err => { + res.status(500).json({ + message: err.message + }) + }) + } + }) + } + } else { + let bookId = req.body.booklist[i] + Book.findById(bookId) + .exec() + .then(foundBook => { + console.log(foundBook); + if (foundBook.stock < 1) { + return res.status(400).json({ + message: `Cannot borrow. book ${foundBook.title} does not have enough stock` + }) + } else { + let updatedStock = {stock : foundBook.stock - 1} + Book.findOneAndUpdate(bookId, updatedStock) + .exec() + .then(updatedBook => { + console.log('book stock updated'); + }) + .catch(err => { + res.status(500).json({ + message: err.message + }) + }) + } + }) + } + } let days = Number(req.body.days)