All files / lib role-cache.ts

100% Statements 11/11
100% Branches 10/10
100% Functions 9/9
100% Lines 10/10

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 64 65 66 67 68 69 70 71 72                                      4x 4x                   6x   6x                 5x 5x                     8x   8x       8x                   26x    
// Role caching layer for user tenant roles
// Reduces 1-2 D1 queries per protected request to 0 on cache hit
import type { DualCache } from "./cache";
import { CACHE_TTL } from "./cache";
import type { UserTenantRole } from "../db/schema";
 
type RolesDalLike = {
	findByUserId(userId: string): Promise<UserTenantRole[]>;
};
 
/**
 * Get all roles for a user from cache or DB.
 * Fetches ALL roles in 1 query and caches the result.
 */
export async function getCachedUserRoles(
	cache: DualCache,
	rolesDal: RolesDalLike,
	userId: string,
): Promise<UserTenantRole[]> {
	const cacheKey = `roles:${userId}`;
	return cache.getOrSet(cacheKey, () => rolesDal.findByUserId(userId), {
		l1Ttl: CACHE_TTL.ROLES_L1,
		l2Ttl: CACHE_TTL.ROLES_L2,
	});
}
 
/**
 * Check if user is a platform admin from cached roles.
 */
export function isPlatformAdminFromRoles(roles: UserTenantRole[]): boolean {
	return roles.some(
		(r) =>
			r.tenantType === "platform" &&
			(r.role === "admin" || r.role === "super_admin"),
	);
}
 
/**
 * Check if user is a super admin from cached roles.
 */
export function isSuperAdminFromRoles(roles: UserTenantRole[]): boolean {
	return roles.some(
		(r) => r.tenantType === "platform" && r.role === "super_admin",
	);
}
 
/**
 * Get pro role for a user from cached roles.
 */
export function getProRoleFromRoles(
	roles: UserTenantRole[],
	proId: string,
): string | null {
	const role = roles.find(
		(r) =>
			r.tenantType === "pro" &&
			r.tenantId === proId &&
			r.isActive !== false,
	);
	return role?.role ?? null;
}
 
/**
 * Invalidate cached roles for a user. Call after any role mutation.
 */
export async function invalidateUserRoles(
	cache: DualCache,
	userId: string,
): Promise<void> {
	await cache.delete(`roles:${userId}`);
}