From 64e0a454b3d8a0a3446030ae7fddbecec9955406 Mon Sep 17 00:00:00 2001 From: Sergey Date: Fri, 26 Apr 2019 14:50:12 +0300 Subject: [PATCH] The completion of the ToDO list --- .gitignore | 2 +- app.js | 7 +-- bin/www | 34 +++++------ config/config.json | 24 ++++---- controllers/task.js | 11 ---- controllers/tasksController.js | 28 +++++++++ db/db.js | 75 ------------------------ migrations/20190424083824-create-task.js | 32 ++++++++++ migrations/createTasks.js | 0 models/index.js | 37 ++++++++++++ models/task.js | 48 +++++---------- npm-debug.log | 45 ++++++++++++++ routes/index.js | 9 --- routes/tasks.js | 26 ++++---- routes/users.js | 9 --- seeders/20190424084345-demo-tasks.js | 18 ++++++ 16 files changed, 220 insertions(+), 185 deletions(-) delete mode 100644 controllers/task.js create mode 100644 controllers/tasksController.js delete mode 100644 db/db.js create mode 100644 migrations/20190424083824-create-task.js delete mode 100644 migrations/createTasks.js create mode 100644 models/index.js create mode 100644 npm-debug.log delete mode 100644 routes/index.js delete mode 100644 routes/users.js create mode 100644 seeders/20190424084345-demo-tasks.js diff --git a/.gitignore b/.gitignore index 3c3629e..c2658d7 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1 @@ -node_modules +node_modules/ diff --git a/app.js b/app.js index 065cf10..ae46ac5 100644 --- a/app.js +++ b/app.js @@ -6,8 +6,7 @@ var logger = require("morgan"); const bodyParser = require("body-parser"); const tasks = require("./routes/tasks"); const cors = require("cors"); -var indexRouter = require("./routes/index"); -var usersRouter = require("./routes/users"); + var app = express(); @@ -15,8 +14,8 @@ var app = express(); app.set("views", path.join(__dirname, "views")); app.set("view engine", "ejs"); -// app.use(cors()); -// app.options("*", cors()); +app.use(cors()); +app.options("*", cors()); app.use(logger("dev")); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); diff --git a/bin/www b/bin/www index 6c43634..dd7f79f 100755 --- a/bin/www +++ b/bin/www @@ -4,16 +4,16 @@ * Module dependencies. */ -var app = require('../app'); -var debug = require('debug')('todo-server2:server'); -var http = require('http'); +var app = require("../app"); +var debug = require("debug")("todo-server2:server"); +var http = require("http"); /** * Get port from environment and store in Express. */ -var port = normalizePort(process.env.PORT || '3000'); -app.set('port', port); +var port = normalizePort(process.env.PORT || "3001"); +app.set("port", port); /** * Create HTTP server. @@ -26,8 +26,8 @@ var server = http.createServer(app); */ server.listen(port); -server.on('error', onError); -server.on('listening', onListening); +server.on("error", onError); +server.on("listening", onListening); /** * Normalize a port into a number, string, or false. @@ -54,22 +54,20 @@ function normalizePort(val) { */ function onError(error) { - if (error.syscall !== 'listen') { + if (error.syscall !== "listen") { throw error; } - var bind = typeof port === 'string' - ? 'Pipe ' + port - : 'Port ' + port; + 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'); + case "EACCES": + console.error(bind + " requires elevated privileges"); process.exit(1); break; - case 'EADDRINUSE': - console.error(bind + ' is already in use'); + case "EADDRINUSE": + console.error(bind + " is already in use"); process.exit(1); break; default: @@ -83,8 +81,6 @@ function onError(error) { function onListening() { var addr = server.address(); - var bind = typeof addr === 'string' - ? 'pipe ' + addr - : 'port ' + addr.port; - debug('Listening on ' + bind); + var bind = typeof addr === "string" ? "pipe " + addr : "port " + addr.port; + debug("Listening on " + bind); } diff --git a/config/config.json b/config/config.json index 0f858c6..7ca8347 100644 --- a/config/config.json +++ b/config/config.json @@ -1,23 +1,23 @@ { "development": { - "username": "root", - "password": null, - "database": "database_development", + "username": "sergey", + "password": "sergey", + "database": "tasks", "host": "127.0.0.1", - "dialect": "mysql" + "dialect": "postgres" }, "test": { - "username": "root", - "password": null, - "database": "database_test", + "username": "sergey", + "password": "sergey", + "database": "tasks", "host": "127.0.0.1", - "dialect": "mysql" + "dialect": "postgres" }, "production": { - "username": "root", - "password": null, - "database": "database_production", + "username": "sergey", + "password": "sergey", + "database": "tasks", "host": "127.0.0.1", - "dialect": "mysql" + "dialect": "postgres" } } diff --git a/controllers/task.js b/controllers/task.js deleted file mode 100644 index e2cba38..0000000 --- a/controllers/task.js +++ /dev/null @@ -1,11 +0,0 @@ -const Task = require("../models/tasksSequelize"); - -class modelMethods { - static add(data, cb) { - Task.create(data).then( - item => console.log("Task success added with id =", item.id), - cb() - ); - } -} -module.exports = modelMethods; diff --git a/controllers/tasksController.js b/controllers/tasksController.js new file mode 100644 index 0000000..fa16a74 --- /dev/null +++ b/controllers/tasksController.js @@ -0,0 +1,28 @@ +const models = require("../models"); + +class TasksController { + static all(cb) { + models.Task.findAll({ order: ["createdAt"] }).then(items => { + cb(items); + }); + } + static create(data, cb) { + models.Task.create(data.task).then(item => { + + cb(item); + }); + } + static update(data, cb) { + models.Task.update(data, { where: { id: data.id } }).then(() => { + cb("ok"); + }); + } + static delete(id, cb) { + models.Task.destroy({ where: { id: id } }).then(item => { + cb(id) + + }); + + } +} +module.exports = TasksController; diff --git a/db/db.js b/db/db.js deleted file mode 100644 index 92f244f..0000000 --- a/db/db.js +++ /dev/null @@ -1,75 +0,0 @@ -// const { Client } = require("pg"); -const Sequelize = require("sequelize"); - -const username = "sergey"; -const password = "sergey"; -const host = "localhost"; -const port = 5432; -const database = "tasks"; -const dialect = "postgres"; -const pool = { - max: 5, - min: 0, - idle: 10000 -}; - -const sequelize = new Sequelize(database, username, password, { - host, - dialect, - pool -}); - -sequelize - .authenticate() - .then(() => { - console.log("Соединение установлено"); - }) - .catch(err => { - console.error("Ошибка соединения:", err); - }); - -// const Task = sequelize.define( -// "task", -// { -// //attributes -// id: { -// type: Sequelize.INTEGER, -// primaryKey: true, -// autoIncrement: true -// }, -// body: { -// type: Sequelize.STRING, -// allowNull: false -// } -// }, -// {} -// ); - -module.exports = sequelize; -// const db = new Client({ -// database: "tasks", -// host: "localhost", -// port: 5432, -// user: username, -// password: password -// }); - -// db.connect((err, client) => { -// if (err) throw err; -// console.log("Connected to database", db.database); -// }); - -// db.query( -// ` -// CREATE TABLE IF NOT EXISTS taskstable ( -// id SERIAL, -// PRIMARY KEY(id), -// body text, -// iscompleted boolean -// ); -// `, -// (err, result) => { -// if (err) throw err; -// console.log('Created table "taskstable"'); -// } -// ); diff --git a/migrations/20190424083824-create-task.js b/migrations/20190424083824-create-task.js new file mode 100644 index 0000000..66f4b51 --- /dev/null +++ b/migrations/20190424083824-create-task.js @@ -0,0 +1,32 @@ +"use strict"; +module.exports = { + up: (queryInterface, Sequelize) => { + return queryInterface.createTable("Tasks", { + id: { + allowNull: false, + autoIncrement: true, + primaryKey: true, + type: Sequelize.INTEGER + }, + text: { + type: Sequelize.STRING + }, + isCompleted: { + type: Sequelize.BOOLEAN + }, + createdAt: { + allowNull: false, + defaultValue: new Date(), + type: Sequelize.DATE + }, + updatedAt: { + allowNull: false, + defaultValue: new Date(), + type: Sequelize.DATE + } + }); + }, + down: (queryInterface, Sequelize) => { + return queryInterface.dropTable("Tasks"); + } +}; diff --git a/migrations/createTasks.js b/migrations/createTasks.js deleted file mode 100644 index e69de29..0000000 diff --git a/models/index.js b/models/index.js new file mode 100644 index 0000000..c1a3d6d --- /dev/null +++ b/models/index.js @@ -0,0 +1,37 @@ +'use strict'; + +const fs = require('fs'); +const path = require('path'); +const Sequelize = require('sequelize'); +const basename = path.basename(__filename); +const env = process.env.NODE_ENV || 'development'; +const config = require(__dirname + '/../config/config.json')[env]; +const db = {}; + +let sequelize; +if (config.use_env_variable) { + sequelize = new Sequelize(process.env[config.use_env_variable], config); +} else { + sequelize = new Sequelize(config.database, config.username, config.password, config); +} + +fs + .readdirSync(__dirname) + .filter(file => { + return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js'); + }) + .forEach(file => { + const model = sequelize['import'](path.join(__dirname, file)); + db[model.name] = model; + }); + +Object.keys(db).forEach(modelName => { + if (db[modelName].associate) { + db[modelName].associate(db); + } +}); + +db.sequelize = sequelize; +db.Sequelize = Sequelize; + +module.exports = db; diff --git a/models/task.js b/models/task.js index 26711c7..90cc7fc 100644 --- a/models/task.js +++ b/models/task.js @@ -1,33 +1,15 @@ -const db = require("../db/db"); - -class Task { - static add(data, cb) { - const sql = ` - INSERT INTO tasks1 (body) VALUES ('${data}') RETURNING *`; - db.query(sql, cb); - } - static update(data, cb) { - const sql = `UPDATE tasks SET body = '${data.text}', isCompleted = '${ - data.isCompleted - }' WHERE id=${data.id} RETURNING *`; - db.query(sql, cb); - } - static all(cb) { - db.query(`SELECT * FROM tasks1 ORDER BY id`, cb); - } - - static find(id, cb) { - const sql = ` - SELECT FROM tasks WHERE id = ${id}; - `; - db.query(sql, cb); - } - - static delete(id, cb) { - if (!id) return cb(new Error("Please provide an id")); - const sql = `DELETE FROM tasks WHERE id = ${id} RETURNING *`; - db.query(sql, cb); - } -} - -module.exports = Task; +"use strict"; +module.exports = (sequelize, DataTypes) => { + const Task = sequelize.define( + "Task", + { + text: DataTypes.STRING, + isCompleted: DataTypes.BOOLEAN + }, + {} + ); + Task.associate = function(models) { + // associations can be defined here + }; + return Task; +}; diff --git a/npm-debug.log b/npm-debug.log new file mode 100644 index 0000000..560d634 --- /dev/null +++ b/npm-debug.log @@ -0,0 +1,45 @@ +0 info it worked if it ends with ok +1 verbose cli [ '/usr/bin/node', '/usr/bin/npm', 'start' ] +2 info using npm@3.5.2 +3 info using node@v8.10.0 +4 verbose run-script [ 'prestart', 'start', 'poststart' ] +5 info lifecycle todo-server2@0.0.0~prestart: todo-server2@0.0.0 +6 silly lifecycle todo-server2@0.0.0~prestart: no script for prestart, continuing +7 info lifecycle todo-server2@0.0.0~start: todo-server2@0.0.0 +8 verbose lifecycle todo-server2@0.0.0~start: unsafe-perm in lifecycle true +9 verbose lifecycle todo-server2@0.0.0~start: PATH: /usr/share/npm/bin/node-gyp-bin:/home/sergey/React/todo-back/node_modules/.bin:/home/sergey/.rvm/gems/ruby-2.6.0/bin:/home/sergey/.rvm/gems/ruby-2.6.0@global/bin:/home/sergey/.rvm/rubies/ruby-2.6.0/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/home/sergey/.rvm/bin:/home/sergey/.rvm/bin +10 verbose lifecycle todo-server2@0.0.0~start: CWD: /home/sergey/React/todo-back +11 silly lifecycle todo-server2@0.0.0~start: Args: [ '-c', 'node ./bin/www' ] +12 silly lifecycle todo-server2@0.0.0~start: Returned: code: 1 signal: null +13 info lifecycle todo-server2@0.0.0~start: Failed to exec start script +14 verbose stack Error: todo-server2@0.0.0 start: `node ./bin/www` +14 verbose stack Exit status 1 +14 verbose stack at EventEmitter. (/usr/share/npm/lib/utils/lifecycle.js:232:16) +14 verbose stack at emitTwo (events.js:126:13) +14 verbose stack at EventEmitter.emit (events.js:214:7) +14 verbose stack at ChildProcess. (/usr/share/npm/lib/utils/spawn.js:24:14) +14 verbose stack at emitTwo (events.js:126:13) +14 verbose stack at ChildProcess.emit (events.js:214:7) +14 verbose stack at maybeClose (internal/child_process.js:925:16) +14 verbose stack at Process.ChildProcess._handle.onexit (internal/child_process.js:209:5) +15 verbose pkgid todo-server2@0.0.0 +16 verbose cwd /home/sergey/React/todo-back +17 error Linux 4.15.0-47-generic +18 error argv "/usr/bin/node" "/usr/bin/npm" "start" +19 error node v8.10.0 +20 error npm v3.5.2 +21 error code ELIFECYCLE +22 error todo-server2@0.0.0 start: `node ./bin/www` +22 error Exit status 1 +23 error Failed at the todo-server2@0.0.0 start script 'node ./bin/www'. +23 error Make sure you have the latest version of node.js and npm installed. +23 error If you do, this is most likely a problem with the todo-server2 package, +23 error not with npm itself. +23 error Tell the author that this fails on your system: +23 error node ./bin/www +23 error You can get information on how to open an issue for this project with: +23 error npm bugs todo-server2 +23 error Or if that isn't available, you can get their info via: +23 error npm owner ls todo-server2 +23 error There is likely additional logging output above. +24 verbose exit [ 1, true ] diff --git a/routes/index.js b/routes/index.js deleted file mode 100644 index ecca96a..0000000 --- a/routes/index.js +++ /dev/null @@ -1,9 +0,0 @@ -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/tasks.js b/routes/tasks.js index 2fe9dc5..f2744be 100644 --- a/routes/tasks.js +++ b/routes/tasks.js @@ -1,31 +1,33 @@ -const modelMethods = require("../controllers/task"); +const TasksController = require("../controllers/tasksController"); exports.list = (req, res) => { - Task.all((err, tasks) => { - if (err) return next(err); - // res.render("tasks", { tasks: tasks.rows }); - res.json(tasks.rows); + TasksController.all(items => { + res.json(items); }); }; exports.submit = (req, res, next) => { const data = req.body; - console.log(data); - modelMethods.add(data, (err, task) => { - res.json(task.rows); + + TasksController.create(data, item => { + res.json(item); }); }; exports.update = (req, res) => { let data = req.body; - Task.update(data, (err, task) => { - res.json(task); + + + TasksController.update(data, item => { + + res.json(item); }); }; exports.delete = (req, res) => { - let id = req.params.id; - Task.delete(id, (err, item) => { + let id = Number(req.params.id); + TasksController.delete(id, item => { + res.json(item); }); }; diff --git a/routes/users.js b/routes/users.js deleted file mode 100644 index 623e430..0000000 --- a/routes/users.js +++ /dev/null @@ -1,9 +0,0 @@ -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/seeders/20190424084345-demo-tasks.js b/seeders/20190424084345-demo-tasks.js new file mode 100644 index 0000000..bd6647a --- /dev/null +++ b/seeders/20190424084345-demo-tasks.js @@ -0,0 +1,18 @@ +"use strict"; + +module.exports = { + up: (queryInterface, Sequelize) => { + return queryInterface.bulkInsert( + "Tasks", + [ + { + text: "Make TODO", + isCompleted: false + } + ], + {} + ); + }, + + down: (queryInterface, Sequelize) => {} +};