blob: 161711cead6c08780540da6806640c395e451b4b [file] [log] [blame]
Misha Krieger-Raynauld708a9632022-10-14 22:55:59 -04001/*
2 * Copyright (C) 2022 Savoir-faire Linux Inc.
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU Affero General Public License as
6 * published by the Free Software Foundation; either version 3 of the
7 * License, or (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU Affero General Public License for more details.
13 *
14 * You should have received a copy of the GNU Affero General Public
15 * License along with this program. If not, see
16 * <https://www.gnu.org/licenses/>.
17 */
Misha Krieger-Raynauld242560f2022-10-16 19:59:58 -040018import express, { json, NextFunction, Request, Response } from 'express';
Misha Krieger-Raynauld8ef48402022-10-23 21:41:51 -040019import helmet from 'helmet';
Misha Krieger-Raynauld2f5d1ce2022-10-23 21:13:33 -040020import { HttpStatusCode } from 'jami-web-common';
Misha Krieger-Raynauld708a9632022-10-14 22:55:59 -040021import log from 'loglevel';
22import { Service } from 'typedi';
23
Misha Krieger-Raynauld242560f2022-10-16 19:59:58 -040024import { accountRouter } from './routers/account-router.js';
25import { authRouter } from './routers/auth-router.js';
Misha Krieger-Raynauld6f9c7ae2022-10-28 11:41:45 -040026import { nameserverRouter } from './routers/nameserver-router.js';
Misha Krieger-Raynauld708a9632022-10-14 22:55:59 -040027
28@Service()
Issam E. Maghnif796a092022-10-09 20:25:26 +000029export class App {
Misha Krieger-Raynauld708a9632022-10-14 22:55:59 -040030 async build() {
31 const app = express();
32
Misha Krieger-Raynauld8ef48402022-10-23 21:41:51 -040033 // Setup middleware
34 app.use(helmet());
Misha Krieger-Raynauld242560f2022-10-16 19:59:58 -040035 app.use(json());
36
Misha Krieger-Raynauld708a9632022-10-14 22:55:59 -040037 // Setup routing
Misha Krieger-Raynauld708a9632022-10-14 22:55:59 -040038 app.use('/auth', authRouter);
Misha Krieger-Raynauld242560f2022-10-16 19:59:58 -040039 app.use('/account', accountRouter);
Misha Krieger-Raynauld6f9c7ae2022-10-28 11:41:45 -040040 app.use('/ns', nameserverRouter);
Misha Krieger-Raynauld708a9632022-10-14 22:55:59 -040041
42 // Setup 404 error handling
43 app.use((_req, res) => {
Misha Krieger-Raynauld2f5d1ce2022-10-23 21:13:33 -040044 res.sendStatus(HttpStatusCode.NotFound);
Misha Krieger-Raynauld708a9632022-10-14 22:55:59 -040045 });
46
47 // Setup internal error handling
48 app.use((err: Error, _req: Request, res: Response, _next: NextFunction) => {
49 log.error(err);
Misha Krieger-Raynauld2f5d1ce2022-10-23 21:13:33 -040050 res.status(HttpStatusCode.InternalServerError).send(err.message);
Misha Krieger-Raynauld708a9632022-10-14 22:55:59 -040051 });
52
53 return app;
54 }
55}