UNPKG

2.22 kBPlain TextView Raw
1import { FastifyInstance, BootstrapOptions } from "./types";
2import * as IO from "socket.io";
3import fastify = require("fastify");
4import dotenv = require("dotenv");
5import { Plugin } from "./plugin";
6import { Controller } from "./controller";
7import { Module, DefaultModule } from "./module";
8import { Repository } from "./repository";
9
10function registerPlugins(server: FastifyInstance, plugins: Plugin[]) {
11 plugins.forEach(plugin => {
12 server.register(plugin.handler, plugin.options);
13 });
14}
15
16function registerControllers(
17 server: FastifyInstance,
18 controllers: Controller[]
19) {
20 controllers.forEach(controller => {
21 server.register(controller.handler, { prefix: controller.path });
22 });
23}
24
25function registerRepositories(
26 server: FastifyInstance,
27 repositories: Repository[]
28) {
29 repositories.forEach(repository => {
30 server.register(repository.controller.handler, {
31 prefix: repository.controller.path
32 });
33 });
34}
35
36function registerModules(
37 server: FastifyInstance,
38 modules: Module[],
39 wss?: IO.Server
40) {
41 modules.forEach(module => {
42 const { plugins, controllers, repositories } = module;
43 if (wss) {
44 registerWebsockets(wss, repositories);
45 }
46 registerPlugins(server, plugins);
47 registerControllers(server, controllers);
48 registerRepositories(server, repositories);
49 });
50}
51
52function registerWebsockets(wss: IO.Server, repositories: Repository[]) {
53 repositories.forEach(repo => {
54 if (!repo.websocket) {
55 return;
56 }
57 wss.on("connection", socket => {
58 repo.model.findAll().then(all => {
59 socket.emit(`${repo.name}`, all);
60 });
61 });
62 });
63}
64
65function startServer(port: string, server: FastifyInstance) {
66 server.listen(port, error => {
67 if (error) {
68 server.log.error(error);
69 process.exit(1);
70 return;
71 }
72 server.log.info(` > Server running on PORT ${port}`);
73 return;
74 });
75}
76
77export function bootstrap({ modules }: BootstrapOptions): void {
78 dotenv.config();
79
80 const port = process.env.PORT || "3000";
81 const server = fastify();
82 const wss = IO(server.server);
83
84 modules = [DefaultModule, ...modules];
85
86 registerModules(server, modules, wss);
87
88 return startServer(port, server);
89}