All files / src server.ts

70% Statements 42/60
46.66% Branches 7/15
50% Functions 2/4
70.68% Lines 41/58

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 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 1981026x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x           1x           1x           1x           1x 1x       1x     1x             1x 1x 1x 1x   1x   1x     1x 78x 78x                                                               1x     1x                                                                                                   1x           1x 1x 1x           1x     1x     1x       1x                                           1x  
// Sentry (error logging) instrumentation, must be imported first
import "@cooper/backend/src/instrument";
import * as Sentry from "@sentry/node";
import express, { Application, NextFunction, Request, Response } from "express";
import cors from "cors";
import { consoleLogger, activityLogger, logger } from "@cooper/backend/src/logging";
import { createExpressEndpoints, initServer } from "@ts-rest/express";
import { contract } from "@cooper/ts-rest/src/contract";
import { serve, setup } from "swagger-ui-express";
import cookieParser from "cookie-parser";
import openapi from "@cooper/backend/src/openapi";
import InMemoryDatabase from "@cooper/backend/src/database/in-memory/database";
import { config } from "dotenv";
 
import { getSelf, getUser } from "@cooper/backend/src/routes/protected/users";
import {
  getTransactions,
  newTransaction,
  updateTransaction,
  deleteTransaction,
} from "@cooper/backend/src/routes/protected/budgeting/transactions";
import {
  getAccounts,
  newAccount,
  updateAccount,
  deleteAccount,
} from "@cooper/backend/src/routes/protected/budgeting/accounts";
import {
  getWorkspaces,
  newWorkspace,
  updateWorkspace,
  deleteWorkspace,
} from "@cooper/backend/src/routes/protected/budgeting/workspaces";
import {
  getCategories,
  newCategory,
  updateCategory,
  deleteCategory,
} from "@cooper/backend/src/routes/protected/budgeting/categories";
import { login, logout, signup, getSessions, validSession } from "@cooper/backend/src/routes/public/auth";
 
config(); // Load variables from .env file into process.env
 
const app: Application = express();
 
// Express middleware and route handlers
app.use(
  cors({
    origin: true,
    credentials: true,
  }),
);
 
Iif (process.env.NODE_ENV != "test") app.use(consoleLogger);
app.use(activityLogger);
app.use(cookieParser());
app.use(express.json());
 
if (process.env.NODE_ENV == "test") {
  // Use in-memory mock database for testing performance
  app.locals.database = new InMemoryDatabase({});
 
  // Allow for our tests to reset the database with a call to this endpoint
  app.get("/testing/reset", (req: Request, res: Response) => {
    req.app.locals.database = new InMemoryDatabase({});
    res.status(200).send();
  });
E} else if (process.env.NODE_ENV == "dev") {
  const initialDatabase = {
    initialUsers: new Map([
      [
        "ianyeoh",
        {
          username: "ianyeoh",
          firstName: "Ian",
          lastName: "Yeoh",
          // hard-coded hash value of "asd", for testing
          password: "$2a$10$C/5nLYy.wjdrIGcQmKxiZ.OcQ9aQephzCTb10RVBvyzfKveYHJQoi",
        },
      ],
    ]),
  };
 
  // Use in-memory mock database for development
  app.locals.database = new InMemoryDatabase(initialDatabase);
 
  // Allow database reset (can be accessed with console command reset)
  app.get("/testing/reset", (req: Request, res: Response) => {
    req.app.locals.database = new InMemoryDatabase(initialDatabase);
    res.status(200).send();
  });
} else {
  // TODO: Change to Postgres DB
  app.locals.database = new InMemoryDatabase({});
}
 
// Initialise and mount ts-rest router
const s = initServer();
 
// @ts-expect-error Ignore type instantiation is excessively deep and possibly infinite error (T2589)
const router = s.router(contract, {
  protected: {
    users: {
      getSelf,
      getUser,
    },
    budgeting: {
      workspaces: {
        getWorkspaces,
        newWorkspace,
        byId: {
          updateWorkspace,
          deleteWorkspace,
          accounts: {
            getAccounts,
            newAccount,
            byId: {
              updateAccount,
              deleteAccount,
            },
          },
          categories: {
            getCategories,
            newCategory,
            byId: {
              updateCategory,
              deleteCategory,
            },
          },
          transactions: {
            getTransactions,
            newTransaction,
            byId: {
              updateTransaction,
              deleteTransaction,
            },
          },
        },
      },
    },
  },
  public: {
    auth: {
      login,
      logout,
      signup,
      validSession,
      getSessions,
    },
  },
});
createExpressEndpoints(contract, router, app, {
  responseValidation: true,
});
 
// Serve API docs at /docs
const apiDocs = express.Router();
apiDocs.use(serve);
apiDocs.get(
  "/",
  setup(openapi, {
    customCssUrl: "/static/theme-flattop.css",
  }),
);
app.use("/docs", apiDocs);
 
// Serve static files from /public directory
app.use(express.static("public"));
 
// The Sentry error handler must be registered before any other error middleware but after all routers
Sentry.setupExpressErrorHandler(app);
 
// Generic error handler
// eslint-disable-next-line @typescript-eslint/no-unused-vars
app.use((err: unknown, req: Request, res: Response, _next: NextFunction) => {
  Iif (process.env.NODE_ENV == "test") {
    logger.info(req.body);
    logger.info(err);
  }
 
  Iif (req.body) {
    logger.error(req.body);
  }
 
  if (err instanceof Error) {
    logger.error(`${err.name} - ${err.cause} - ${err.message} - ${err.stack}`);
  } else {
    logger.error(err);
  }
 
  res.status(500).json({
    error: "Unexpected server error. Please try again later.",
  });
  return;
});
 
export default app;