-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.js
More file actions
86 lines (67 loc) · 2.55 KB
/
api.js
File metadata and controls
86 lines (67 loc) · 2.55 KB
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
const { config } = require('dotenv');
const { join } = require('path');
const { ok } = require('assert')
const env = process.env.NODE_ENV || 'dev'
ok(env === "prod" || env === "dev", 'a env é inválida, ou dev ou prod');
const configPath = join(__dirname, './config', `.env.${env}`);
config({
path: configPath
});
console.log('port-app', process.env.PORT);
const Hapi = require('hapi');
const HeroRoute = require('./src/routes/heroRoutes');
const AuthRoute = require('./src/routes/authRoutes');
const UserSchemaPostgres = require('./src/bd/strategies/postgres/schema/userSchema');
const HeroSchemaMongo = require('./src/bd/strategies/mongodb/schema/hero.schema');
const HelperContext = require('./src/helpers/contextHelper');
const HapiSwagger = require('hapi-swagger');
const Vision = require('vision')
const Inert = require('inert');
const app = new Hapi.Server({ port: process.env.PORT });
const HaipJwt = require('hapi-auth-jwt2');
const JWT_SECRET = process.env.JWT_KEY;
function mapRoutes(instance, methods) {
return methods.map(method => instance[method]());
}
async function Main() {
const swaggerOtions = {
documentationPath: '/',
info: {
title: 'API Heroes - #CursoNodeBR',
version: 'v1.0',
contact: {
name: 'Diego Silva',
email: 'silva.pucrs@gmail.com',
url: 'https://github.com/doublesilva/'
},
},
lang: 'pt'
}
await app.register([HaipJwt, Vision, Inert, {
plugin: HapiSwagger,
options: swaggerOtions
}])
app.auth.strategy('jwt', 'jwt', {
key: JWT_SECRET,
// options: {
// expiresIn: 20
// },
validate: async (data, request) => {
const context = await HelperContext.ContextPostgress(UserSchemaPostgres);
const [result] = await context.read({ username: data.username.toLowerCase(), id: data.id });
if (!result) {
return { isValid: false };
}
return { isValid: true };
}
});
app.auth.default('jwt');
app.route([
...mapRoutes(new HeroRoute(HelperContext.ContextMongoDb(HeroSchemaMongo)), HeroRoute.methods()),
...mapRoutes(new AuthRoute(JWT_SECRET, (await HelperContext.ContextPostgress(UserSchemaPostgres))), AuthRoute.methods())
]);
await app.start()
console.log('server running at', app.info.port)
return app;
}
module.exports = Main();