@kaito-http/core 3.0.1 → 3.0.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.
package/src/handler.ts DELETED
@@ -1,96 +0,0 @@
1
- import type {KaitoError} from './error.ts';
2
- import type {KaitoRequest} from './request.ts';
3
- import type {Router} from './router/router.ts';
4
- import type {GetContext} from './util.ts';
5
-
6
- export type HandlerConfig<ContextFrom> = {
7
- /**
8
- * The root router to mount on this handler.
9
- */
10
- router: Router<ContextFrom, unknown, any>;
11
-
12
- /**
13
- * A function that is called to get the context for a request.
14
- *
15
- * This is useful for things like authentication, to pass in a database connection, etc.
16
- *
17
- * It's fine for this function to throw; if it does, the error is passed to the `onError` function.
18
- */
19
- getContext: GetContext<ContextFrom>;
20
-
21
- /**
22
- * A function that is called when an error occurs inside a route handler.
23
- *
24
- * The result of this function is used to determine the response status and message, and is
25
- * always sent to the client. You could include logic to check for production vs development
26
- * environments here, and this would also be a good place to include error tracking
27
- * like Sentry or Rollbar.
28
- *
29
- * @param arg - The error thrown, and the KaitoRequest instance
30
- * @returns A KaitoError or an object with a status and message
31
- */
32
- onError: (arg: {error: Error; req: KaitoRequest}) => Promise<KaitoError | {status: number; message: string}>;
33
-
34
- /**
35
- * A function that is called before every request. Most useful for bailing out early in the case of an OPTIONS request.
36
- *
37
- * @example
38
- * ```ts
39
- * before: async req => {
40
- * if (req.method === 'OPTIONS') {
41
- * return new Response(null, {status: 204});
42
- * }
43
- * }
44
- * ```
45
- */
46
- before?: (req: Request) => Promise<Response | void | undefined>;
47
-
48
- /**
49
- * Transforms the response before it is sent to the client. Very useful for settings headers like CORS.
50
- *
51
- * You can also return a new response in this function, or just mutate the current one.
52
- *
53
- * This function WILL receive the result of `.before()` if you return a response from it. This means
54
- * you only need to define headers in a single place.
55
- *
56
- * @example
57
- * ```ts
58
- * transform: async (req, res) => {
59
- * res.headers.set('Access-Control-Allow-Origin', 'http://localhost:3000');
60
- * res.headers.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
61
- * res.headers.set('Access-Control-Allow-Headers', 'Content-Type, Authorization');
62
- * res.headers.set('Access-Control-Max-Age', '86400');
63
- * res.headers.set('Access-Control-Allow-Credentials', 'true');
64
- * }
65
- * ```
66
- */
67
- transform?: (req: Request, res: Response) => Promise<Response | void | undefined>;
68
- };
69
-
70
- export function createKaitoHandler<Context>(config: HandlerConfig<Context>) {
71
- const handle = config.router.freeze(config);
72
-
73
- return async (request: Request): Promise<Response> => {
74
- if (config.before) {
75
- const result = await config.before(request);
76
-
77
- if (result instanceof Response) {
78
- if (config.transform) {
79
- const result2 = await config.transform(request, result);
80
- if (result2 instanceof Response) return result;
81
- }
82
-
83
- return result;
84
- }
85
- }
86
-
87
- const response = await handle(request);
88
-
89
- if (config.transform) {
90
- const result = await config.transform(request, response);
91
- if (result instanceof Response) return result;
92
- }
93
-
94
- return response;
95
- };
96
- }
package/src/head.ts DELETED
@@ -1,83 +0,0 @@
1
- import type {APIResponse} from './util.ts';
2
-
3
- /**
4
- * This class is merely a wrapper around a `Headers` object and a status code.
5
- * It's used while the router is executing a route to store any mutations to the status
6
- * code or headers that the developer may want to make.
7
- *
8
- * This exists because there's otherwise no way to indicate back to Kaito that
9
- * the developer wants to change the status code or headers.
10
- *
11
- * @example
12
- * ```ts
13
- * const response = new KaitoHead();
14
- *
15
- * response.status(200);
16
- * response.headers.set('Content-Type', 'application/json');
17
- *
18
- * console.log(response.headers); // Headers {'content-type': 'application/json'}
19
- * ```
20
- */
21
- export class KaitoHead {
22
- private _headers: Headers | null;
23
- private _status: number;
24
-
25
- public constructor() {
26
- this._headers = null;
27
- this._status = 200;
28
- }
29
-
30
- public get headers() {
31
- if (this._headers === null) {
32
- this._headers = new Headers();
33
- }
34
-
35
- return this._headers;
36
- }
37
-
38
- /**
39
- * Gets the status code of this KaitoHead instance
40
- * @returns The status code
41
- */
42
- public status(): number;
43
-
44
- /**
45
- * Sets the status code of this KaitoHead instance
46
- * @param status The status code to set
47
- * @returns This KaitoHead instance
48
- */
49
- public status(status: number): this;
50
-
51
- public status(status?: number) {
52
- if (status === undefined) {
53
- return this._status;
54
- }
55
-
56
- this._status = status;
57
- return this;
58
- }
59
-
60
- /**
61
- * Turn this KaitoHead instance into a Response instance
62
- * @param body The Kaito JSON format to be sent as the response body
63
- * @returns A Response instance, ready to be sent
64
- */
65
- public toResponse<T>(body: APIResponse<T>): Response {
66
- const init: ResponseInit = {
67
- status: this._status,
68
- };
69
-
70
- if (this._headers) {
71
- init.headers = this._headers;
72
- }
73
-
74
- return Response.json(body, init);
75
- }
76
-
77
- /**
78
- * Whether this KaitoHead instance has been touched/modified
79
- */
80
- public get touched() {
81
- return this._status !== 200 || this._headers !== null;
82
- }
83
- }
package/src/index.ts DELETED
@@ -1,7 +0,0 @@
1
- export * from './error.ts';
2
- export * from './handler.ts';
3
- export * from './request.ts';
4
- export * from './route.ts';
5
- export * from './router/router.ts';
6
- export type {KaitoMethod} from './router/types.ts';
7
- export * from './util.ts';
package/src/request.ts DELETED
@@ -1,47 +0,0 @@
1
- export class KaitoRequest {
2
- public readonly url: URL;
3
-
4
- private readonly _request: Request;
5
-
6
- public constructor(url: URL, request: Request) {
7
- this._request = request;
8
- this.url = url;
9
- }
10
-
11
- public get headers() {
12
- return this._request.headers;
13
- }
14
-
15
- public get method() {
16
- return this._request.method;
17
- }
18
-
19
- public async arrayBuffer(): Promise<ArrayBuffer> {
20
- return this._request.arrayBuffer();
21
- }
22
-
23
- public async blob(): Promise<Blob> {
24
- return this._request.blob();
25
- }
26
-
27
- public async formData(): Promise<FormData> {
28
- return this._request.formData();
29
- }
30
-
31
- public async bytes(): Promise<Uint8Array> {
32
- const buffer = await this.arrayBuffer();
33
- return new Uint8Array(buffer);
34
- }
35
-
36
- public async json(): Promise<unknown> {
37
- return this._request.json();
38
- }
39
-
40
- public async text(): Promise<string> {
41
- return this._request.text();
42
- }
43
-
44
- public get request() {
45
- return this._request;
46
- }
47
- }
package/src/route.ts DELETED
@@ -1,52 +0,0 @@
1
- import type {KaitoMethod} from './router/types.ts';
2
- import type {ExtractRouteParams, InferParsable, Parsable} from './util.ts';
3
-
4
- export type RouteArgument<Path extends string, Context, QueryOutput, BodyOutput> = {
5
- ctx: Context;
6
- body: BodyOutput;
7
- query: QueryOutput;
8
- params: ExtractRouteParams<Path>;
9
- };
10
-
11
- export type AnyQueryDefinition = Record<string, Parsable<any, string | undefined>>;
12
-
13
- export type Through<From, To> = (context: From) => Promise<To>;
14
-
15
- export type Route<
16
- // Router context
17
- ContextFrom,
18
- ContextTo,
19
- // Route information
20
- Result,
21
- Path extends string,
22
- Method extends KaitoMethod,
23
- // Schemas
24
- Query extends AnyQueryDefinition,
25
- Body extends Parsable,
26
- > = {
27
- through: Through<ContextFrom, ContextTo>;
28
- body?: Body;
29
- query?: Query;
30
- path: Path;
31
- method: Method;
32
- run(
33
- arg: RouteArgument<
34
- Path,
35
- ContextTo,
36
- {
37
- [Key in keyof Query]: InferParsable<Query[Key]>['output'];
38
- },
39
- InferParsable<Body>['output']
40
- >,
41
- ): Promise<Result>;
42
- };
43
-
44
- export type AnyRoute<ContextFrom = any, ContextTo = any> = Route<
45
- ContextFrom,
46
- ContextTo,
47
- any,
48
- any,
49
- any,
50
- AnyQueryDefinition,
51
- any
52
- >;
@@ -1,269 +0,0 @@
1
- import assert from 'node:assert';
2
- import {describe, it} from 'node:test';
3
- import {z} from 'zod';
4
- import {KaitoError} from '../error.ts';
5
- import {Router} from './router.ts';
6
-
7
- type Context = {
8
- userId: string;
9
- };
10
-
11
- type AuthContext = Context & {
12
- isAdmin: boolean;
13
- };
14
-
15
- describe('Router', () => {
16
- describe('create', () => {
17
- it('should create an empty router', () => {
18
- const router = Router.create<Context>();
19
- assert.strictEqual(router.routes.size, 0);
20
- });
21
- });
22
-
23
- describe('route handling', () => {
24
- it('should handle GET requests', async () => {
25
- const router = Router.create<Context>().get('/users', {
26
- run: async () => ({users: []}),
27
- });
28
-
29
- const handler = router.freeze({
30
- getContext: async () => ({userId: '123'}),
31
- onError: async () => ({status: 500, message: 'Internal Server Error'}),
32
- });
33
-
34
- const response = await handler(new Request('http://localhost/users', {method: 'GET'}));
35
- const data = await response.json();
36
-
37
- assert.strictEqual(response.status, 200);
38
- assert.deepStrictEqual(data, {
39
- success: true,
40
- data: {users: []},
41
- message: 'OK',
42
- });
43
- });
44
-
45
- it('should handle POST requests with body parsing', async () => {
46
- const router = Router.create<Context>().post('/users', {
47
- body: z.object({name: z.string()}),
48
- run: async ({body}) => ({id: '1', name: body.name}),
49
- });
50
-
51
- const handler = router.freeze({
52
- getContext: async () => ({userId: '123'}),
53
- onError: async () => ({status: 500, message: 'Internal Server Error'}),
54
- });
55
-
56
- const response = await handler(
57
- new Request('http://localhost/users', {
58
- method: 'POST',
59
- headers: {'Content-Type': 'application/json'},
60
- body: JSON.stringify({name: 'John'}),
61
- }),
62
- );
63
- const data = await response.json();
64
-
65
- assert.strictEqual(response.status, 200);
66
- assert.deepStrictEqual(data, {
67
- success: true,
68
- data: {id: '1', name: 'John'},
69
- message: 'OK',
70
- });
71
- });
72
-
73
- it('should handle URL parameters', async () => {
74
- const router = Router.create<Context>().get('/users/:id', {
75
- run: async ({params}) => ({id: params.id}),
76
- });
77
-
78
- const handler = router.freeze({
79
- getContext: async () => ({userId: '123'}),
80
- onError: async () => ({status: 500, message: 'Internal Server Error'}),
81
- });
82
-
83
- const response = await handler(new Request('http://localhost/users/456', {method: 'GET'}));
84
- const data = await response.json();
85
-
86
- assert.strictEqual(response.status, 200);
87
- assert.deepStrictEqual(data, {
88
- success: true,
89
- data: {id: '456'},
90
- message: 'OK',
91
- });
92
- });
93
-
94
- it('should handle query parameters', async () => {
95
- const router = Router.create<Context>().get('/search', {
96
- query: {
97
- q: z.string(),
98
- limit: z
99
- .string()
100
- .transform(value => Number(value))
101
- .pipe(z.number()),
102
- },
103
- run: async ({query}) => ({
104
- query: query.q,
105
- limit: query.limit,
106
- }),
107
- });
108
-
109
- const handler = router.freeze({
110
- getContext: async () => ({userId: '123'}),
111
- onError: async () => ({status: 500, message: 'Internal Server Error'}),
112
- });
113
-
114
- const response = await handler(new Request('http://localhost/search?q=test&limit=10', {method: 'GET'}));
115
- const data = await response.json();
116
-
117
- assert.strictEqual(response.status, 200);
118
- assert.deepStrictEqual(data, {
119
- success: true,
120
- data: {query: 'test', limit: 10},
121
- message: 'OK',
122
- });
123
- });
124
- });
125
-
126
- describe('middleware and context', () => {
127
- it('should transform context through middleware', async () => {
128
- const router = Router.create<Context>()
129
- .through(async ctx => ({
130
- ...ctx,
131
- isAdmin: ctx.userId === 'admin',
132
- }))
133
- .get('/admin', {
134
- run: async ({ctx}) => ({
135
- isAdmin: (ctx as AuthContext).isAdmin,
136
- }),
137
- });
138
-
139
- const handler = router.freeze({
140
- getContext: async () => ({userId: 'admin'}),
141
- onError: async () => ({status: 500, message: 'Internal Server Error'}),
142
- });
143
-
144
- const response = await handler(new Request('http://localhost/admin', {method: 'GET'}));
145
- const data = await response.json();
146
-
147
- assert.strictEqual(response.status, 200);
148
- assert.deepStrictEqual(data, {
149
- success: true,
150
- data: {isAdmin: true},
151
- message: 'OK',
152
- });
153
- });
154
- });
155
-
156
- describe('error handling', () => {
157
- it('should handle KaitoError with custom status', async () => {
158
- const router = Router.create<Context>().get('/error', {
159
- run: async () => {
160
- throw new KaitoError(403, 'Forbidden');
161
- },
162
- });
163
-
164
- const handler = router.freeze({
165
- getContext: async () => ({userId: '123'}),
166
- onError: async () => ({status: 500, message: 'Internal Server Error'}),
167
- });
168
-
169
- const response = await handler(new Request('http://localhost/error', {method: 'GET'}));
170
- const data = await response.json();
171
-
172
- assert.strictEqual(response.status, 403);
173
- assert.deepStrictEqual(data, {
174
- success: false,
175
- data: null,
176
- message: 'Forbidden',
177
- });
178
- });
179
-
180
- it('should handle generic errors with server error handler', async () => {
181
- const router = Router.create<Context>().get('/error', {
182
- run: async () => {
183
- throw new Error('Something went wrong');
184
- },
185
- });
186
-
187
- const handler = router.freeze({
188
- getContext: async () => ({userId: '123'}),
189
- onError: async () => ({status: 500, message: 'Custom Error Message'}),
190
- });
191
-
192
- const response = await handler(new Request('http://localhost/error', {method: 'GET'}));
193
- const data = await response.json();
194
-
195
- assert.strictEqual(response.status, 500);
196
- assert.deepStrictEqual(data, {
197
- success: false,
198
- data: null,
199
- message: 'Custom Error Message',
200
- });
201
- });
202
- });
203
-
204
- describe('router merging', () => {
205
- it('should merge routers with prefix', async () => {
206
- const userRouter = Router.create<Context>().get('/me', {
207
- run: async ({ctx}) => ({id: ctx.userId}),
208
- });
209
-
210
- const mainRouter = Router.create<Context>().merge('/api', userRouter);
211
-
212
- const handler = mainRouter.freeze({
213
- getContext: async () => ({userId: '123'}),
214
- onError: async () => ({status: 500, message: 'Internal Server Error'}),
215
- });
216
-
217
- const response = await handler(new Request('http://localhost/api/me', {method: 'GET'}));
218
- const data = await response.json();
219
-
220
- assert.strictEqual(response.status, 200);
221
- assert.deepStrictEqual(data, {
222
- success: true,
223
- data: {id: '123'},
224
- message: 'OK',
225
- });
226
- });
227
- });
228
-
229
- describe('404 handling', () => {
230
- it('should return 404 for non-existent routes', async () => {
231
- const router = Router.create<Context>();
232
- const handler = router.freeze({
233
- getContext: async () => ({userId: '123'}),
234
- onError: async () => ({status: 500, message: 'Internal Server Error'}),
235
- });
236
-
237
- const response = await handler(new Request('http://localhost/not-found', {method: 'GET'}));
238
- const data = await response.json();
239
-
240
- assert.strictEqual(response.status, 404);
241
- assert.deepStrictEqual(data, {
242
- success: false,
243
- data: null,
244
- message: 'Cannot GET /not-found',
245
- });
246
- });
247
-
248
- it('should return 404 for wrong method on existing path', async () => {
249
- const router = Router.create<Context>().get('/users', {
250
- run: async () => ({users: []}),
251
- });
252
-
253
- const handler = router.freeze({
254
- getContext: async () => ({userId: '123'}),
255
- onError: async () => ({status: 500, message: 'Internal Server Error'}),
256
- });
257
-
258
- const response = await handler(new Request('http://localhost/users', {method: 'POST'}));
259
- const data = await response.json();
260
-
261
- assert.strictEqual(response.status, 404);
262
- assert.deepStrictEqual(data, {
263
- success: false,
264
- data: null,
265
- message: 'Cannot POST /users',
266
- });
267
- });
268
- });
269
- });