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 import {HttpError} from '../errors';
18 export type HttpHandler<I, O> = (params: I & AuthInfo, rawReq: Request, rawRes: Response) => Promise<O>;
20 export class HttpServer {
21 server: express.Application;
24 port: string | number;
25 bullAdapter: ExpressAdapter;
26 constructor(port: string | number) {
28 this.server = express();
29 this.bullAdapter = new ExpressAdapter()
30 this.configureMiddleWare();
31 this.http = http.createServer(this.server);
32 this.ws = new Server(this.http);
35 configureMiddleWare() {
36 this.server.use(express.json());
37 this.server.use(bodyParser());
38 this.server.use(express.static(join(__dirname, '..', '..', 'public')));
40 this.bullAdapter.setBasePath('/admin/queues');
41 this.server.use('/admin/queues', this.bullAdapter.getRouter());
44 authFromUrl(raw: string): {authInfo: {token: string, accountId: string}} {
45 let url = new URL('http://localhost.com?id=null&token=null');
50 token: url.searchParams.get('token'),
51 accountId: url.searchParams.get('id')
62 wrap<I, O>(handler: HttpHandler<I, O>, hxEvents: string) {
64 return async function (req: Request, res: Response) {
66 const start = Date.now();
67 console.log(`Req: ${req.method.toUpperCase()} ${req.path}`);
69 // extract hx game vars (token, id);
70 const headerData = self.authFromUrl(req.headers['hx-current-url'].toString());
71 const output: O = await handler(merge(req, headerData) as unknown as (I & AuthInfo), req, res);
72 console.log(`Runtime: ${Date.now() - start}ms`);
74 res.setHeader('hx-trigger', hxEvents);
75 if(output === undefined) {
78 else if(isString(output)) {
88 <div class="alert danger autofade">${e.message}</div>
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));
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));
107 start(fn?: any): void {
108 console.log(`Listening on port ${this.port}`);
109 this.http.listen(this.port, fn?.bind(this));