@h3ravel/http 0.1.0

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.
@@ -0,0 +1,199 @@
1
+ import { H3Event, EventHandlerRequest } from 'h3';
2
+ import { DotNestedKeys, DotNestedValue } from '@h3ravel/support';
3
+ import { ServiceProvider } from '@h3ravel/core';
4
+
5
+ declare class Request {
6
+ private readonly event;
7
+ constructor(event: H3Event);
8
+ /**
9
+ * Get all input data (query + body).
10
+ */
11
+ all<T = Record<string, unknown>>(): Promise<T>;
12
+ /**
13
+ * Get a single input field from query or body.
14
+ */
15
+ input<T = unknown>(key: string, defaultValue?: T): Promise<T>;
16
+ /**
17
+ * Get route parameters.
18
+ */
19
+ params<T = Record<string, string>>(): T;
20
+ /**
21
+ * Get query parameters.
22
+ */
23
+ query<T = Record<string, string>>(): T;
24
+ /**
25
+ * Get the base event
26
+ */
27
+ getEvent(): H3Event;
28
+ getEvent<K extends DotNestedKeys<H3Event>>(key: K): DotNestedValue<H3Event, K>;
29
+ }
30
+
31
+ declare class Response {
32
+ private readonly event;
33
+ private statusCode;
34
+ private headers;
35
+ constructor(event: H3Event);
36
+ /**
37
+ * Set HTTP status code.
38
+ */
39
+ setStatusCode(code: number): this;
40
+ /**
41
+ * Set a header.
42
+ */
43
+ setHeader(name: string, value: string): this;
44
+ html(content: string): string;
45
+ /**
46
+ * Send a JSON response.
47
+ */
48
+ json<T = unknown>(data: T): T;
49
+ /**
50
+ * Send plain text.
51
+ */
52
+ text(data: string): string;
53
+ /**
54
+ * Redirect to another URL.
55
+ */
56
+ redirect(url: string, status?: number): string;
57
+ /**
58
+ * Apply headers before sending response.
59
+ */
60
+ private applyHeaders;
61
+ /**
62
+ * Get the base event
63
+ */
64
+ getEvent(): H3Event;
65
+ getEvent<K extends DotNestedKeys<H3Event>>(key: K): DotNestedValue<H3Event, K>;
66
+ }
67
+
68
+ interface HttpContext {
69
+ request: Request;
70
+ response: Response;
71
+ }
72
+
73
+ declare abstract class Middleware {
74
+ abstract handle(context: HttpContext, next: () => Promise<unknown>): Promise<unknown>;
75
+ }
76
+
77
+ /**
78
+ * Defines the contract for all controllers.
79
+ * Any controller implementing this must define these methods.
80
+ */
81
+ interface IController {
82
+ show(ctx: HttpContext): any;
83
+ index(ctx: HttpContext): any;
84
+ store(ctx: HttpContext): any;
85
+ update(ctx: HttpContext): any;
86
+ destroy(ctx: HttpContext): any;
87
+ }
88
+
89
+ declare class LogRequests extends Middleware {
90
+ handle({ request }: HttpContext, next: () => Promise<unknown>): Promise<unknown>;
91
+ }
92
+
93
+ /**
94
+ * Sets up HTTP kernel and request lifecycle.
95
+ *
96
+ * Register Request, Response, and Middleware classes.
97
+ * Configure global middleware stack.
98
+ * Boot HTTP kernel.
99
+ *
100
+ * Auto-Registered
101
+ */
102
+ declare class HttpServiceProvider extends ServiceProvider {
103
+ register(): void;
104
+ }
105
+
106
+ interface Resource {
107
+ [key: string]: any;
108
+ pagination?: {
109
+ from?: number | undefined;
110
+ to?: number | undefined;
111
+ perPage?: number | undefined;
112
+ total?: number | undefined;
113
+ } | undefined;
114
+ }
115
+ type BodyResource = Resource & {
116
+ data: Omit<Resource, 'pagination'>;
117
+ meta?: {
118
+ pagination?: Resource['pagination'];
119
+ } | undefined;
120
+ };
121
+ /**
122
+ * Class to render API resource
123
+ */
124
+ declare class JsonResource<R extends Resource = any> {
125
+ #private;
126
+ private event;
127
+ /**
128
+ * The request instance
129
+ */
130
+ request: H3Event<EventHandlerRequest>['req'];
131
+ /**
132
+ * The response instance
133
+ */
134
+ response: H3Event['res'];
135
+ /**
136
+ * The data to send to the client
137
+ */
138
+ resource: R;
139
+ /**
140
+ * The final response data object
141
+ */
142
+ body: BodyResource;
143
+ /**
144
+ * Flag to track if response should be sent automatically
145
+ */
146
+ private shouldSend;
147
+ /**
148
+ * Flag to track if response has been sent
149
+ */
150
+ private responseSent;
151
+ /**
152
+ * Declare that this includes R's properties
153
+ */
154
+ [key: string]: any;
155
+ /**
156
+ * @param req The request instance
157
+ * @param res The response instance
158
+ * @param rsc The data to send to the client
159
+ */
160
+ constructor(event: H3Event, rsc: R);
161
+ /**
162
+ * Return the data in the expected format
163
+ *
164
+ * @returns
165
+ */
166
+ data(): Resource;
167
+ /**
168
+ * Build the response object
169
+ * @returns this
170
+ */
171
+ json(): this;
172
+ /**
173
+ * Add context data to the response object
174
+ * @param data Context data
175
+ * @returns this
176
+ */
177
+ additional<X extends {
178
+ [key: string]: any;
179
+ }>(data: X): this;
180
+ /**
181
+ * Send the output to the client
182
+ * @returns this
183
+ */
184
+ send(): this;
185
+ /**
186
+ * Set the status code for this response
187
+ * @param code Status code
188
+ * @returns this
189
+ */
190
+ status(code: number): this;
191
+ /**
192
+ * Check if send should be triggered automatically
193
+ */
194
+ private checkSend;
195
+ }
196
+
197
+ declare function ApiResource(instance: JsonResource): JsonResource<any>;
198
+
199
+ export { ApiResource, type HttpContext, HttpServiceProvider, type IController, JsonResource, LogRequests, Middleware, Request, type Resource, Response };
package/dist/index.js ADDED
@@ -0,0 +1,340 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
3
+
4
+ // src/Middleware.ts
5
+ var Middleware = class {
6
+ static {
7
+ __name(this, "Middleware");
8
+ }
9
+ };
10
+
11
+ // src/Request.ts
12
+ import { getQuery, getRouterParams, readBody } from "h3";
13
+ import { safeDot } from "@h3ravel/support";
14
+ var Request = class {
15
+ static {
16
+ __name(this, "Request");
17
+ }
18
+ event;
19
+ constructor(event) {
20
+ this.event = event;
21
+ }
22
+ /**
23
+ * Get all input data (query + body).
24
+ */
25
+ async all() {
26
+ let data = {
27
+ ...getRouterParams(this.event),
28
+ ...getQuery(this.event)
29
+ };
30
+ if (this.event.req.method === "POST") {
31
+ data = Object.assign({}, data, Object.fromEntries((await this.event.req.formData()).entries()));
32
+ } else if (this.event.req.method === "PUT") {
33
+ data = Object.fromEntries(Object.entries(await readBody(this.event)));
34
+ }
35
+ return data;
36
+ }
37
+ /**
38
+ * Get a single input field from query or body.
39
+ */
40
+ async input(key, defaultValue) {
41
+ const data = await this.all();
42
+ return data[key] ?? defaultValue;
43
+ }
44
+ /**
45
+ * Get route parameters.
46
+ */
47
+ params() {
48
+ return getRouterParams(this.event);
49
+ }
50
+ /**
51
+ * Get query parameters.
52
+ */
53
+ query() {
54
+ return getQuery(this.event);
55
+ }
56
+ getEvent(key) {
57
+ return safeDot(this.event, key);
58
+ }
59
+ };
60
+
61
+ // src/Response.ts
62
+ import { safeDot as safeDot2 } from "@h3ravel/support";
63
+ import { html, redirect } from "h3";
64
+ var Response = class {
65
+ static {
66
+ __name(this, "Response");
67
+ }
68
+ event;
69
+ statusCode = 200;
70
+ headers = {};
71
+ constructor(event) {
72
+ this.event = event;
73
+ }
74
+ /**
75
+ * Set HTTP status code.
76
+ */
77
+ setStatusCode(code) {
78
+ this.statusCode = code;
79
+ this.event.res.status = code;
80
+ return this;
81
+ }
82
+ /**
83
+ * Set a header.
84
+ */
85
+ setHeader(name, value) {
86
+ this.headers[name] = value;
87
+ return this;
88
+ }
89
+ html(content) {
90
+ this.applyHeaders();
91
+ return html(this.event, content);
92
+ }
93
+ /**
94
+ * Send a JSON response.
95
+ */
96
+ json(data) {
97
+ this.setHeader("content-type", "application/json; charset=utf-8");
98
+ this.applyHeaders();
99
+ return data;
100
+ }
101
+ /**
102
+ * Send plain text.
103
+ */
104
+ text(data) {
105
+ this.setHeader("content-type", "text/plain; charset=utf-8");
106
+ this.applyHeaders();
107
+ return data;
108
+ }
109
+ /**
110
+ * Redirect to another URL.
111
+ */
112
+ redirect(url, status = 302) {
113
+ this.setStatusCode(status);
114
+ return redirect(this.event, url, this.statusCode);
115
+ }
116
+ /**
117
+ * Apply headers before sending response.
118
+ */
119
+ applyHeaders() {
120
+ Object.entries(this.headers).forEach(([key, value]) => {
121
+ this.event.res.headers.set(key, value);
122
+ });
123
+ }
124
+ getEvent(key) {
125
+ return safeDot2(this.event, key);
126
+ }
127
+ };
128
+
129
+ // src/Middleware/LogRequests.ts
130
+ var LogRequests = class extends Middleware {
131
+ static {
132
+ __name(this, "LogRequests");
133
+ }
134
+ async handle({ request }, next) {
135
+ const url = request.getEvent("url");
136
+ console.log(`[${request.getEvent("method")}] ${url.pathname + url.search}`);
137
+ return next();
138
+ }
139
+ };
140
+
141
+ // src/Providers/HttpServiceProvider.ts
142
+ import { H3, serve } from "h3";
143
+ import { ServiceProvider } from "@h3ravel/core";
144
+ var HttpServiceProvider = class extends ServiceProvider {
145
+ static {
146
+ __name(this, "HttpServiceProvider");
147
+ }
148
+ register() {
149
+ this.app.singleton("http.app", () => {
150
+ return new H3();
151
+ });
152
+ this.app.singleton("http.serve", () => serve);
153
+ }
154
+ };
155
+
156
+ // src/Resources/JsonResource.ts
157
+ var JsonResource = class {
158
+ static {
159
+ __name(this, "JsonResource");
160
+ }
161
+ event;
162
+ /**
163
+ * The request instance
164
+ */
165
+ request;
166
+ /**
167
+ * The response instance
168
+ */
169
+ response;
170
+ /**
171
+ * The data to send to the client
172
+ */
173
+ resource;
174
+ /**
175
+ * The final response data object
176
+ */
177
+ body = {
178
+ data: {}
179
+ };
180
+ /**
181
+ * Flag to track if response should be sent automatically
182
+ */
183
+ shouldSend = false;
184
+ /**
185
+ * Flag to track if response has been sent
186
+ */
187
+ responseSent = false;
188
+ /**
189
+ * @param req The request instance
190
+ * @param res The response instance
191
+ * @param rsc The data to send to the client
192
+ */
193
+ constructor(event, rsc) {
194
+ this.event = event;
195
+ this.request = event.req;
196
+ this.response = event.res;
197
+ this.resource = rsc;
198
+ for (const key of Object.keys(rsc)) {
199
+ if (!(key in this)) {
200
+ Object.defineProperty(this, key, {
201
+ enumerable: true,
202
+ configurable: true,
203
+ get: /* @__PURE__ */ __name(() => this.resource[key], "get"),
204
+ set: /* @__PURE__ */ __name((value) => {
205
+ this.resource[key] = value;
206
+ }, "set")
207
+ });
208
+ }
209
+ }
210
+ }
211
+ /**
212
+ * Return the data in the expected format
213
+ *
214
+ * @returns
215
+ */
216
+ data() {
217
+ return this.resource;
218
+ }
219
+ /**
220
+ * Build the response object
221
+ * @returns this
222
+ */
223
+ json() {
224
+ this.shouldSend = true;
225
+ this.response.status = 200;
226
+ const resource = this.data();
227
+ let data = Array.isArray(resource) ? [
228
+ ...resource
229
+ ] : {
230
+ ...resource
231
+ };
232
+ if (typeof data.data !== "undefined") {
233
+ data = data.data;
234
+ }
235
+ if (!Array.isArray(resource)) {
236
+ delete data.pagination;
237
+ }
238
+ this.body = {
239
+ data
240
+ };
241
+ if (!Array.isArray(resource) && resource.pagination) {
242
+ const meta = this.body.meta ?? {};
243
+ meta.pagination = resource.pagination;
244
+ this.body.meta = meta;
245
+ }
246
+ if (this.resource.pagination && !this.body.meta?.pagination) {
247
+ const meta = this.body.meta ?? {};
248
+ meta.pagination = this.resource.pagination;
249
+ this.body.meta = meta;
250
+ }
251
+ return this;
252
+ }
253
+ /**
254
+ * Add context data to the response object
255
+ * @param data Context data
256
+ * @returns this
257
+ */
258
+ additional(data) {
259
+ this.shouldSend = true;
260
+ delete data.data;
261
+ delete data.pagination;
262
+ this.body = {
263
+ ...this.body,
264
+ ...data
265
+ };
266
+ return this;
267
+ }
268
+ /**
269
+ * Send the output to the client
270
+ * @returns this
271
+ */
272
+ send() {
273
+ this.shouldSend = false;
274
+ if (!this.responseSent) {
275
+ this.#send();
276
+ }
277
+ return this;
278
+ }
279
+ /**
280
+ * Set the status code for this response
281
+ * @param code Status code
282
+ * @returns this
283
+ */
284
+ status(code) {
285
+ this.response.status = code;
286
+ return this;
287
+ }
288
+ /**
289
+ * Private method to send the response
290
+ */
291
+ #send() {
292
+ if (!this.responseSent) {
293
+ this.event.context.this.response.json(this.body);
294
+ this.responseSent = true;
295
+ }
296
+ }
297
+ /**
298
+ * Check if send should be triggered automatically
299
+ */
300
+ checkSend() {
301
+ if (this.shouldSend && !this.responseSent) {
302
+ this.#send();
303
+ }
304
+ }
305
+ };
306
+
307
+ // src/Resources/ApiResource.ts
308
+ function ApiResource(instance) {
309
+ return new Proxy(instance, {
310
+ get(target, prop, receiver) {
311
+ const value = Reflect.get(target, prop, receiver);
312
+ if (typeof value === "function") {
313
+ if (prop === "json" || prop === "additional") {
314
+ return (...args) => {
315
+ const result = value.apply(target, args);
316
+ setImmediate(() => target["checkSend"]());
317
+ return result;
318
+ };
319
+ } else if (prop === "send") {
320
+ return (...args) => {
321
+ target["shouldSend"] = false;
322
+ return value.apply(target, args);
323
+ };
324
+ }
325
+ }
326
+ return value;
327
+ }
328
+ });
329
+ }
330
+ __name(ApiResource, "ApiResource");
331
+ export {
332
+ ApiResource,
333
+ HttpServiceProvider,
334
+ JsonResource,
335
+ LogRequests,
336
+ Middleware,
337
+ Request,
338
+ Response
339
+ };
340
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/Middleware.ts","../src/Request.ts","../src/Response.ts","../src/Middleware/LogRequests.ts","../src/Providers/HttpServiceProvider.ts","../src/Resources/JsonResource.ts","../src/Resources/ApiResource.ts"],"sourcesContent":["import { HttpContext } from './Contracts/HttpContract';\n\nexport abstract class Middleware {\n abstract handle (context: HttpContext, next: () => Promise<unknown>): Promise<unknown>\n}\n","import { getQuery, getRouterParams, readBody, type H3Event } from 'h3'\nimport { DotNestedKeys, DotNestedValue, safeDot } from '@h3ravel/support'\n\nexport class Request {\n private readonly event: H3Event\n\n constructor(event: H3Event) {\n this.event = event\n }\n\n /**\n * Get all input data (query + body).\n */\n async all<T = Record<string, unknown>> (): Promise<T> {\n let data = {\n ...getRouterParams(this.event),\n ...getQuery(this.event),\n } as T\n\n if (this.event.req.method === 'POST') {\n data = Object.assign({}, data, Object.fromEntries((await this.event.req.formData()).entries()))\n } else if (this.event.req.method === 'PUT') {\n data = <never>Object.fromEntries(Object.entries(<never>await readBody(this.event)))\n }\n\n return data\n }\n\n /**\n * Get a single input field from query or body.\n */\n async input<T = unknown> (key: string, defaultValue?: T): Promise<T> {\n const data = await this.all<Record<string, T>>()\n return (data[key] ?? defaultValue) as T\n }\n\n /**\n * Get route parameters.\n */\n params<T = Record<string, string>> (): T {\n return getRouterParams(this.event) as T\n }\n\n /**\n * Get query parameters.\n */\n query<T = Record<string, string>> (): T {\n return getQuery(this.event) as T\n }\n\n /**\n * Get the base event\n */\n getEvent (): H3Event\n getEvent<K extends DotNestedKeys<H3Event>> (key: K): DotNestedValue<H3Event, K>\n getEvent<K extends DotNestedKeys<H3Event>> (key?: K): any {\n return safeDot(this.event, key)\n }\n}\n","import { DotNestedKeys, DotNestedValue, safeDot } from '@h3ravel/support'\nimport { html, redirect, } from 'h3'\n\nimport type { H3Event } from 'h3'\n\nexport class Response {\n private readonly event: H3Event\n private statusCode: number = 200\n private headers: Record<string, string> = {}\n\n constructor(event: H3Event) {\n this.event = event\n }\n\n /**\n * Set HTTP status code.\n */\n setStatusCode (code: number): this {\n this.statusCode = code\n this.event.res.status = code\n return this\n }\n\n /**\n * Set a header.\n */\n setHeader (name: string, value: string): this {\n this.headers[name] = value\n return this\n }\n\n html (content: string): string {\n this.applyHeaders()\n return html(this.event, content)\n }\n\n /**\n * Send a JSON response.\n */\n json<T = unknown> (data: T): T {\n this.setHeader(\"content-type\", \"application/json; charset=utf-8\")\n this.applyHeaders()\n return data\n }\n\n /**\n * Send plain text.\n */\n text (data: string): string {\n this.setHeader(\"content-type\", \"text/plain; charset=utf-8\")\n this.applyHeaders()\n return data;\n }\n\n /**\n * Redirect to another URL.\n */\n redirect (url: string, status = 302): string {\n this.setStatusCode(status)\n return redirect(this.event, url, this.statusCode)\n }\n\n /**\n * Apply headers before sending response.\n */\n private applyHeaders (): void {\n Object.entries(this.headers).forEach(([key, value]) => {\n this.event.res.headers.set(key, value)\n })\n }\n\n /**\n * Get the base event\n */\n getEvent (): H3Event\n getEvent<K extends DotNestedKeys<H3Event>> (key: K): DotNestedValue<H3Event, K>\n getEvent<K extends DotNestedKeys<H3Event>> (key?: K): any {\n return safeDot(this.event, key)\n }\n}\n","import { HttpContext, Middleware } from '@h3ravel/http'\n\nexport class LogRequests extends Middleware {\n async handle ({ request }: HttpContext, next: () => Promise<unknown>): Promise<unknown> {\n const url = request.getEvent('url')\n console.log(`[${request.getEvent('method')}] ${url.pathname + url.search}`)\n return next()\n }\n}\n","import { H3, serve } from 'h3'\n\nimport { ServiceProvider } from '@h3ravel/core'\n\n/**\n * Sets up HTTP kernel and request lifecycle.\n * \n * Register Request, Response, and Middleware classes.\n * Configure global middleware stack.\n * Boot HTTP kernel.\n * \n * Auto-Registered\n */\nexport class HttpServiceProvider extends ServiceProvider {\n register () {\n this.app.singleton('http.app', () => {\n return new H3()\n })\n\n this.app.singleton('http.serve', () => serve)\n }\n}\n","import { EventHandlerRequest, H3Event } from \"h3\";\n\nexport interface Resource {\n [key: string]: any;\n pagination?: {\n from?: number | undefined;\n to?: number | undefined;\n perPage?: number | undefined;\n total?: number | undefined;\n } | undefined;\n}\n\ntype BodyResource = Resource & {\n data: Omit<Resource, 'pagination'>,\n meta?: {\n pagination?: Resource['pagination']\n } | undefined;\n}\n\n/**\n * Class to render API resource\n */\nexport class JsonResource<R extends Resource = any> {\n /**\n * The request instance\n */\n request: H3Event<EventHandlerRequest>['req'];\n /**\n * The response instance\n */\n response: H3Event['res'];\n /**\n * The data to send to the client\n */\n resource: R;\n /**\n * The final response data object\n */\n body: BodyResource = {\n data: {},\n };\n /**\n * Flag to track if response should be sent automatically\n */\n private shouldSend: boolean = false;\n /**\n * Flag to track if response has been sent\n */\n\n private responseSent: boolean = false;\n\n /**\n * Declare that this includes R's properties\n */\n [key: string]: any;\n\n /**\n * @param req The request instance\n * @param res The response instance\n * @param rsc The data to send to the client\n */\n constructor(private event: H3Event, rsc: R) {\n this.request = event.req;\n this.response = event.res;\n this.resource = rsc;\n\n // Copy all properties from rsc to this, avoiding conflicts\n for (const key of Object.keys(rsc)) {\n if (!(key in this)) {\n Object.defineProperty(this, key, {\n enumerable: true,\n configurable: true,\n get: () => this.resource[key],\n set: (value) => {\n (<any>this.resource)[key] = value;\n },\n });\n }\n }\n }\n\n /**\n * Return the data in the expected format\n * \n * @returns \n */\n data (): Resource {\n return this.resource\n }\n\n /**\n * Build the response object\n * @returns this\n */\n json () {\n // Indicate response should be sent automatically\n this.shouldSend = true;\n\n // Set default status code\n this.response.status = 200;\n\n // Prepare body\n const resource = this.data()\n let data: Resource = Array.isArray(resource) ? [...resource] : { ...resource };\n\n if (typeof data.data !== 'undefined') {\n data = data.data\n }\n\n if (!Array.isArray(resource)) {\n delete data.pagination;\n }\n\n this.body = {\n data,\n };\n\n // Set the pagination from the data() resource, if available\n if (!Array.isArray(resource) && resource.pagination) {\n const meta: BodyResource['meta'] = this.body.meta ?? {}\n meta.pagination = resource.pagination;\n this.body.meta = meta;\n }\n\n // If pagination is not available on the resource, then check and set it\n // if it's available on the base resource.\n if (this.resource.pagination && !this.body.meta?.pagination) {\n const meta: BodyResource['meta'] = this.body.meta ?? {}\n meta.pagination = this.resource.pagination;\n this.body.meta = meta;\n }\n\n return this;\n }\n\n /**\n * Add context data to the response object\n * @param data Context data\n * @returns this\n */\n additional<X extends { [key: string]: any }> (data: X) {\n\n // Allow automatic send after additional\n this.shouldSend = true;\n\n // Merge data with body\n delete data.data;\n delete data.pagination;\n\n this.body = {\n ...this.body,\n ...data,\n };\n\n return this;\n }\n\n /**\n * Send the output to the client\n * @returns this\n */\n send () {\n this.shouldSend = false; // Prevent automatic send\n if (!this.responseSent) {\n this.#send();\n }\n return this;\n }\n\n /**\n * Set the status code for this response\n * @param code Status code\n * @returns this\n */\n status (code: number) {\n this.response.status = code;\n return this;\n }\n\n /**\n * Private method to send the response\n */\n #send () {\n if (!this.responseSent) {\n this.event.context.\n this.response.json(this.body);\n\n // Mark response as sent\n this.responseSent = true;\n }\n }\n\n /**\n * Check if send should be triggered automatically\n */\n private checkSend () {\n if (this.shouldSend && !this.responseSent) {\n this.#send();\n }\n }\n}\n","import { JsonResource, Resource } from \"./JsonResource\";\n\nimport { H3Event } from \"h3\";\n\nexport function ApiResource (\n instance: JsonResource\n) {\n return new Proxy(instance, {\n get (target, prop, receiver) {\n const value = Reflect.get(target, prop, receiver);\n if (typeof value === 'function') {\n // Intercept json, additional, and send methods\n if (prop === 'json' || prop === 'additional') {\n return (...args: any[]) => {\n const result = value.apply(target, args);\n // Schedule checkSend after json or additional\n setImmediate(() => target['checkSend']());\n return result;\n };\n } else if (prop === 'send') {\n return (...args: any[]) => {\n // Prevent checkSend from firing\n target['shouldSend'] = false;\n\n return value.apply(target, args);\n };\n }\n }\n return value;\n },\n });\n}\n\nexport default function BaseResource<R extends Resource> (\n evt: H3Event,\n rsc: R\n) {\n return ApiResource(new JsonResource<R>(evt, rsc))\n}\n"],"mappings":";;;;AAEO,IAAeA,aAAf,MAAeA;EAAtB,OAAsBA;;;AAEtB;;;ACJA,SAASC,UAAUC,iBAAiBC,gBAA8B;AAClE,SAAwCC,eAAe;AAEhD,IAAMC,UAAN,MAAMA;EAHb,OAGaA;;;EACQC;EAEjB,YAAYA,OAAgB;AACxB,SAAKA,QAAQA;EACjB;;;;EAKA,MAAMC,MAAgD;AAClD,QAAIC,OAAO;MACP,GAAGC,gBAAgB,KAAKH,KAAK;MAC7B,GAAGI,SAAS,KAAKJ,KAAK;IAC1B;AAEA,QAAI,KAAKA,MAAMK,IAAIC,WAAW,QAAQ;AAClCJ,aAAOK,OAAOC,OAAO,CAAC,GAAGN,MAAMK,OAAOE,aAAa,MAAM,KAAKT,MAAMK,IAAIK,SAAQ,GAAIC,QAAO,CAAA,CAAA;IAC/F,WAAW,KAAKX,MAAMK,IAAIC,WAAW,OAAO;AACxCJ,aAAcK,OAAOE,YAAYF,OAAOI,QAAe,MAAMC,SAAS,KAAKZ,KAAK,CAAA,CAAA;IACpF;AAEA,WAAOE;EACX;;;;EAKA,MAAMW,MAAoBC,KAAaC,cAA8B;AACjE,UAAMb,OAAO,MAAM,KAAKD,IAAG;AAC3B,WAAQC,KAAKY,GAAAA,KAAQC;EACzB;;;;EAKAC,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;AACvC,WAAK,MAAK;IACd;EACJ;AACJ;;;ACpMO,SAAS0B,YACZC,UAAsB;AAEtB,SAAO,IAAIC,MAAMD,UAAU;IACvBE,IAAKC,QAAQC,MAAMC,UAAQ;AACvB,YAAMC,QAAQC,QAAQL,IAAIC,QAAQC,MAAMC,QAAAA;AACxC,UAAI,OAAOC,UAAU,YAAY;AAE7B,YAAIF,SAAS,UAAUA,SAAS,cAAc;AAC1C,iBAAO,IAAII,SAAAA;AACP,kBAAMC,SAASH,MAAMI,MAAMP,QAAQK,IAAAA;AAEnCG,yBAAa,MAAMR,OAAO,WAAA,EAAY,CAAA;AACtC,mBAAOM;UACX;QACJ,WAAWL,SAAS,QAAQ;AACxB,iBAAO,IAAII,SAAAA;AAEPL,mBAAO,YAAA,IAAgB;AAEvB,mBAAOG,MAAMI,MAAMP,QAAQK,IAAAA;UAC/B;QACJ;MACJ;AACA,aAAOF;IACX;EACJ,CAAA;AACJ;AA3BgBP;","names":["Middleware","getQuery","getRouterParams","readBody","safeDot","Request","event","all","data","getRouterParams","getQuery","req","method","Object","assign","fromEntries","formData","entries","readBody","input","key","defaultValue","params","query","getEvent","safeDot","safeDot","html","redirect","Response","event","statusCode","headers","setStatusCode","code","res","status","setHeader","name","value","html","content","applyHeaders","json","data","text","redirect","url","Object","entries","forEach","key","set","getEvent","safeDot","LogRequests","Middleware","handle","request","next","url","getEvent","console","log","pathname","search","H3","serve","ServiceProvider","HttpServiceProvider","ServiceProvider","register","app","singleton","H3","serve","JsonResource","request","response","resource","body","data","shouldSend","responseSent","event","rsc","req","res","key","Object","keys","defineProperty","enumerable","configurable","get","set","value","json","status","Array","isArray","pagination","meta","additional","send","code","context","this","checkSend","ApiResource","instance","Proxy","get","target","prop","receiver","value","Reflect","args","result","apply","setImmediate"]}
package/package.json ADDED
@@ -0,0 +1,28 @@
1
+ {
2
+ "name": "@h3ravel/http",
3
+ "version": "0.1.0",
4
+ "description": "HTTP kernel, middleware pipeline, request/response classes for H3ravel.",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "publishConfig": {
9
+ "access": "public"
10
+ },
11
+ "dependencies": {
12
+ "srvx": "^0.8.2",
13
+ "h3": "^2.0.0-beta.1",
14
+ "@h3ravel/core": "0.1.0",
15
+ "@h3ravel/support": "0.1.0"
16
+ },
17
+ "devDependencies": {
18
+ "typescript": "^5.4.0"
19
+ },
20
+ "scripts": {
21
+ "barrel": "barrelsby --directory src --delete --singleQuotes",
22
+ "build": "tsup",
23
+ "dev": "tsx watch src/index.ts",
24
+ "start": "node dist/index.js",
25
+ "lint": "eslint . --ext .ts",
26
+ "test": "vitest"
27
+ }
28
+ }
@@ -0,0 +1,13 @@
1
+ import { HttpContext } from "./HttpContract"
2
+
3
+ /**
4
+ * Defines the contract for all controllers.
5
+ * Any controller implementing this must define these methods.
6
+ */
7
+ export interface IController {
8
+ show (ctx: HttpContext): any
9
+ index (ctx: HttpContext): any
10
+ store (ctx: HttpContext): any
11
+ update (ctx: HttpContext): any
12
+ destroy (ctx: HttpContext): any
13
+ }
@@ -0,0 +1,7 @@
1
+ import { Request } from "../Request"
2
+ import { Response } from "../Response"
3
+
4
+ export interface HttpContext {
5
+ request: Request
6
+ response: Response
7
+ }
@@ -0,0 +1,9 @@
1
+ import { HttpContext, Middleware } from '@h3ravel/http'
2
+
3
+ export class LogRequests extends Middleware {
4
+ async handle ({ request }: HttpContext, next: () => Promise<unknown>): Promise<unknown> {
5
+ const url = request.getEvent('url')
6
+ console.log(`[${request.getEvent('method')}] ${url.pathname + url.search}`)
7
+ return next()
8
+ }
9
+ }
@@ -0,0 +1,5 @@
1
+ import { HttpContext } from './Contracts/HttpContract';
2
+
3
+ export abstract class Middleware {
4
+ abstract handle (context: HttpContext, next: () => Promise<unknown>): Promise<unknown>
5
+ }
@@ -0,0 +1,22 @@
1
+ import { H3, serve } from 'h3'
2
+
3
+ import { ServiceProvider } from '@h3ravel/core'
4
+
5
+ /**
6
+ * Sets up HTTP kernel and request lifecycle.
7
+ *
8
+ * Register Request, Response, and Middleware classes.
9
+ * Configure global middleware stack.
10
+ * Boot HTTP kernel.
11
+ *
12
+ * Auto-Registered
13
+ */
14
+ export class HttpServiceProvider extends ServiceProvider {
15
+ register () {
16
+ this.app.singleton('http.app', () => {
17
+ return new H3()
18
+ })
19
+
20
+ this.app.singleton('http.serve', () => serve)
21
+ }
22
+ }