Skip to content

Commit

Permalink
feat(core): normalize IDs to string inside default cache implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
paul-thebaud committed Jul 3, 2024
1 parent d4c86d8 commit 4de6033
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 6 deletions.
1 change: 1 addition & 0 deletions packages/core/src/blueprints/makeCache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ type CacheConfig = Partial<RefsCacheConfig>;
export default (config: CacheConfig = {}) => ({
cache: makeRefsCacheWith({
manager: weakRefManager,
normalizeId: (id) => String(id),
...config,
}),
});
10 changes: 6 additions & 4 deletions packages/core/src/cache/makeRefsCacheWith.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,21 +11,23 @@ import { makeIdentifiersMap } from '@foscia/shared';
export default (config: RefsCacheConfig): RefsCache => {
const instances = makeIdentifiersMap<string, ModelIdType, unknown>();

const forget = async (type: string, id: ModelIdType) => instances.forget(type, id);
const normalizeId = config.normalizeId ?? ((v) => v);

const forget = async (type: string, id: ModelIdType) => instances.forget(type, normalizeId(id));

const forgetAll = async (type: string) => instances.forgetAll(type);

const clear = async () => instances.clear();

const find = async (type: string, id: ModelIdType) => {
const ref = instances.find(type, id);
const ref = instances.find(type, normalizeId(id));
if (!ref) {
return null;
}

const instance = await config.manager.value(ref);
if (!instance) {
await forget(type, id);
await forget(type, normalizeId(id));

return null;
}
Expand All @@ -34,7 +36,7 @@ export default (config: RefsCacheConfig): RefsCache => {
};

const put = async (type: string, id: ModelIdType, instance: ModelInstance) => {
instances.put(type, id, await config.manager.ref(instance));
instances.put(type, normalizeId(id), await config.manager.ref(instance));
};

return {
Expand Down
5 changes: 3 additions & 2 deletions packages/core/src/cache/types.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { ModelInstance } from '@foscia/core/model/types';
import { ModelIdType, ModelInstance } from '@foscia/core/model/types';
import { CacheI } from '@foscia/core/types';
import { Awaitable } from '@foscia/shared';
import { Awaitable, Optional, Transformer } from '@foscia/shared';

export type RefManager<R> = {
ref(instance: ModelInstance): Awaitable<R>;
Expand All @@ -9,6 +9,7 @@ export type RefManager<R> = {

export type RefsCacheConfig<R = unknown> = {
manager: RefManager<R>;
normalizeId?: Optional<Transformer<ModelIdType>>;
};

export interface RefsCache extends CacheI {
Expand Down

0 comments on commit 4de6033

Please sign in to comment.