-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
91 lines (73 loc) · 2.02 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
"use strict";
const couchDB = "http://memluk:[email protected]:5984";
// WEBSERVER
const formidable = require("formidable");
const express = require("express");
const server = express();
// Middleware
server.use(
express.static("public", {
extensions: ["html"],
})
);
server.use(express.json())
// ROUTES
// Write & update a record
server.post("/save_Item", (request, response) => {
const form = formidable({
uploadDir: "./uploads",
keepExtensions: true,
});
form.parse(request, (err, fields, uploads) => {
if (err) console.warn(err);
else {
let myDB = db.use(dbName); // Connect to the DB
fields.url = uploads.url.newFilename;
if(fields._id == "") {
delete fields._id;
delete fields._rev;
}
console.log(fields);
myDB // Enter data record in DB
.insert(fields)
.then((res) => response.json(res))
.catch(console.warn);
}
});
});
// Load all products data
server.get("/load_all_items", (request, response) => {
let myDB = db.use(dbName); // Connect to the DB
myDB
.list({ include_docs: true })
.then((res) => res.rows.map((row) => row.doc))
.then((res) => response.json(res))
.catch(console.warn);
});
// Delete a record
server.delete('/del_item', (request, response) => {
let myDB = db.use(dbName); // Connect to the DB
myDB
.destroy(request.body.id, request.body.rev) // Delete the record
.then(res => response.json(res))
.catch(console.warn);
})
// DATABASE
const dbName = "items";
const db = require("nano")(couchDB).db;
// FUNCTIONS
// Initialize DB
const dbInit = () => {
// Check whether the database exists
return db.list().then((res) => {
if (!res.includes(dbName)) return db.create(dbName);
});
};
const init = () => {
dbInit()
.then(
() => server.listen(3000, (err) => console.log(err || "Server runs")) // Start web server
)
.catch(console.warn);
};
init();