All files / src/business org.ts

0% Statements 0/47
100% Branches 1/1
100% Functions 1/1
0% Lines 0/47

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63                                                                                                                             
/**
 * Organization Membership Logic
 *
 * Centralized business logic for user-organization relationships.
 */
 
import { logger } from "@snapback/infrastructure";
import { db } from "@snapback/platform";
import { member } from "@snapback/platform/db/schema/postgres";
import { and, eq } from "drizzle-orm";
 
/**
 * Get all organization IDs for a user
 * Used for Row-Level Security (RLS) enforcement
 */
export async function getUserOrgIds(userId: string): Promise<string[]> {
	if (!db) {
		logger.warn("Database not available for org lookup");
		return [];
	}
	try {
		const memberships = await db
			.select({ orgId: member.organizationId })
			.from(member)
			.where(eq(member.userId, userId));
		return memberships.map((m: { orgId: string }) => m.orgId);
	} catch (error) {
		logger.error("Failed to get user org IDs", {
			userId,
			error: error instanceof Error ? error.message : String(error),
		});
		return [];
	}
}
 
/**
 * Check if user is member of a specific organization
 */
export async function checkOrgMembership(userId: string, orgId: string) {
	if (!db) {
		return null;
	}
	try {
		return await db
			.select({
				userId: member.userId,
				organizationId: member.organizationId,
				role: member.role,
			})
			.from(member)
			.where(and(eq(member.userId, userId), eq(member.organizationId, orgId)))
			.limit(1)
			.then((rows: { userId: string; organizationId: string; role: string }[]) => rows[0] || null);
	} catch (error) {
		logger.error("Failed to check org membership", {
			userId,
			orgId,
			error: error instanceof Error ? error.message : String(error),
		});
		return null;
	}
}