92 lines
2.5 KiB
JavaScript
92 lines
2.5 KiB
JavaScript
const Datastore = require('@seald-io/nedb');
|
|
const express = require('express');
|
|
const app = express();
|
|
const port = 3000;
|
|
const { create } = require('express-handlebars');
|
|
const path = require("path");
|
|
|
|
const baza = new Datastore({
|
|
filename: 'users.db',
|
|
autoload: true
|
|
});
|
|
|
|
const itemki = new Datastore({
|
|
filename: 'items.db',
|
|
autoload: true
|
|
});
|
|
|
|
const hbs = create({
|
|
defaultLayout: 'main.hbs',
|
|
extname: '.hbs'
|
|
});
|
|
|
|
app.engine('.hbs', hbs.engine);
|
|
app.set('view engine', '.hbs');
|
|
app.set('views', path.join(__dirname, 'views'));
|
|
|
|
app.use(express.urlencoded({ extended: true }));
|
|
|
|
app.get("/", function (req, res) {
|
|
baza.find({}).sort({ timestamp: 1 }).exec(function (err, docs) {
|
|
let ctx = { docs: docs };
|
|
|
|
res.render('users.hbs', ctx);
|
|
});
|
|
})
|
|
|
|
app.get("/produkty", function (req, res) {
|
|
itemki.find({}, function(err, docs) {
|
|
const ctx = { docs: docs };
|
|
|
|
res.render('items.hbs', ctx);
|
|
});
|
|
});
|
|
|
|
app.get("/przywroc", function (req, res) {
|
|
itemki.remove({}, { multi: true }, function (err, rowsDeleted) {
|
|
console.log(`Usunięto ${rowsDeleted} wierszy`);
|
|
});
|
|
|
|
const wzorzec = [
|
|
{ "name": "monitor", "price": "1000", "_id": "NDecyInUUH1J2LHg" },
|
|
{ "name": "kable", "price": "50", "_id": "OabZKvdCsGJLHnG6" },
|
|
{ "name": "klawiatura", "price": "200", "_id": "eefB8sB5n7VskNXT" },
|
|
{ "name": "klawiatura", "price": "250", "_id": "tpfbWz2RIPiCLSnK" },
|
|
{ "name": "mysz", "price": "100", "_id": "wPKJpK0LQkV2Kb57" }
|
|
];
|
|
|
|
wzorzec.forEach(item => {
|
|
itemki.insert(item, function(err, doc) {
|
|
console.log(`Wstawiono obiekt z id ${item._id}`);
|
|
});
|
|
});
|
|
|
|
res.redirect("/produkty");
|
|
});
|
|
|
|
app.post("/usun", function(req, res) {
|
|
if(req.body.remove) {
|
|
if(typeof(req.body.remove) == 'string') {
|
|
itemki.remove({ _id: req.body.remove }, {}, function(err, numDeleted) {
|
|
console.log(`Usunięto ${numDeleted} wiersz(y), id: ${req.body.remove}`);
|
|
});
|
|
} else {
|
|
req.body.remove.forEach(id => {
|
|
itemki.remove({ _id: id }, {}, function(err, numDeleted) {
|
|
console.log(`Usunięto ${numDeleted} wiersz(y), id: ${id}`);
|
|
});
|
|
});
|
|
}
|
|
|
|
res.redirect("/produkty");
|
|
} else {
|
|
res.send("Bro. Musisz coś zaznaczyć");
|
|
}
|
|
});
|
|
|
|
app.use(express.static("static"));
|
|
|
|
app.listen(port, function () {
|
|
console.log(`Start ${port}`);
|
|
});
|