-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexpress.ts
99 lines (87 loc) · 2.15 KB
/
express.ts
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
import cookieParser from "cookie-parser";
import exp, {
Request,
RequestHandler,
ErrorRequestHandler,
Response,
NextFunction,
} from "express";
import session from "express-session";
import passport from "passport";
import flash from "connect-flash";
const app = exp();
app.use(exp.json()); // Body Parser
app.use(exp.urlencoded({ extended: false }));
app.use("/", exp.static("./public"));
app.use(cookieParser("SECRET"));
app.use(
session({
secret: "SECRET",
})
);
app.use(passport.initialize());
app.use(passport.session());
app.use(flash()); // 미들웨어에 장착 and req.xxx 메서드 추가 타이핑
declare global {
namespace Express {
export interface Response {
baoBabTree: "babTree";
}
export interface Request {
baoBabTree: "babTree";
}
}
}
// 미들웨어는 RequestHandler 타입이다.
const middleware: RequestHandler<
{ paramType: string },
{ message: string },
{ bodyType: number },
{ queryType: boolean },
{ localType: unknown }
> = (req, res, next) => {
req.params.paramType;
req.body.bodyType;
req.query.queryType;
res.locals.localType;
res.json({
message: "hello",
});
req.baoBabTree;
req.flash("플래시메시지"); // set
req.flash("1회성", "플래시메시지"); // set
const a = req.flash(); // get
req.flash(); // undefined
req.session;
req.user?.baoBabTree;
// declare global { types.d.ts
// namespace Express {
// interface User {
// baoBabTree: string;
// }
// }
// }
// export {};
};
app.get("/", middleware);
// app.get("/", (req, res) => {
// }, cors(), multer(), (req, res) => {
// }, (req, res) => {
// });
declare global {
interface Error {
status: number;
// Error는 lib이라서 import 안해도 사용 가능
}
// 혹여 import { ... , Error } from 'xxx'처럼 사용할 경우, 충돌을 대비해 declare global 사용, namespace까지 같이있다면 같이 사용
}
const errorMiddleware: ErrorRequestHandler = (
err: Error,
req: Request,
res: Express.Response, // 🔥
next: NextFunction
) => {
console.log(err.status);
};
app.use(errorMiddleware);
app.listen(8080, () => {});