manicanldes-backend/src/forum/forum-submission.store.ts

88 lines
2.7 KiB
TypeScript

import { Injectable } from '@nestjs/common';
import { AccessStore } from '../identity/access.store';
import { DatabaseService } from '../database/database.service';
import type { Principal } from '../identity/identity.types';
import type { PageInput } from '../identity/identity.schemas';
import { AppError } from '../common/errors/app-error';
import { assertReplay, commandHash } from '../common/idempotency';
import { recordAudit } from '../identity/audit';
import { forumInclude, ownForumView, requirePublicThread } from './forum-view';
import type { ForumReplyInput, ForumThreadInput } from './forum.schemas';
@Injectable()
export class ForumSubmissionStore {
constructor(
private readonly db: DatabaseService,
private readonly access: AccessStore,
) {}
async own(actor: Principal, page: PageInput) {
const posts = await this.db.forumPost.findMany({
where: { organizationId: actor.organizationId, userId: actor.userId },
include: forumInclude,
orderBy: [{ createdAt: 'desc' }, { id: 'desc' }],
skip: page.offset,
take: page.limit,
});
return posts.map(ownForumView);
}
submit(
actor: Principal,
input: ForumReplyInput | ForumThreadInput,
threadId: string | null = null,
) {
const title = 'title' in input ? input.title : null;
const requestHash = commandHash(
threadId ?? '',
title ?? '',
input.displayName,
input.body,
);
return this.access.mutate(actor, null, async (tx) => {
const scope = {
userId: actor.userId,
organizationId: actor.organizationId,
};
const previous = await tx.forumPost.findUnique({
where: {
userId_organizationId_idempotencyKey: {
...scope,
idempotencyKey: input.idempotencyKey,
},
},
include: forumInclude,
});
if (previous) {
assertReplay(previous.requestHash, requestHash);
return ownForumView(previous);
}
if (threadId)
await requirePublicThread(tx, actor.organizationId, threadId);
if (
(await tx.forumPost.count({
where: { ...scope, events: { none: {} } },
})) >= 20
)
throw new AppError('FORUM_PENDING_LIMIT');
const post = await tx.forumPost.create({
data: {
...scope,
threadId,
title,
displayName: input.displayName,
body: input.body,
idempotencyKey: input.idempotencyKey,
requestHash,
},
include: forumInclude,
});
await recordAudit(
tx,
actor.organizationId,
actor.userId,
'forum.submitted',
post.id,
);
return ownForumView(post);
});
}
}