manicanldes-backend/src/catalog/group.store.ts

50 lines
1.6 KiB
TypeScript

import { Injectable } from '@nestjs/common';
import { DatabaseService } from '../database/database.service';
import { AccessStore } from '../identity/access.store';
import { recordAudit } from '../identity/audit';
import type { Principal } from '../identity/identity.types';
import type { PageInput } from '../identity/identity.schemas';
import { AppError } from '../common/errors/app-error';
import type { GroupInput } from './catalog.schemas';
@Injectable()
export class GroupStore {
constructor(
private readonly db: DatabaseService,
private readonly access: AccessStore,
) {}
list(actor: Principal, page: PageInput) {
return this.db.catalogGroup.findMany({
where: { organizationId: actor.organizationId },
orderBy: { id: 'asc' },
take: page.limit,
skip: page.offset,
});
}
save(actor: Principal, input: GroupInput, id?: string) {
return this.access.mutate(actor, 'catalog.manage', async (tx) => {
if (
id &&
!(await tx.catalogGroup.findFirst({
where: { id, organizationId: actor.organizationId },
}))
) {
throw new AppError('GROUP_NOT_FOUND');
}
const group = id
? await tx.catalogGroup.update({ where: { id }, data: input })
: await tx.catalogGroup.create({
data: { ...input, organizationId: actor.organizationId },
});
await recordAudit(
tx,
actor.organizationId,
actor.userId,
id ? 'catalog_group.updated' : 'catalog_group.created',
group.id,
);
return group;
});
}
}