Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/apps/worker/src/rls-context.ts
T

28 lines
1.1 KiB
TypeScript

import { runWithRlsContext, type RlsIdentityContext } from "@hivegrid/db/rls-context.server";
import type { QueueName, TypedProcessor } from "@hivegrid/queue";
function readNonEmptyString(value: unknown): string | undefined {
if (typeof value !== "string") return undefined;
const normalized = value.trim();
return normalized.length > 0 ? normalized : undefined;
}
export function resolveWorkerRlsIdentity(payload: unknown): RlsIdentityContext | null {
if (!payload || typeof payload !== "object" || Array.isArray(payload)) return null;
const record = payload as Record<string, unknown>;
const tenantId = readNonEmptyString(record.tenantId);
if (!tenantId) return null;
return { tenantId };
}
export function runWorkerPayloadWithRlsContext<T>(payload: unknown, operation: () => T): T {
const identity = resolveWorkerRlsIdentity(payload);
return identity ? runWithRlsContext(identity, operation) : operation();
}
export function wrapProcessorWithRlsContext<Name extends QueueName>(processor: TypedProcessor<Name>): TypedProcessor<Name> {
return async (job) => runWorkerPayloadWithRlsContext(job.data, () => processor(job));
}