-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
58 lines (42 loc) · 1.09 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
54
55
56
57
58
var express=require('express');
var bodyParser=require('body-parser');
var DataStore=require('nedb');
var port= 3000;
var BASE_API_PATH="/api/v1";
var DB_FILE_NAME=__dirname+"/contacts.json";
console.log("Starting API Server...");
var app= express();
app.use(bodyParser.json());
var db= new DataStore({
filename:DB_FILE_NAME,
autoload: true
})
app.get("/", (req,res)=>{
res.send("<html><body><h1>My server</h1></body></html>")
}
)
app.get(BASE_API_PATH+"/contacts", (req,res)=>{
console.log(Date()+"- GET/contacts");
db.find({}, (err,contacts)=>{
if(err){
console.log(Date()+"-"+err)
res.sendStatus(500)
}else{
res.send(contacts);
}
});
});
app.post(BASE_API_PATH+"/contacts", (req,res)=>{
console.log(Date()+"- POST/contacts");
var contact=req.body;
db.insert(contact,(err)=>{
if(err){
console.log(Date()+"-"+ err);
res.sendStatus(500);
}else{
res.sendStatus(201);
}
});
});
app.listen(port);
console.log("Server ready!");