-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
97 lines (81 loc) · 1.89 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
'use strict';
const Hapi = require('hapi');
const mongoose = require('mongoose');
const DogController = require('./src/controllers/dog');
const UserController = require('./src/controllers/user');
const { validate, verifyCredentials } = require('./src/utils/auth');
const MongoDBUrl = 'mongodb://localhost:27017/dogapi';
const server = new Hapi.Server({
port: 3000,
host: 'localhost',
});
const registerRoutes = () => {
server.route({
method: 'POST',
path: '/api/authenticate',
options: {
auth: false,
handler: UserController.authenticate,
pre: [{ method: verifyCredentials, assign: 'user' }],
}
});
server.route({
method: 'POST',
path: '/api/users',
options: {
auth: false,
handler: UserController.create,
}
})
server.route({
method: 'GET',
path: '/api/dogs',
handler: DogController.list,
});
server.route({
method: 'GET',
path: '/api/dogs/{id}',
handler: DogController.get,
});
server.route({
method: 'POST',
path: '/api/dogs',
handler: DogController.create,
});
server.route({
method: 'PUT',
path: '/api/dogs/{id}',
handler: DogController.update,
});
server.route({
method: 'DELETE',
path: '/api/dogs/{id}',
handler: DogController.remove,
});
}
const main = async () => {
await server.register(require('hapi-auth-jwt2'));
server.auth.strategy('jwt', 'jwt', {
key: 'DO_THE_THING',
validate,
verifyOptions: {
algorithms: ['HS256'],
},
});
server.auth.default('jwt');
registerRoutes();
await server.start();
mongoose.connect(MongoDBUrl, {
useNewUrlParser: true,
}, err => {
if (err) console.error(err);
console.log('Connected to Mongo Server');
});
return server;
}
main().then(server => {
console.log(`Server running at ${server.info.uri}`);
}).catch(err => {
console.error(err);
process.exit(1);
});