28 lines
1.1 KiB
TypeScript
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));
|
|
}
|