generated from wednesday-solutions/nodejs-hapi-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
188 lines (167 loc) · 5.4 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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
import Hapi from '@hapi/hapi';
import path from 'path';
import wurst from 'wurst';
import { camelCase, snakeCase } from 'lodash';
import authBearer from 'hapi-auth-bearer-token';
import authConfig from 'config/auth';
import mapKeysDeep from 'map-keys-deep';
import hapiPagination from 'hapi-pagination';
import hapiSwaggerUI from 'hapi-swaggerui';
import inert from '@hapi/inert';
import vision from '@hapi/vision';
import Pack from './package.json';
import rateLimiter from 'hapi-rate-limit';
import rTracer from 'cls-rtracer';
import cors from 'hapi-cors';
import serverConfig from 'config/server';
import dbConfig from 'config/db';
import hapiPaginationOptions from 'utils/paginationConstants';
import models from 'models';
import { cachedUser } from 'utils/cacheMethods';
const prepDatabase = async () => {
await models.sequelize
.authenticate()
.then(() => {
// eslint-disable-next-line no-console
console.log('Connection has been established successfully.');
})
.catch(err => {
// eslint-disable-next-line no-console
console.error('Unable to connect to the database:', err);
});
};
export let server;
const initServer = async () => {
server = Hapi.server(serverConfig);
// Register hapi swagger plugin
await server.register([
inert,
vision,
{
plugin: hapiSwaggerUI,
swaggerOptions: {
documentationPage: true,
swaggerUI: true,
auth: false,
authorization: null,
info: {
title: 'Node Hapi Template API documentation',
version: Pack.version
}
},
options: {
grouping: 'tags',
tags: [
{
name: 'health-check',
description: 'Health check endpoint'
},
{
name: 'users',
description: 'User related endpoints'
},
{
name: 'oauth2-resources',
description: 'Oauth2 resources related endpoints'
},
{
name: 'oauth2-scopes',
description: 'Oauth2 scopes related endpoints'
},
{
name: 'oauth2-clients',
description: 'Oauth2 clients related endpoints'
},
{
name: 'oauth2-tokens',
description: 'Oauth2 tokens related endpoints'
},
{
name: 'reset-cache',
description: 'Cache invalidation endpoints'
}
]
}
}
]);
await server.register({
plugin: rTracer.hapiPlugin
});
// Register pagignation plugin
await server.register({
plugin: hapiPagination,
options: hapiPaginationOptions
});
// register auth plugin
await server.register({
plugin: authBearer
});
server.auth.strategy('bearer', 'bearer-access-token', authConfig);
server.auth.default('bearer');
// Register Wurst plugin
await server.register({
plugin: wurst,
options: {
routes: '**/routes.js',
cwd: path.join(__dirname, 'lib/routes'),
log: true
}
});
await cachedUser(server);
// Register cors plugin
await server.register({
plugin: cors,
options: {
origins: ['http://localhost:3000']
}
});
// Register rate limiter plugin
await server.register({
plugin: rateLimiter
});
await server.start();
const onPreHandler = function (request, h) {
const requestQueryParams = request.query;
const requestPayload = request.payload;
request.query = mapKeysDeep(requestQueryParams, keys =>
camelCase(keys)
);
request.payload = mapKeysDeep(requestPayload, keys => camelCase(keys));
return h.continue;
};
const onPreResponse = function (request, h) {
const response = request.response;
const responseSource = response.source;
response.source = mapKeysDeep(responseSource, keys => snakeCase(keys));
return h.continue;
};
server.ext('onPreHandler', onPreHandler);
server.ext('onPreResponse', onPreResponse);
// eslint-disable-next-line no-console
console.log('Server running on %s', server.info.uri);
return true;
};
process.on('unhandledRejection', err => {
// eslint-disable-next-line no-console
console.log(err);
process.exit(1);
});
prepDatabase().then(
() => {
// eslint-disable-next-line no-console
console.log(
`Database connection to ${
dbConfig.development.url
} is successful.\nThe following options were applied: ${JSON.stringify(
dbConfig.development
)}`
);
// eslint-disable-next-line no-console
console.log(`Initializing the server...`);
return initServer();
},
error => {
// eslint-disable-next-line no-console
console.error(error, `Server startup failed...`);
}
);