eletrotupi / tcc/ commit / a1fd052

api: create an app factory (for working with ava later on)

Pedro Lucas Porcellis porcellis@eletrotupi.com · 6 months ago a1fd0524d340f602c388a3afd9383d95b2b8cfa9 Browse files
Parents bdc1f3a
Changed files
2
Additions
+37
Deletions
-23
/dev/null → api/src/create-app.ts
1 +
import express from 'express';
2 +
import cors from 'cors';
3 +
import morgan from 'morgan';
4 +
import userRouter from '@app/routes/users';
5 +
import authRouter from '@app/routes/auth';
6 +
import { errorHandler } from '@app/middleware/errorHandler';
7 +
import { PrismaClient } from '@prisma/client';
8 +

9 +
export function createApp(prismaClient?: PrismaClient) {
10 +
  const app = express();
11 +

12 +
  // Configure CORS
13 +
  app.use(cors({
14 +
    origin: process.env.FRONTEND_URL || '*',
15 +
    credentials: true
16 +
  }));
17 +

18 +
  app.use(express.json());
19 +

20 +
  // Only use morgan in non-test environments
21 +
  if (process.env.NODE_ENV !== 'test') {
22 +
    app.use(morgan('combined'));
23 +
  }
24 +

25 +
  // Make prisma client available to routes if provided (for testing)
26 +
  if (prismaClient) {
27 +
    app.locals.prisma = prismaClient;
28 +
  }
29 +

30 +
  app.use("/users", userRouter);
31 +
  app.use("/auth", authRouter);
32 +

33 +
  app.use(errorHandler); // always last
34 +

35 +
  return app;
36 +
}
api/src/index.ts modified+2 -23
api/src/index.ts
1 -
import express from 'express';
2 -
import cors from 'cors';
3 -
import morgan from 'morgan';
4 -
import userRouter from '@app/routes/users'
5 -
import authRouter from '@app/routes/auth'
6 -
import { errorHandler } from '@app/middleware/errorHandler';
1 +
import { createApp } from '@app/create-app';
7 2

8 3
const port = process.env.PORT || 3000;
9 4

10 -
const app = express();
11 -

12 -
// Configure CORS
13 -
// Fucking expo
14 -
app.use(cors({
15 -
  //origin: process.env.FRONTEND_URL || 'http://localhost:8081', // Expo default port
16 -
  origin: "*",
17 -
  credentials: true
18 -
}));
19 -

20 -
app.use(express.json())
21 -
app.use(morgan('combined'))
22 -

23 -
app.use("/users", userRouter);
24 -
app.use("/auth", authRouter);
25 -

26 -
app.use(errorHandler); // always last
5 +
const app = createApp();
27 6

28 7
app.listen(port, () => {
29 8
  console.log(`Server booted on port ${port}`)
30 9
})
31 10