47 lines
1.5 KiB
TypeScript
47 lines
1.5 KiB
TypeScript
import { countWords, ensureIdentity } from '@app/server/helpers';
|
|
import { IdentityContext } from '@app/server/identity';
|
|
import { prisma } from '@app/server/prisma/client';
|
|
import { updateBookStats } from '@app/server/service/book';
|
|
import { BookChapter, MutationBookChapterUpdateArgs } from '@generated/types';
|
|
import { toBookChapterSchema } from './mappers/bookChapterMapper';
|
|
|
|
export async function BookChapterUpdateResolver(
|
|
_: any,
|
|
{ input }: MutationBookChapterUpdateArgs,
|
|
{ req, res, identity }: IdentityContext
|
|
): Promise<BookChapter> {
|
|
ensureIdentity(identity);
|
|
|
|
const model = await prisma.bookChapter.findUniqueOrThrow({
|
|
where: { id: input.id },
|
|
select: {
|
|
book: {
|
|
select: {
|
|
authorId: true
|
|
}
|
|
}
|
|
}
|
|
});
|
|
|
|
if (identity.id !== model.book.authorId) throw new Error('Operation is not permitted.');
|
|
|
|
if (input.title.length > 60) throw new Error('Title is too long.');
|
|
if (input.foreword != null && input.foreword.length > 500)
|
|
throw new Error('Foreword is too long.');
|
|
if (input.footnote != null && input.footnote.length > 500)
|
|
throw new Error('Footnote is too long.');
|
|
|
|
const modelUpdated = await prisma.bookChapter.update({
|
|
where: { id: input.id },
|
|
data: {
|
|
title: input.title,
|
|
foreword: input.foreword,
|
|
footnote: input.footnote,
|
|
content: input.content,
|
|
wordsTotal: countWords(input.content)
|
|
}
|
|
});
|
|
|
|
await updateBookStats(modelUpdated.bookId);
|
|
return toBookChapterSchema(modelUpdated, { req, res, identity });
|
|
}
|