| 1 | import { prisma } from '@app/lib/prisma';
|
| 2 | import { Mood } from '@prisma/client';
|
| 3 |
|
| 4 | import { CreateMoodInput } from '@app/schemas';
|
| 5 |
|
| 6 | export const createMood = async (userId: number, input: CreateMoodInput): Promise<Mood> => {
|
| 7 | const { moodComponents, ...moodData } = input;
|
| 8 |
|
| 9 | return prisma.mood.create({
|
| 10 | data: {
|
| 11 | ...moodData,
|
| 12 | userId,
|
| 13 | moodComponents: {
|
| 14 | create: moodComponents
|
| 15 | }
|
| 16 | },
|
| 17 | include: { moodComponents: true }
|
| 18 | });
|
| 19 | };
|
| 20 |
|
| 21 | export const getMoodsByUserId = async (
|
| 22 | userId: number,
|
| 23 | params?: {
|
| 24 | limit?: number;
|
| 25 | page?: number;
|
| 26 | from?: string;
|
| 27 | to?: string;
|
| 28 | }
|
| 29 | ): Promise<{ entries: Mood[]; total: number; page: number; nextPage: number | null }> => {
|
| 30 | const page = params?.page ?? 1;
|
| 31 | const limit = params?.limit ?? 20;
|
| 32 | const skip = (page - 1) * limit;
|
| 33 |
|
| 34 | const where = {
|
| 35 | userId,
|
| 36 | ...(params?.from || params?.to ? {
|
| 37 | moment: {
|
| 38 | ...(params.from && { gte: new Date(params.from) }),
|
| 39 | ...(params.to && { lte: new Date(params.to) }),
|
| 40 | }
|
| 41 | } : {}),
|
| 42 | };
|
| 43 |
|
| 44 | const [entries, total] = await Promise.all([
|
| 45 | prisma.mood.findMany({
|
| 46 | where,
|
| 47 | include: { moodComponents: true },
|
| 48 | orderBy: { moment: 'desc' },
|
| 49 | take: limit,
|
| 50 | skip,
|
| 51 | }),
|
| 52 | prisma.mood.count({ where }),
|
| 53 | ]);
|
| 54 |
|
| 55 | const totalPages = Math.ceil(total / limit);
|
| 56 |
|
| 57 | return {
|
| 58 | entries,
|
| 59 | total,
|
| 60 | page,
|
| 61 | nextPage: page < totalPages ? page + 1 : null,
|
| 62 | };
|
| 63 | };
|
| 64 |
|
| 65 | export const getMoodById = async (id: number): Promise<Mood | null> => {
|
| 66 | return await prisma.mood.findUnique({
|
| 67 | where: {
|
| 68 | id
|
| 69 | },
|
| 70 | include: { moodComponents: true }
|
| 71 | });
|
| 72 | }
|
| 73 |
|
| 74 | export const destroyMoodById = async (userId: number, id: number): Promise<Mood> => {
|
| 75 | return await prisma.mood.delete({
|
| 76 | where: {
|
| 77 | id,
|
| 78 | userId
|
| 79 | }
|
| 80 | })
|
| 81 | }
|