global chat via socket.io
[browser-rts.git] / src / lib / server.ts
1 import express, { Request, Response } from 'express';
2 import { join } from 'path';
3 import { isString } from 'lodash';
4 import { merge } from 'lodash';
5 import bodyParser from 'body-parser';
6 import { ExpressAdapter } from '@bull-board/express';
7 import http from 'http';
8 import { Server } from 'socket.io';
9
10 type AuthInfo = {
11         authInfo: { 
12                 accountId: string;
13                 token: string;
14         }
15 };
16
17 export type HttpHandler<I, O> = (params: I & AuthInfo, rawReq: Request, rawRes: Response) => Promise<O>;
18
19 export class HttpServer {
20         server: express.Application;
21   http: http.Server;
22   ws: Server;
23         port: string | number;
24         bullAdapter: ExpressAdapter;
25         constructor(port: string | number) {
26                 this.port = port;
27     this.server = express();
28                 this.bullAdapter = new ExpressAdapter()
29                 this.configureMiddleWare();
30     this.http = http.createServer(this.server);
31     this.ws = new Server(this.http);
32         }
33
34         configureMiddleWare() {
35                 this.server.use(express.json());
36                 this.server.use(bodyParser());
37                 this.server.use(express.static(join(__dirname, '..', '..', 'public')));
38                 
39                 this.bullAdapter.setBasePath('/admin/queues');
40                 this.server.use('/admin/queues', this.bullAdapter.getRouter());
41         }
42
43   authFromUrl(raw: string): {authInfo: {token: string, accountId: string}} {
44     let url = new URL('http://localhost.com?id=null&token=null');
45     try {
46       url = new URL(raw);
47       const authInfo = {
48         authInfo: {
49           token: url.searchParams.get('token'),
50           accountId: url.searchParams.get('id')
51         }
52       };
53
54       return authInfo;
55     }
56     catch(e) {
57       console.log(e);
58     }
59   }
60
61         wrap<I, O>(handler: HttpHandler<I, O>, hxEvents: string) {
62     const self = this;
63                 return async function (req: Request, res: Response) {
64                         try {
65                                 const start = Date.now();
66                                 console.log(`Req: ${req.method.toUpperCase()} ${req.path}`);
67
68                                 // extract hx game vars (token, id);
69         const headerData = self.authFromUrl(req.headers['hx-current-url'].toString());
70                                 const output: O = await handler(merge(req, headerData) as unknown as (I & AuthInfo), req, res);
71                                 console.log(`Runtime: ${Date.now() - start}ms`);
72
73                                 res.setHeader('hx-trigger', hxEvents);
74                                 if(output === undefined) {
75                                         res.statusCode = 204;
76                                 }
77                                 else if(isString(output)) {
78                                         res.send(output);
79                                 }
80                                 else {
81                                         res.json(output);
82                                 }
83                         }
84                         catch(e) {
85                                 console.log(e);
86                                 //res.statusCode = (e as HttpError).statusCode || 500;
87                                 res.send(`
88                                 <div class="alert danger">${e.message}</div>
89                                 `);
90                         }
91                         finally {
92                                 res.end();
93                         }
94                 }
95         }
96
97         get<I, O>(endpoint: string, handler: HttpHandler<I, O>, hxEvents: string = ''): void {
98                 console.log(`Mapped GET ${endpoint}`);
99                 this.server.get(endpoint, this.wrap(handler, hxEvents));
100         }
101
102         post<I, O>(endpoint: string, handler: HttpHandler<I, O>, hxEvents: string = ''): void {
103                 console.log(`Mapped POST ${endpoint}`);
104                 this.server.post(endpoint, this.wrap(handler, hxEvents));
105         }
106
107         start(fn?: any): void {
108                 console.log(`Listening on port ${this.port}`);
109                 this.http.listen(this.port, fn?.bind(this));
110         }
111 }