-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
53 lines (42 loc) · 1.21 KB
/
index.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
var express = require('express');
var bodyParser = require('body-parser');
var DataStore = require('nedb');
var path = require('path')
var port = (process.env.PORT || 3000);
var BASE_URL = "/api/v1";
var filename = __dirname + "/contacts.json";
const CONTACTS_APP_DIR = "/dist/contacts-app";
var contacts = [
{"name": "juan", "phone": 5555}
];
var db = new DataStore({
filename: filename,
autoload: true
});
console.log("Starting API server...");
var app = express();
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, CONTACTS_APP_DIR)));
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname, CONTACTS_APP_DIR, '/index.html'));
});
app.get(BASE_URL + "/contacts", (req, res) => {
db.find({}, (err, contacts) => {
if (err) {
console.error("Error accessing database");
res.sendStatus(500);
} else {
res.send(contacts.map((contact) => {
delete contact._id;
return contact;
}));
}
});
});
app.post(BASE_URL + "/contacts", (req, res) => {
var contact = req.body;
db.insert(contact);
res.sendStatus(201);
});
app.listen(port);
console.log("Server ready!");