Files
HiveGrid-Wireframes/hivegrid-cloud/apps/web/app/utils/db/entities/rowRelationships.db.server.ts
T

92 lines
2.4 KiB
TypeScript

import { db } from "~/utils/db.server";
import { createScopedLogger } from "~/utils/logger.server";
const rowRelationshipsLogger = createScopedLogger("db.entities.rowRelationships");
type RowRelationshipTenantScope = {
tenantId: string | null;
};
function scopedRowRelationshipWhere(scope: RowRelationshipTenantScope) {
return {
parent: { deletedAt: null, tenantId: scope.tenantId },
child: { deletedAt: null, tenantId: scope.tenantId },
};
}
export async function getRowRelationship(id: string, scope: RowRelationshipTenantScope) {
return await db.rowRelationship.findFirst({
where: { id, ...scopedRowRelationshipWhere(scope) },
include: {
relationship: true,
},
});
}
export async function getRowsRelationship({ parentId, childId, tenantId }: { parentId: string; childId: string; tenantId: string | null }) {
return await db.rowRelationship.findFirst({
where: { parentId, childId, ...scopedRowRelationshipWhere({ tenantId }) },
});
}
export async function createRowRelationship({
parentId,
childId,
relationshipId,
metadata,
tenantId,
}: {
parentId: string;
childId: string;
relationshipId: string;
metadata: string | null;
tenantId: string | null;
}) {
const [parent, child] = await Promise.all([
db.row.findFirst({ where: { id: parentId, deletedAt: null, tenantId }, select: { id: true } }),
db.row.findFirst({ where: { id: childId, deletedAt: null, tenantId }, select: { id: true } }),
]);
if (!parent || !child) {
return undefined;
}
return await db.rowRelationship
.create({
data: {
parentId,
childId,
relationshipId,
metadata,
},
})
.catch((e) => {
rowRelationshipsLogger.error({ err: e }, "Error creating row relationship");
});
}
export async function deleteRowRelationship({ parentId, childId, tenantId }: { parentId: string; childId: string; tenantId: string | null }) {
return await db.rowRelationship.deleteMany({
where: {
parentId,
childId,
...scopedRowRelationshipWhere({ tenantId }),
},
});
}
export async function deleteRowRelationshipById(id: string, scope: RowRelationshipTenantScope) {
const item = await db.rowRelationship.findFirst({
where: { id, ...scopedRowRelationshipWhere(scope) },
select: { id: true },
});
if (!item) {
return null;
}
return await db.rowRelationship.delete({
where: {
id: item.id,
},
});
}