Commit 978516a0 authored by Vadim's avatar Vadim

конец занятия №87

parent f34a5ff6
......@@ -5,9 +5,7 @@ module.exports = {
rootPath,
uploadPath: path.join(rootPath, '../public/uploads'),
db: {
host: 'localhost',
user: 'user',
password: 'user',
database: 'shop'
name: "shop",
url: "mongodb://localhost"
}
};
\ No newline at end of file
[{"title":"Новый продукт2","price":100,"description":"Product description","_id":"po07wU69_bGgD9lJaGBoB"},{"title":"Новый продукт3","price":100,"description":"Product description","_id":"po07wU69_bGgD9lJaGBoA"},{"title":"Название продукта3","price":100,"description":"Описание продукта3","_id":"po07wU69_bGgD9lJaGBoR"},{"title":"TestForm","price":"123","description":"Desc!","_id":"djfxvIUE1PboYuIg3GrqF"},{"title":"TEST","price":"2121","description":"dcsf","_id":"XHR1Qm678_6qm5YpC8FwF"},{"title":"ProductWithImage","price":"123","description":"desc","_id":"L9oUjrTVNIQAFPgMNkxjS"},{"title":"gtest2","price":"122","description":"dasd","_id":"lbZ2pROuopEILrZAP11Wx"},{"title":"dasZD","price":"111","description":"fsaf","_id":"vahqDU0OfxrhM5dZ-JWZ0","image":"32VkzVPFTTYhNCzErV1TC.jpg"}]
\ No newline at end of file
const fs = require('fs');
const fileName = './app/db/db.json';
let data = [];
module.exports = {
init() {
try {
const fileContents = fs.readFileSync(fileName, 'utf-8');
data = JSON.parse(fileContents);
}catch (e) {
console.error(e);
data = []
}
},
getItem(id){
},
getItems() {
return data;
},
addItem(item) {
data.push(item);
this.save();
},
save() {
fs.writeFileSync(fileName, JSON.stringify(data));
}
};
\ No newline at end of file
module.exports = (db) => ({
getItems(entity){
return new Promise((res, rej) => {
db.query("SELECT * FROM ??", [entity], (err, result)=> {
if(err) {
rej(err)
}
res(result);
})
});
},
getItem(entity, id){
return new Promise((res, rej) => {
db.query("SELECT * FROM ?? WHERE id = ?", [entity, id], (err, result)=> {
if(err) {
rej(err)
}
res(result);
})
});
},
addItem(entity, data){
return new Promise((res, rej) => {
db.query("INSERT INTO ?? SET ?", [entity, data], (err, result)=> {
if(err) {
rej(err)
}
data.id = result.insertId;
res(data);
})
});
}
});
\ No newline at end of file
......@@ -18,11 +18,6 @@ const ProductSchema = new Schema({
type: Schema.Types.ObjectId,
ref: 'Category',
required: true
},
user: {
type: Schema.Types.ObjectId,
ref: 'User',
required: true
}
}, {
versionKey: false
......
const express = require("express");
const User = require("./models/User");
const auth = require("./middleware/auth");
const router = express.Router();
......@@ -34,6 +35,16 @@ const createRouter = () => {
res.send(user);
});
router.delete('/sessions', auth ,async (req, res) => {
const user = req.user;
const success = {message: 'Success'};
user.token = '';
await user.save({validateBeforeSave: false});
return res.send(success);
});
return router;
};
......
const config = require("./app/config");
const mongoose = require("mongoose");
const Category = require("./app/models/Category");
const Products = require("./app/models/Products");
const User = require("./app/models/User");
const {nanoid} = require("nanoid");
mongoose.connect(config.db.url + '/' + config.db.name);
const db = mongoose.connection;
db.once('open', async () => {
try {
await db.dropCollection('categories');
await db.dropCollection('products');
await db.dropCollection('users');
} catch (e) {
console.log('Collections not found, skipping drop...');
}
const [cpuCategory, hddCategory] = await Category.create({
title: "CPUs",
description: "Central Processor Units"
}, {
title: "HDDs",
description: "Hard Disk Drives"
});
await Products.create({
title: "Intel core i7",
price: 500,
category: cpuCategory._id,
image: "cpu.jpeg"
}, {
title: "Seagate Barracuda 2TB",
price: 350,
category: hddCategory._id,
image: "hdd.jpeg"
});
await User.create({
username: 'admin',
email: 'admin@admin.com',
password: '123456',
token: nanoid()
}, {
username: 'user',
email: 'user@user.com',
password: '123456',
token: nanoid()
})
await db.close();
});
\ No newline at end of file
CREATE DATABASE IF NOT EXISTS shop;
USE shop;
CREATE TABLE IF NOT EXISTS products(
`id` int NOT NULL PRIMARY KEY AUTO_INCREMENT,
`title` varchar(255) NOT NULL,
`price` decimal(6,2) NOT NULL,
`description` text(1000),
`image` varchar(30)
);
......@@ -4,8 +4,9 @@
"description": "",
"main": "server.js",
"scripts": {
"start": "node server.js",
"dev": "nodemon server.js",
"test": "echo \"Error: no test specified\" && exit 1"
"seed": "node fixtures.js"
},
"author": "",
"license": "ISC",
......
*
\ No newline at end of file
*
!.gitignore
!cpu.jpeg
!hdd.jpeg
\ No newline at end of file
......@@ -20,7 +20,7 @@ app.use(express.static('public'));
const run = async () => {
await mongoose.connect("mongodb://localhost/shop", {useNewUrlParser: true});
await mongoose.connect(config.db.url + "/" + config.db.name, {useNewUrlParser: true});
app.use('/products', products());
app.use('/categories', categories());
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment