server/packages/sdk/inbox-processor.ts
Jesse Wierzbinski 709e1c6087
Some checks failed
CodeQL Scan / Analyze (push) Failing after 0s
Deploy Docs to GitHub Pages / build (push) Failing after 0s
Deploy Docs to GitHub Pages / Deploy (push) Has been skipped
Nix Build / check (push) Failing after 0s
Test Publish / build (client) (push) Failing after 0s
Test Publish / build (sdk) (push) Failing after 0s
Build Docker Images / lint (push) Has been cancelled
Build Docker Images / check (push) Has been cancelled
Build Docker Images / tests (push) Has been cancelled
Build Docker Images / detect-circular (push) Has been cancelled
Mirror to Codeberg / Mirror (push) Has been cancelled
Build Docker Images / build (server, Dockerfile, ${{ github.repository_owner }}/server) (push) Has been cancelled
Build Docker Images / build (worker, Worker.Dockerfile, ${{ github.repository_owner }}/worker) (push) Has been cancelled
refactor(federation): Make references always have domains
2026-04-03 13:34:19 +02:00

59 lines
1.7 KiB
TypeScript

import type { Entity } from "./entities/entity.ts";
import type { JSONObject } from "./types.ts";
type EntitySorterHandlers = Map<
typeof Entity,
(entity: Entity) => MaybePromise<void>
>;
type MaybePromise<T> = T | Promise<T>;
/**
* @example
* const jsonData = { ... };
* const processor = await new EntitySorter(jsonData)
* .on(User, async (user) => {
* // Do something with the user
* })
* .sort();
*/
export class EntitySorter {
private readonly handlers: EntitySorterHandlers = new Map();
public constructor(
private readonly jsonData: JSONObject,
public instanceDomain: string,
) {}
public on<T extends typeof Entity>(
entity: T,
handler: (entity: InstanceType<T>) => MaybePromise<void>,
): EntitySorter {
this.handlers.set(
entity,
handler as (entity: Entity) => MaybePromise<void>,
);
return this;
}
/**
* Sorts the entity based on the provided JSON data.
* @param {() => MaybePromise<void>} defaultHandler - A default handler to call if no specific handler is found.
* @throws {Error} If no handler is found for the entity type
*/
public async sort(
defaultHandler?: () => MaybePromise<void>,
): Promise<void> {
const type = this.jsonData.type;
const entity = this.handlers.keys().find((key) => key.name === type);
if (entity) {
await this.handlers.get(entity)?.(
await entity.fromJSON(this.jsonData, this.instanceDomain),
);
} else {
await defaultHandler?.();
}
}
}
export type { JSONObject } from "./types.ts";