73 lines
2.3 KiB
TypeScript
73 lines
2.3 KiB
TypeScript
import { Injectable } from '@nestjs/common';
|
|
import { AccessStore } from '../identity/access.store';
|
|
import type { Principal } from '../identity/identity.types';
|
|
import { assertReplay, commandHash } from '../common/idempotency';
|
|
import { recordAudit } from '../identity/audit';
|
|
import { AppError } from '../common/errors/app-error';
|
|
import { requireArticle, nextBlogVersion } from './blog-lookup';
|
|
import type { BlogCreateInput, BlogPatchInput } from './blog.schemas';
|
|
|
|
@Injectable()
|
|
export class BlogDraftStore {
|
|
constructor(private readonly access: AccessStore) {}
|
|
create(actor: Principal, input: BlogCreateInput) {
|
|
const requestHash = commandHash(
|
|
input.slug,
|
|
input.title,
|
|
input.summary,
|
|
input.body,
|
|
);
|
|
return this.access.mutate(actor, 'blog.manage', async (tx) => {
|
|
const previous = await tx.blogArticle.findUnique({
|
|
where: {
|
|
organizationId_idempotencyKey: {
|
|
organizationId: actor.organizationId,
|
|
idempotencyKey: input.idempotencyKey,
|
|
},
|
|
},
|
|
});
|
|
if (previous) {
|
|
assertReplay(previous.requestHash, requestHash);
|
|
return previous;
|
|
}
|
|
const article = await tx.blogArticle.create({
|
|
data: {
|
|
...input,
|
|
organizationId: actor.organizationId,
|
|
createdById: actor.userId,
|
|
requestHash,
|
|
},
|
|
});
|
|
await recordAudit(
|
|
tx,
|
|
actor.organizationId,
|
|
actor.userId,
|
|
'blog.created',
|
|
article.id,
|
|
);
|
|
return article;
|
|
});
|
|
}
|
|
edit(actor: Principal, id: string, input: BlogPatchInput) {
|
|
return this.access.mutate(actor, 'blog.manage', async (tx) => {
|
|
const article = await requireArticle(tx, actor.organizationId, id);
|
|
if (article.state === 'WITHDRAWN')
|
|
throw new AppError('BLOG_STATE_CONFLICT');
|
|
if (article.version !== input.version) throw new AppError('BLOG_CHANGED');
|
|
const { version, ...fields } = input;
|
|
const updated = await tx.blogArticle.update({
|
|
where: { id },
|
|
data: { ...fields, version: nextBlogVersion(version) },
|
|
});
|
|
await recordAudit(
|
|
tx,
|
|
actor.organizationId,
|
|
actor.userId,
|
|
'blog.updated',
|
|
id,
|
|
);
|
|
return updated;
|
|
});
|
|
}
|
|
}
|