All files / src bootstrap.ts

67.81% Statements 59/87
43.75% Branches 7/16
57.89% Functions 11/19
69.51% Lines 57/82

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 1817x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x   7x 7x 7x 7x   7x 7x             7x   7x     7x 7x   7x                                     7x   7x     7x 6x   6x     7x 8x 8x 8x 8x       1x 8x   8x 8x   8x               1x 36x       36x   4x   4x       1x         1x   1x             1x     7x               7x               7x                                                                     7x           7x 7x 7x 7x 7x 7x 7x    
import express from 'express';
import * as googleOAuth2Middleware from './web/middleware/googleOAuth2Middleware';
import { router as transactionsRouter } from './web/routes/transactionsRoutes';
import { router as gmailTransactionsRouter } from './web/routes/gmailTransactionsRoutes';
import { router as swaggerRouter } from './web/routes/swaggerRoutes';
import { router as healthRouter } from './web/routes/healthRoutes';
import { router as groupsRouter } from './web/routes/groupsRoutes';
import { router as groupRulesRouter } from './web/routes/groupRulesRoutes';
import { Sequelize } from 'sequelize-typescript';
import bodyParser from 'body-parser';
import * as mariadb from 'mariadb';
import { Server } from 'http';
import { limiter as rateLimiter } from './web/middleware/rateLimiter';
import { Umzug, SequelizeStorage, InputMigrations, Resolver, MigrationParams } from 'umzug';
import fs from 'fs';
import RepositoryError from './core/errors/repositoryError';
 
const createDatabaseIfNotExistsAsync = async (host: string, port: number, username: string, password: string, database: string) => {
    const conn = await mariadb.createConnection({
        host: host,
        port: port,
        user: username,
        password: password
    });
 
    await conn.query(`CREATE DATABASE IF NOT EXISTS \`${database}\`;`);
 
    await conn.end();
}
 
const createDatabaseConnectionAsync = async (host: string, port: number, username: string, password: string, database: string) => {
    await createDatabaseIfNotExistsAsync(host, port, username, password, database);
 
    const connection = new Sequelize({
        dialect: "mariadb",
        host: host,
        port: port,
        username: username,
        password: password,
        database: database,
        logging: false,
        pool: {
            max: 5,
            min: 0,
            acquire: 30000,
            idle: 10000
        },
        dialectOptions: {
            multipleStatements: true,
        },
    });
    
    await connection.authenticate();
    
    return connection;
}
 
const defineDatabaseModels = async (connection: Sequelize, force?: boolean) => {
    connection.addModels([__dirname + '/**/models/*.model.{js,ts}']);
 
    await connection.sync({ force });
}
 
const resolveMigrationTool = (connection: Sequelize) => {
    const resolveMigrationFileContentsAsync = (path: string) => new Promise<string>(resolve =>
        fs.readFile(path, (err, data) => {
            Iif (err) throw err;
            if (data) resolve(data.toString());
        })
    );
 
    const executeQueryAsync = async (context: Sequelize, path: string) => {
        const sql = await resolveMigrationFileContentsAsync(path);
 
        try {
            const [results, ] = await context.query(sql);
            
            return results;
        } catch (ex) {
            Iif (ex instanceof Error) {
                throw new RepositoryError(ex);
            }
        }
    }
    
    const resolver: Resolver<Sequelize> = (params: MigrationParams<Sequelize>) => {
        Iif (!params.path?.endsWith('.sql')) {
            return Umzug.defaultResolver(params);
        }
 
        return {
            name: params.name,
            up: async () => executeQueryAsync(params.context, params.path!),
            // eslint-disable-next-line
            down: async () => executeQueryAsync(params.context, params.path?.replace('.up.sql', '.down.sql')!)
        };
    };
    
    const migrations: InputMigrations<Sequelize> = {
        glob: __dirname + '/**/migrations/*.{js,ts,up.sql}',
        resolve: resolver
    };
 
    const storage = new SequelizeStorage({ sequelize: connection });
 
    const umzug = new Umzug({
        migrations,
        storage,
        context: connection,
        logger: console,
    });
 
    return umzug;
}
 
const applyDatabaseMigrationsAsync = async (umzug: Umzug<Sequelize>, step?: number) => {
    if (step === undefined) {
        await umzug.up();
    } else {
        await umzug.up({ step });
    }
}
 
const revertDatabaseMigrationsAsync = async (umzug: Umzug<Sequelize>, step?: number) => {
    if (step === undefined) {
        await umzug.down();
    } else {
        await umzug.down({ step });
    }
}
 
const startServerAsync = (port?: number) => {
    const app = express();
 
    app.use(bodyParser.urlencoded({ extended: true }));
 
    app.use(express.json());
 
    // Startup, Readiness and Liveness Probes
    app.use(healthRouter);
 
    app.use(rateLimiter);
 
    // Google OAuth2 Callback Route. Used for authz of all ../gmail routes, as well as for authn via oauth2-proxy
    app.use('/api/oauthcallback', googleOAuth2Middleware.redirect);
 
    // Transactions Routes
    app.use('/api/transactions', transactionsRouter);
 
    // Gmail Transactions Routes
    app.use('/api/transactions/gmail', googleOAuth2Middleware.protect, gmailTransactionsRouter);
 
    // Transaction Groups Routes
    app.use('/api/groups', groupsRouter);
    app.use('/api/groups/:group/rules', groupRulesRouter);
 
    // Swagger
    app.use('/swagger', swaggerRouter);
 
    const server = new Promise<Server>((resolve) => {
        const server: Server = app.listen(port, () => resolve(server));
    });
 
    return server;
};
 
const stopServerAsync = async (app: Server) =>
    new Promise<void>((resolve) =>
        app.on('close', () => resolve())
            .close());
 
export {
    createDatabaseConnectionAsync,
    defineDatabaseModels,
    resolveMigrationTool,
    applyDatabaseMigrationsAsync,
    revertDatabaseMigrationsAsync,
    startServerAsync,
    stopServerAsync
}