Skip to content

Commit

Permalink
Implement model registry declarations
Browse files Browse the repository at this point in the history
  • Loading branch information
NoelDeMartin committed Mar 1, 2024
1 parent c39e106 commit ce96ff9
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 2 deletions.
38 changes: 38 additions & 0 deletions src/models/index.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { tt } from '@noeldemartin/utils';
import type { Equals, Expect } from '@noeldemartin/utils';

import User from '@/testing/stubs/User';
import Post from '@/testing/stubs/Post';
import City from '@/testing/stubs/City';
import type { ModelConstructor } from '@/models/inference';

import { bootModels, requireBootedModel } from './index';

declare module './index' {
interface ModelsRegistry {
User: typeof User;
}
}

describe('Models helpers', () => {

it('registers booted models', () => {
bootModels({ User, Post, City });

const user = requireBootedModel('User');
const post = requireBootedModel('Post');
const city = requireBootedModel<typeof City>('City');

expect(user).toBe(User);
expect(post).toBe(Post);
expect(city).toBe(City);

tt<
Expect<Equals<typeof user, typeof User>> |
Expect<Equals<typeof post, ModelConstructor>> |
Expect<Equals<typeof city, typeof City>> |
true
>();
});

});
8 changes: 6 additions & 2 deletions src/models/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,12 @@ export type { TimestampFieldValue, TimestampsDefinition } from './timestamps';

const bootedModels: Map<string, typeof Model> = new Map;

export function requireBootedModel<T extends ModelConstructor<Model> = ModelConstructor<Model>>(name: string): T {
return bootedModels.get(name) as T
export interface ModelsRegistry {}

export function requireBootedModel<T extends keyof ModelsRegistry>(name: T): ModelsRegistry[T];
export function requireBootedModel<T extends ModelConstructor<Model> = ModelConstructor<Model>>(name: string): T;
export function requireBootedModel(name: string): typeof Model {
return bootedModels.get(name)
?? fail(SoukaiError, `Could not find Model with name '${name}', are you sure it's booted?`);
}

Expand Down

0 comments on commit ce96ff9

Please sign in to comment.