-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
52 lines (43 loc) · 1.17 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
import express from 'express';
import Boom from '@hapi/boom';
import morgan from 'morgan';
import persistence from './persistence/index.js';
const PORT = 3000;
function asyncMiddleware(fn) {
return (req, res, next) => {
Promise.resolve(fn(req, res, next)).catch(next);
};
}
const app = express();
app.use(morgan('dev'));
app.use(express.json());
app.use((_, res, next) => {
res.set('X-Database-Used', process.env.MONGO_URL ? 'MongoDB' : 'SQLite');
next();
});
app.get('/animals', asyncMiddleware(async (_, res) => {
const animals = await persistence.getAnimals();
res.json(animals);
}));
app.get('/animals/:id', asyncMiddleware(async (req, res) => {
const animal = await persistence.getAnimal(Number(req.params.id));
res.json(animal);
}));
app.use((err, _, res, next) => {
res.status(Boom.isBoom(err) ? err.output.statusCode : 500).json({
error: err.message,
});
next();
});
persistence
.initialize()
.then(() => {
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
})
.catch((err) => {
console.error('Database failed to connect, check the error below');
console.error(err);
process.exit(1);
});