eletrotupi / tcc/ api/src/services/sleepRecord.service.tsa2422f7425b70cec99fafc8f1c976110c794ee25
1.5 KB | 69 lines Raw
1
import { prisma } from '@app/lib/prisma';
2
import { SleepRecord } from '@prisma/client';
3

4
import { CreateSleepRecordInput } from '@app/schemas';
5

6
export const createSleepRecord = async (
7
  userId: number, input: CreateSleepRecordInput
8
): Promise<SleepRecord> => {
9
  return prisma.sleepRecord.create({
10
    data: {
11
      ...input,
12
      userId
13
    }
14
  });
15
};
16

17
export const getSleepRecordsByUserId = async (
18
  userId: number,
19
  params?: {
20
    limit?: number;
21
    page?: number;
22
    from?: string;
23
    to?: string;
24
  }
25
): Promise<{ entries: SleepRecord[]; total: number; page: number; nextPage: number | null }> => {
26
  const page  = params?.page  ?? 1;
27
  const limit = params?.limit ?? 20;
28
  const skip  = (page - 1) * limit;
29

30
  const where = {
31
    userId,
32
    ...(params?.from || params?.to ? {
33
      date: {
34
        ...(params.from && { gte: new Date(params.from) }),
35
        ...(params.to   && { lte: new Date(params.to)   }),
36
      }
37
    } : {}),
38
  };
39

40
  const [entries, total] = await Promise.all([
41
    prisma.sleepRecord.findMany({
42
      where,
43
      orderBy: { date: 'desc' },
44
      take: limit,
45
      skip,
46
    }),
47
    prisma.sleepRecord.count({ where }),
48
  ]);
49

50
  const totalPages = Math.ceil(total / limit);
51

52
  return {
53
    entries,
54
    total,
55
    page,
56
    nextPage: page < totalPages ? page + 1 : null,
57
  };
58
};
59

60
export const destroySleepRecordById = async (
61
  userId: number, id: number
62
): Promise<SleepRecord> => {
63
  return await prisma.sleepRecord.delete({
64
    where: {
65
      id,
66
      userId
67
    }
68
  })
69
}