Files
stats/packages/db/src/services/access.service.ts
Carl-Gerhard Lindesvärd f454449365 fix: read-after-write issues (#215)
* fix: read-after-write issues

* fix: coderabbit comments

* fix: clear cache on invite

* fix: use primary after a read
2025-10-31 09:56:07 +01:00

97 lines
1.9 KiB
TypeScript

import { cacheable } from '@openpanel/redis';
import { db } from '../prisma-client';
import { getProjectById } from './project.service';
export const getProjectAccess = cacheable(
'getProjectAccess',
async ({
userId,
projectId,
}: {
userId: string;
projectId: string;
}) => {
try {
// Check if user has access to the project
const project = await getProjectById(projectId);
if (!project?.organizationId) {
return false;
}
const [projectAccess, member] = await Promise.all([
db.$primary().projectAccess.findMany({
where: {
userId,
organizationId: project.organizationId,
},
}),
db.$primary().member.findFirst({
where: {
organizationId: project.organizationId,
userId,
},
}),
]);
if (projectAccess.length === 0 && member) {
return true;
}
return projectAccess.find((item) => item.projectId === projectId);
} catch (err) {
return false;
}
},
60 * 5,
);
export const getOrganizationAccess = cacheable(
'getOrganizationAccess',
async ({
userId,
organizationId,
}: {
userId: string;
organizationId: string;
}) => {
return db.$primary().member.findFirst({
where: {
userId,
organizationId,
},
});
},
60 * 5,
);
export async function getClientAccess({
userId,
clientId,
}: {
userId: string;
clientId: string;
}) {
const client = await db.client.findFirst({
where: {
id: clientId,
},
});
if (!client) {
return false;
}
if (client.projectId) {
return getProjectAccess({ userId, projectId: client.projectId });
}
if (client.organizationId) {
return getOrganizationAccess({
userId,
organizationId: client.organizationId,
});
}
return false;
}