xonecas.io
4515
Nr

node-react-typescript-boilerplate / files

node-react-typescript-boilerplate / server / src / index.ts

1.4 KB
1import cors from "@koa/cors";
2import { PrismaClient } from "@prisma/client";
3import Koa from "koa";
4import body from "koa-body";
5import json from "koa-json";
6import logger from "koa-logger";
7import Router from "koa-router";
8import stripAnsi from "strip-ansi";
9import auth_router from "./auth/routes";
10import health_check_router from "./health-check/routes"
11// try got and axios for server to server requests
12
13// Create the client to let prisma manage the connection pool
14const prisma = new PrismaClient();
15
16async function main() {
17  const app = new Koa();
18  const router = new Router();
19
20  // Middleware:
21  app.use(
22    logger((str) => {
23      // Remove colors for simplicity.
24      console.log(stripAnsi(str));
25    })
26  );
27  app.use(json());
28  app.use(body());
29  app.use(cors());
30
31  // Share the connection for the db:
32  app.use(async (ctx, next) => {
33    ctx.prisma = prisma;
34    await next();
35  });
36
37  // Serve configured routes:
38  app
39    .use(health_check_router.routes())
40    .use(health_check_router.allowedMethods());
41  app.use(auth_router.routes()).use(auth_router.allowedMethods());
42
43  // App starts
44  const port = process.env.PORT || 3001;
45  app.listen(port, () => console.log("Server listening on", port));
46}
47
48main()
49  .then(async () => {
50    await prisma.$disconnect();
51  })
52  .catch(async (e) => {
53    console.error(e);
54    await prisma.$disconnect();
55    process.exit();
56  });