@mandujs/core 0.3.2 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,219 +1,228 @@
1
- /**
2
- * Mandu Context - 만두 접시 🥟
3
- * Request/Response를 래핑하여 편리한 API 제공
4
- */
5
-
6
- import type { ZodSchema } from "zod";
7
-
8
- export class ManduContext {
9
- private store: Map<string, unknown> = new Map();
10
- private _params: Record<string, string>;
11
- private _query: Record<string, string>;
12
- private _shouldContinue: boolean = true;
13
- private _response: Response | null = null;
14
-
15
- constructor(
16
- public readonly request: Request,
17
- params: Record<string, string> = {}
18
- ) {
19
- this._params = params;
20
- this._query = this.parseQuery();
21
- }
22
-
23
- private parseQuery(): Record<string, string> {
24
- const url = new URL(this.request.url);
25
- const query: Record<string, string> = {};
26
- url.searchParams.forEach((value, key) => {
27
- query[key] = value;
28
- });
29
- return query;
30
- }
31
-
32
- // ============================================
33
- // 🥟 Request 읽기
34
- // ============================================
35
-
36
- /** Path parameters (e.g., /users/:id → { id: '123' }) */
37
- get params(): Record<string, string> {
38
- return this._params;
39
- }
40
-
41
- /** Query parameters (e.g., ?name=mandu → { name: 'mandu' }) */
42
- get query(): Record<string, string> {
43
- return this._query;
44
- }
45
-
46
- /** Request headers */
47
- get headers(): Headers {
48
- return this.request.headers;
49
- }
50
-
51
- /** HTTP method */
52
- get method(): string {
53
- return this.request.method;
54
- }
55
-
56
- /** Request URL */
57
- get url(): string {
58
- return this.request.url;
59
- }
60
-
61
- /**
62
- * Parse request body with optional Zod validation
63
- * @example
64
- * const data = await ctx.body() // any
65
- * const data = await ctx.body(UserSchema) // typed & validated
66
- */
67
- async body<T = unknown>(schema?: ZodSchema<T>): Promise<T> {
68
- const contentType = this.request.headers.get("content-type") || "";
69
- let data: unknown;
70
-
71
- if (contentType.includes("application/json")) {
72
- data = await this.request.json();
73
- } else if (contentType.includes("application/x-www-form-urlencoded")) {
74
- const formData = await this.request.formData();
75
- data = Object.fromEntries(formData.entries());
76
- } else if (contentType.includes("multipart/form-data")) {
77
- const formData = await this.request.formData();
78
- data = Object.fromEntries(formData.entries());
79
- } else {
80
- data = await this.request.text();
81
- }
82
-
83
- if (schema) {
84
- const result = schema.safeParse(data);
85
- if (!result.success) {
86
- throw new ValidationError(result.error.errors);
87
- }
88
- return result.data;
89
- }
90
-
91
- return data as T;
92
- }
93
-
94
- // ============================================
95
- // 🥟 Response 보내기
96
- // ============================================
97
-
98
- /** 200 OK */
99
- ok<T>(data: T): Response {
100
- return this.json(data, 200);
101
- }
102
-
103
- /** 201 Created */
104
- created<T>(data: T): Response {
105
- return this.json(data, 201);
106
- }
107
-
108
- /** 204 No Content */
109
- noContent(): Response {
110
- return new Response(null, { status: 204 });
111
- }
112
-
113
- /** 400 Bad Request */
114
- error(message: string, details?: unknown): Response {
115
- return this.json({ status: "error", message, details }, 400);
116
- }
117
-
118
- /** 401 Unauthorized */
119
- unauthorized(message: string = "Unauthorized"): Response {
120
- return this.json({ status: "error", message }, 401);
121
- }
122
-
123
- /** 403 Forbidden */
124
- forbidden(message: string = "Forbidden"): Response {
125
- return this.json({ status: "error", message }, 403);
126
- }
127
-
128
- /** 404 Not Found */
129
- notFound(message: string = "Not Found"): Response {
130
- return this.json({ status: "error", message }, 404);
131
- }
132
-
133
- /** 500 Internal Server Error */
134
- fail(message: string = "Internal Server Error"): Response {
135
- return this.json({ status: "error", message }, 500);
136
- }
137
-
138
- /** Custom JSON response */
139
- json<T>(data: T, status: number = 200): Response {
140
- return Response.json(data, { status });
141
- }
142
-
143
- /** Custom text response */
144
- text(data: string, status: number = 200): Response {
145
- return new Response(data, {
146
- status,
147
- headers: { "Content-Type": "text/plain" },
148
- });
149
- }
150
-
151
- /** Custom HTML response */
152
- html(data: string, status: number = 200): Response {
153
- return new Response(data, {
154
- status,
155
- headers: { "Content-Type": "text/html" },
156
- });
157
- }
158
-
159
- /** Redirect response */
160
- redirect(url: string, status: 301 | 302 | 307 | 308 = 302): Response {
161
- return Response.redirect(url, status);
162
- }
163
-
164
- // ============================================
165
- // 🥟 상태 저장 (Guard → Handler 전달)
166
- // ============================================
167
-
168
- /** Store value for later use */
169
- set<T>(key: string, value: T): void {
170
- this.store.set(key, value);
171
- }
172
-
173
- /** Get stored value */
174
- get<T>(key: string): T | undefined {
175
- return this.store.get(key) as T | undefined;
176
- }
177
-
178
- /** Check if key exists */
179
- has(key: string): boolean {
180
- return this.store.has(key);
181
- }
182
-
183
- // ============================================
184
- // 🥟 Guard 제어
185
- // ============================================
186
-
187
- /** Continue to next guard/handler */
188
- next(): symbol {
189
- this._shouldContinue = true;
190
- return NEXT_SYMBOL;
191
- }
192
-
193
- /** Check if should continue */
194
- get shouldContinue(): boolean {
195
- return this._shouldContinue;
196
- }
197
-
198
- /** Set early response (from guard) */
199
- setResponse(response: Response): void {
200
- this._shouldContinue = false;
201
- this._response = response;
202
- }
203
-
204
- /** Get early response */
205
- getResponse(): Response | null {
206
- return this._response;
207
- }
208
- }
209
-
210
- /** Symbol to indicate continue to next */
211
- export const NEXT_SYMBOL = Symbol("mandu:next");
212
-
213
- /** Validation error with details */
214
- export class ValidationError extends Error {
215
- constructor(public readonly errors: unknown[]) {
216
- super("Validation failed");
217
- this.name = "ValidationError";
218
- }
219
- }
1
+ /**
2
+ * Mandu Context - 만두 접시 🥟
3
+ * Request/Response를 래핑하여 편리한 API 제공
4
+ */
5
+
6
+ import type { ZodSchema } from "zod";
7
+
8
+ export class ManduContext {
9
+ private store: Map<string, unknown> = new Map();
10
+ private _params: Record<string, string>;
11
+ private _query: Record<string, string>;
12
+ private _shouldContinue: boolean = true;
13
+ private _response: Response | null = null;
14
+
15
+ constructor(
16
+ public readonly request: Request,
17
+ params: Record<string, string> = {}
18
+ ) {
19
+ this._params = params;
20
+ this._query = this.parseQuery();
21
+ }
22
+
23
+ private parseQuery(): Record<string, string> {
24
+ const url = new URL(this.request.url);
25
+ const query: Record<string, string> = {};
26
+ url.searchParams.forEach((value, key) => {
27
+ query[key] = value;
28
+ });
29
+ return query;
30
+ }
31
+
32
+ // ============================================
33
+ // 🥟 Request 읽기
34
+ // ============================================
35
+
36
+ /** Path parameters (e.g., /users/:id → { id: '123' }) */
37
+ get params(): Record<string, string> {
38
+ return this._params;
39
+ }
40
+
41
+ /** Query parameters (e.g., ?name=mandu → { name: 'mandu' }) */
42
+ get query(): Record<string, string> {
43
+ return this._query;
44
+ }
45
+
46
+ /** Request headers */
47
+ get headers(): Headers {
48
+ return this.request.headers;
49
+ }
50
+
51
+ /** HTTP method */
52
+ get method(): string {
53
+ return this.request.method;
54
+ }
55
+
56
+ /** Request URL */
57
+ get url(): string {
58
+ return this.request.url;
59
+ }
60
+
61
+ /**
62
+ * Parse request body with optional Zod validation
63
+ * @example
64
+ * const data = await ctx.body() // any
65
+ * const data = await ctx.body(UserSchema) // typed & validated
66
+ */
67
+ async body<T = unknown>(schema?: ZodSchema<T>): Promise<T> {
68
+ const contentType = this.request.headers.get("content-type") || "";
69
+ let data: unknown;
70
+
71
+ if (contentType.includes("application/json")) {
72
+ data = await this.request.json();
73
+ } else if (contentType.includes("application/x-www-form-urlencoded")) {
74
+ const formData = await this.request.formData();
75
+ data = Object.fromEntries(formData.entries());
76
+ } else if (contentType.includes("multipart/form-data")) {
77
+ const formData = await this.request.formData();
78
+ data = Object.fromEntries(formData.entries());
79
+ } else {
80
+ data = await this.request.text();
81
+ }
82
+
83
+ if (schema) {
84
+ const result = schema.safeParse(data);
85
+ if (!result.success) {
86
+ throw new ValidationError(result.error.errors);
87
+ }
88
+ return result.data;
89
+ }
90
+
91
+ return data as T;
92
+ }
93
+
94
+ // ============================================
95
+ // 🥟 Response 보내기
96
+ // ============================================
97
+
98
+ /** 200 OK */
99
+ ok<T>(data: T): Response {
100
+ return this.json(data, 200);
101
+ }
102
+
103
+ /** 201 Created */
104
+ created<T>(data: T): Response {
105
+ return this.json(data, 201);
106
+ }
107
+
108
+ /** 204 No Content */
109
+ noContent(): Response {
110
+ return new Response(null, { status: 204 });
111
+ }
112
+
113
+ /** 400 Bad Request */
114
+ error(message: string, details?: unknown): Response {
115
+ return this.json({ status: "error", message, details }, 400);
116
+ }
117
+
118
+ /** 401 Unauthorized */
119
+ unauthorized(message: string = "Unauthorized"): Response {
120
+ return this.json({ status: "error", message }, 401);
121
+ }
122
+
123
+ /** 403 Forbidden */
124
+ forbidden(message: string = "Forbidden"): Response {
125
+ return this.json({ status: "error", message }, 403);
126
+ }
127
+
128
+ /** 404 Not Found */
129
+ notFound(message: string = "Not Found"): Response {
130
+ return this.json({ status: "error", message }, 404);
131
+ }
132
+
133
+ /** 500 Internal Server Error */
134
+ fail(message: string = "Internal Server Error"): Response {
135
+ return this.json({ status: "error", message }, 500);
136
+ }
137
+
138
+ /** Custom JSON response */
139
+ json<T>(data: T, status: number = 200): Response {
140
+ return Response.json(data, { status });
141
+ }
142
+
143
+ /** Custom text response */
144
+ text(data: string, status: number = 200): Response {
145
+ return new Response(data, {
146
+ status,
147
+ headers: { "Content-Type": "text/plain" },
148
+ });
149
+ }
150
+
151
+ /** Custom HTML response */
152
+ html(data: string, status: number = 200): Response {
153
+ return new Response(data, {
154
+ status,
155
+ headers: { "Content-Type": "text/html" },
156
+ });
157
+ }
158
+
159
+ /** Redirect response */
160
+ redirect(url: string, status: 301 | 302 | 307 | 308 = 302): Response {
161
+ return Response.redirect(url, status);
162
+ }
163
+
164
+ // ============================================
165
+ // 🥟 상태 저장 (Guard → Handler 전달)
166
+ // ============================================
167
+
168
+ /** Store value for later use */
169
+ set<T>(key: string, value: T): void {
170
+ this.store.set(key, value);
171
+ }
172
+
173
+ /** Get stored value */
174
+ get<T>(key: string): T | undefined {
175
+ return this.store.get(key) as T | undefined;
176
+ }
177
+
178
+ /** Check if key exists */
179
+ has(key: string): boolean {
180
+ return this.store.has(key);
181
+ }
182
+
183
+ // ============================================
184
+ // 🥟 Guard 제어
185
+ // ============================================
186
+
187
+ /** Continue to next guard/handler */
188
+ next(): symbol {
189
+ this._shouldContinue = true;
190
+ return NEXT_SYMBOL;
191
+ }
192
+
193
+ /** Check if should continue */
194
+ get shouldContinue(): boolean {
195
+ return this._shouldContinue;
196
+ }
197
+
198
+ /** Set early response (from guard) */
199
+ setResponse(response: Response): void {
200
+ this._shouldContinue = false;
201
+ this._response = response;
202
+ }
203
+
204
+ /** Get early response */
205
+ getResponse(): Response | null {
206
+ return this._response;
207
+ }
208
+ }
209
+
210
+ /** Symbol to indicate continue to next */
211
+ export const NEXT_SYMBOL = Symbol("mandu:next");
212
+
213
+ /** Route context for error reporting */
214
+ export interface ValidationRouteContext {
215
+ routeId: string;
216
+ pattern: string;
217
+ }
218
+
219
+ /** Validation error with details */
220
+ export class ValidationError extends Error {
221
+ constructor(
222
+ public readonly errors: unknown[],
223
+ public readonly routeContext?: ValidationRouteContext
224
+ ) {
225
+ super("Validation failed");
226
+ this.name = "ValidationError";
227
+ }
228
+ }