-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
57 lines (47 loc) · 1.51 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
const express = require('express');
const morgan = require('morgan');
const bodyParser = require('body-parser');
const BooktonicaDatabase = require('./src/booktonica-database');
const DEFAULT_DB_NAME = 'booktonica';
const dbName = process.env.DB_NAME || DEFAULT_DB_NAME;
/**
* Creates a new database object.
* Add new database queries to that class.
*
* You can run this app like:
* `DB_NAME=osito npm start` and it will
* use the DB named osito instead of DEFAULT_DB_NAME.
*/
const db = new BooktonicaDatabase(dbName);
const api = express();
// Middlewares
api.use(morgan('tiny'));
api.use(bodyParser.json());
api.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", process.env.REACT_CLIENT_ORIGIN); // update to match the domain you will make the request from
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
/**
* This will just print the incoming request bodies
* which is useful for debugging. You can skip it if you want
* by removing
*/
const bodyDebugMiddleware = require('./src/body-debug-middleware');
api.use(bodyDebugMiddleware);
// GET /books
api.get('/books', (_unused, res, next) =>
db
.getAllBooks()
.then(books => res.send(books))
.catch(next)
);
const PORT = process.env.PORT || 3001;
// sanityCheck will make sure the DB is working before listening
db.sanityCheck().then(() => {
api.listen(PORT, () => {
console.log(`
📚 booktonica express api listening on port ${PORT}
`);
});
});