This repository has been archived by the owner on Sep 11, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
70 lines (62 loc) · 1.57 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
var express = require("express");
var fs = require("fs");
var async = require("async");
var data = require("./data");
var app = express();
app.use(express.logger());
app.use(express.bodyParser());
app.use("/css", express.static(__dirname + "/css"));
app.use("/html", express.static(__dirname + "/html"));
app.use("/js", express.static(__dirname + "/js"));
app.use(express.static(__dirname + "/public"));
function isJson(file) {
return /json$/.test(file);
}
function loadRecord(file, callback) {
fs.readFile(file, "utf8", function(err, text) {
var item = JSON.parse(text);
console.log(item);
callback(null, item);
});
}
app.get("/animals", function(req,res) {
data.all("animals", function(err, data) {
res.send({items: data});
});
});
app.get("/animals/:id", function(req,res) {
data.get("animals", req.params.id, function(err, data) {
if (err) {
if (err.errno === 34) {
res.send(404);
} else {
res.send(500);
}
} else {
res.send(data);
}
})
});
app.post("/animals", function(req,res) {
var animal = req.body;
data.add("animals", animal, function(err, data) {
if (err) {
res.send(500);
} else {
res.status(201);
res.set("Location", "/animals/" + animal.id)
res.send(data);
}
});
});
app.put("/animals", function(req,res) {
var animal = req.body;
data.update("animals", animal, function(err, data) {
if (err) {
res.send(500);
} else {
res.send(200);
}
});
});
app.listen(3000);