Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(file-resolver): add classes support for files #77

Merged
merged 3 commits into from
Jan 25, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
153 changes: 88 additions & 65 deletions examples/typescript/pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

30 changes: 30 additions & 0 deletions examples/typescript/src/api/classes/[[...slug]].ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import type { UUID } from 'node:crypto';
import { randomUUID } from 'node:crypto';
import { parseJson } from '../../utils/server.utils';
import type { IncomingMessage, ServerResponse } from 'node:http';

const db: Record<UUID, Record<string, string>> = {};

interface Params {
slug: UUID[]
}

export default class Resource {
get(_: IncomingMessage, res: ServerResponse, { slug: [id] }: Params) {
if (!db[id]) {
res.statusCode = 404;
res.end('Not found');
}

res.end(JSON.stringify(db[id]));
}

async post(req: IncomingMessage, res: ServerResponse) {
const userToCreate = await parseJson(req);
const id = randomUUID();
db[id] = { ...userToCreate, id };

res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(db[id]));
}
};
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -74,5 +74,6 @@
"ts-node-dev": "2.0.0",
"typescript": "5.0.4",
"vitest": "0.31.0"
}
},
"packageManager": "pnpm@9.2.0+sha512.98a80fd11c2e7096747762304106432b3ddc67dcf54b5a8c01c93f68a2cd5e05e6821849522a06fb76284d41a2660d5e334f2ee3bbf29183bf2e739b1dafa771"
}
6 changes: 5 additions & 1 deletion src/components/file-route-resolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { MiddlewareHandler } from './route-handler/middleware-handler';
import { isCommonJs } from '../utils/env.utils';
import { validateFileFormat } from '../validations/validations';

import { isClass } from '../utils/common.utils';
import type { ParamExtractor } from './dynamic-routes/common/route-params-parser';
import type { Dirent } from 'node:fs';

Expand Down Expand Up @@ -192,7 +193,10 @@ export class FileRouteResolver {

const handler = await import(fullPath)
.then((module) => validateFileFormat(fullPath, module))
.then((module) => module.default);
.then((module) => module.default)
.then((FunctionOrClass) =>
isClass(FunctionOrClass) ? new FunctionOrClass() : FunctionOrClass
);

const initialRoute = routePath.replace(
FileRouteResolver.fileExtensionPattern,
Expand Down
6 changes: 6 additions & 0 deletions src/utils/common.utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,9 @@ export function getType(something: unknown): string {

return typeof something;
}

export function isClass(maybeClass: unknown): boolean {
return (
typeof maybeClass === 'function' && /^class\s/.test(maybeClass.toString())
);
}
6 changes: 5 additions & 1 deletion src/utils/object.utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,11 @@ export function filterValues<V>(
export function isRecordWith<T>(
maybeObject: unknown
): maybeObject is Record<string, T> {
return maybeObject != null && maybeObject.constructor.name === 'Object';
return (
typeof maybeObject === 'object' &&
!Array.isArray(maybeObject) &&
maybeObject !== null
);
}

export function isFunction(
Expand Down
8 changes: 8 additions & 0 deletions tests/api-classes/[id]/endpoint-with-instance.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { createTestRequestHandler } from '../../test-utils';

const resource = class Resource {
get = createTestRequestHandler(__filename);
post = createTestRequestHandler(__filename);
};

export default resource;
6 changes: 6 additions & 0 deletions tests/api-classes/[id]/endpoint.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { createTestRequestHandler } from '../../test-utils';

export default class Resource {
get = createTestRequestHandler(__filename);
post = createTestRequestHandler(__filename);
}
40 changes: 38 additions & 2 deletions tests/request-handler.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@ import {
expectAfterInit
} from './test-utils';
import { initFileRouter } from '../src';
import { describe, expect, it, beforeAll, vi, afterEach } from 'vitest';
import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
import type { FileRouterRequestHandler } from '../src';

import type { IncomingMessage } from 'node:http';
import type { FileRouterRequestHandler } from '../src';

const currentCwd = process.cwd();
vi.mock('process', () => ({
Expand Down Expand Up @@ -647,4 +647,40 @@ describe('RequestHandler', () => {
expect(result).toEqual('new-data');
});
});

describe('#Classes', () => {
const baseDir = `${process.cwd()}/tests/api-classes`;

it('should invoke http-method based handlers from class-based file', async () => {
const requestHandler = await initFileRouter({ baseDir });
const run = createTestRequestRunner(requestHandler);

await run('/3/endpoint', 'post').then(({ req, routeParams }) => {
expect(routeParams).toEqual({ id: '3' });
expect(req?.method).toBe('post');
});
await run('/3/endpoint', 'get').then(({ req, routeParams }) => {
expect(routeParams).toEqual({ id: '3' });
expect(req?.method).toBe('get');
});
});

it('should invoke http-method based handlers from instance of class based file', async () => {
const requestHandler = await initFileRouter({ baseDir });
const run = createTestRequestRunner(requestHandler);

await run('/3/endpoint-with-instance', 'post').then(
({ req, routeParams }) => {
expect(routeParams).toEqual({ id: '3' });
expect(req?.method).toBe('post');
}
);
await run('/3/endpoint-with-instance', 'get').then(
({ req, routeParams }) => {
expect(routeParams).toEqual({ id: '3' });
expect(req?.method).toBe('get');
}
);
});
});
});
Loading