-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.ts
More file actions
71 lines (58 loc) · 1.8 KB
/
app.ts
File metadata and controls
71 lines (58 loc) · 1.8 KB
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
import express, { Request, Response, NextFunction } from "express";
import "dotenv/config";
import helmet from "helmet";
import cors from "cors";
import morgan from "morgan";
// app setup
const app = express();
const port = process.env.PORT || 3000;
// API security
app.use(helmet());
app.use(cors());
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
// Redis connection
import { connectRedis } from "./src/helper/redis.helper.ts";
connectRedis();
// MongoDB connection
import mongoose from "mongoose";
mongoose.connect(process.env.MONGODB_URL as string);
if (process.env.NODE_ENV !== "production") {
mongoose.connection.on("connected", () => {
console.log("Mongoose is connected");
});
mongoose.connection.on("error", (err) => {
console.log(err);
});
// Logger
app.use(morgan("combined"));
}
// API router
import UserRouter from "./src/routers/user.router.ts";
import ListRouter from "./src/routers/list.router.ts";
import AuthRouter from "./src/routers/auth.router.ts";
// Register routes before error handlers
app.use("/v1/auth", AuthRouter);
app.use("/v1/user", UserRouter);
app.use("/v1/list", ListRouter);
// Error Handler for non-existent routes (404)
app.use("*", (req: Request, res: Response, next: NextFunction) => {
const error = new Error("Resource not found!") as Error & { status: number };
error.status = 404;
next(error); // Pass error to the next middleware
});
// Global error handler (catches any errors)
import handleError from "./src/utils/errorHandler.ts";
app.use(
"*",
(error: Error, req: Request, res: Response, next: NextFunction) => {
handleError(error, req, res);
}
);
// Start the server
if (process.env.NODE_ENV !== "test") {
app.listen(port, () =>
console.log(`API is ready on http://localhost:${port}`)
);
}
export default app;