/
provider.js
92 lines (77 loc) · 1.85 KB
/
provider.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
92
const express = require("express")
const cors = require("cors")
const bodyParser = require("body-parser")
const Repository = require("./repository")
const server = express()
server.use(cors())
server.use(bodyParser.json())
server.use(
bodyParser.urlencoded({
extended: true,
})
)
server.use((req, res, next) => {
res.header("Content-Type", "application/json; charset=utf-8")
next()
})
server.use((req, res, next) => {
console.log(req.headers)
const token = req.headers["authorization"] || ""
if (token !== "Bearer 1234") {
res.sendStatus(401).send()
} else {
next()
}
})
const animalRepository = new Repository()
// Load default data into a repository
const importData = () => {
const data = require("./data/animalData.json")
data.reduce((a, v) => {
v.id = a + 1
animalRepository.insert(v)
return a + 1
}, 0)
}
// List all animals with 'available' eligibility
const availableAnimals = () => {
return animalRepository.fetchAll().filter(a => {
return a.eligibility.available
})
}
// Get all animals
server.get("/animals", (req, res) => {
res.json(animalRepository.fetchAll())
})
// Get all available animals
server.get("/animals/available", (req, res) => {
res.json(availableAnimals())
})
// Find an animal by ID
server.get("/animals/:id", (req, res) => {
const response = animalRepository.getById(req.params.id)
if (response) {
res.end(JSON.stringify(response))
} else {
res.writeHead(404)
res.end()
}
})
// Register a new Animal for the service
server.post("/animals", (req, res) => {
const animal = req.body
// Really basic validation
if (!animal || !animal.first_name) {
res.writeHead(400)
res.end()
return
}
animal.id = animalRepository.fetchAll().length
animalRepository.insert(animal)
res.json(animal)
})
module.exports = {
server,
importData,
animalRepository,
}