-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
76 lines (65 loc) · 1.51 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
require("dotenv").config();
const path = require("path");
require("./models");
// CommonJs
const fastify = require("fastify")({
logger: true,
});
/**
* Configure CORS
*/
fastify.register(require("@fastify/cors"), {
origin: [process.env.DASHBOARD_URL],
methods: "*",
allowedHeaders: ["Content-Type", "Authorization"],
});
/**
* Fastify Redis Register
*/
fastify.register(require("@fastify/redis"), {
host: process.env.REDIS_HOST,
port: process.env.REDIS_PORT,
});
/**
* Serve Static Assets
*/
fastify.register(require("@fastify/static"), {
root: path.join(__dirname, "public"),
// prefix: "/public/", // optional: default '/'
});
/**
* Autoload Plugins
*/
fastify.register(require("@fastify/autoload"), {
dir: path.join(__dirname, "plugins"),
});
/**
* Load Routes - From ./route/index (Array style)
*/
const { routes } = require("./routes/index");
routes.forEach(({ routeName, prefix }) => {
const route = path.join(__dirname, "routes", `${routeName}.js`);
fastify.register(require(route), { prefix });
});
/**
* Not Found Route
*/
fastify.setNotFoundHandler(function (request, reply) {
return reply.code(404).sendFile("404.html");
});
/**
* Run the server!
*/
const start = async () => {
try {
await fastify.listen({ port: process.env.PORT, host: process.env.HOST });
const redis = fastify.redis;
fastify.log.info(
`Redis listening at http://${redis.options.host}:${redis.options.port}`
);
} catch (err) {
fastify.log.error(err);
process.exit(1);
}
};
start();