62 lines
1.9 KiB
TypeScript
62 lines
1.9 KiB
TypeScript
import { assertUnreachable } from '@app/client/helpers';
|
|
import { call } from '@app/common';
|
|
import { prisma } from '@app/server/prisma/client';
|
|
import {
|
|
Book as BookSchema,
|
|
WorkingProgressStatus as WorkingProgressStatusSchema
|
|
} from '@generated/types';
|
|
import { Book, WorkingProgressStatus } from '@prisma/client';
|
|
import { toUserSchema } from './userMapper';
|
|
|
|
export async function toBookSchema(model: Book): Promise<BookSchema> {
|
|
return {
|
|
id: model.id,
|
|
title: model.title,
|
|
description: model.description,
|
|
author: await call(async () => {
|
|
const userModel = await prisma.user.findUniqueOrThrow({ where: { id: model.authorId } });
|
|
return toUserSchema(userModel);
|
|
}),
|
|
createdAt: model.createdAt.toISOString(),
|
|
updatedAt: model.updatedAt.toISOString(),
|
|
progressStatus: call(() => {
|
|
ensureWorkingProgressStatus(model.progressStatus);
|
|
return model.progressStatus;
|
|
}),
|
|
wordsTotal: model.wordsTotal,
|
|
chaptersTotal: await call(async () => {
|
|
const chaptersCount = await prisma.bookChapter.count({
|
|
where: {
|
|
bookId: model.id
|
|
}
|
|
});
|
|
return chaptersCount;
|
|
}),
|
|
// todo: ratings implementation
|
|
ratingTotal: await call(async () => {
|
|
const ratingsCount = await prisma.rating.count({
|
|
where: {
|
|
bookId: model.id
|
|
}
|
|
});
|
|
return ratingsCount;
|
|
}),
|
|
reviewsTotal: await call(async () => {
|
|
const reviewsCount = await prisma.review.count({
|
|
where: {
|
|
bookId: model.id
|
|
}
|
|
});
|
|
return reviewsCount;
|
|
})
|
|
};
|
|
}
|
|
|
|
function ensureWorkingProgressStatus(
|
|
value: WorkingProgressStatus
|
|
): asserts value is WorkingProgressStatusSchema {
|
|
if (value === WorkingProgressStatus.inProgress) return;
|
|
if (value === WorkingProgressStatus.frozen) return;
|
|
if (value === WorkingProgressStatus.complete) return;
|
|
assertUnreachable(value);
|
|
}
|