| 1 | import { prisma } from '@app/lib/prisma';
|
| 2 | import { SleepRecord } from '@prisma/client';
|
| 3 |
|
| 4 | import { CreateSleepRecordInput } from '@app/schemas';
|
| 5 | import { rollingPeriod } from "@app/lib/queue/processors/insights/utils";
|
| 6 | import { InsightJobName } from "@app/lib/queue/types";
|
| 7 | import { getQueue } from "@app/lib/queue";
|
| 8 |
|
| 9 | export const createSleepRecord = async (
|
| 10 | userId: number, input: CreateSleepRecordInput
|
| 11 | ): Promise<SleepRecord> => {
|
| 12 | const sleepRecord = await prisma.sleepRecord.create({
|
| 13 | data: {
|
| 14 | ...input,
|
| 15 | userId
|
| 16 | }
|
| 17 | });
|
| 18 |
|
| 19 | void enqueueEnergySleepInsight(userId);
|
| 20 |
|
| 21 | return sleepRecord;
|
| 22 | };
|
| 23 |
|
| 24 | export const getSleepRecordsByUserId = async (
|
| 25 | userId: number,
|
| 26 | params?: {
|
| 27 | limit?: number;
|
| 28 | page?: number;
|
| 29 | from?: string;
|
| 30 | to?: string;
|
| 31 | }
|
| 32 | ): Promise<{ entries: SleepRecord[]; total: number; page: number; nextPage: number | null }> => {
|
| 33 | const page = params?.page ?? 1;
|
| 34 | const limit = params?.limit ?? 20;
|
| 35 | const skip = (page - 1) * limit;
|
| 36 |
|
| 37 | const where = {
|
| 38 | userId,
|
| 39 | ...(params?.from || params?.to ? {
|
| 40 | date: {
|
| 41 | ...(params.from && { gte: new Date(params.from) }),
|
| 42 | ...(params.to && { lte: new Date(params.to) }),
|
| 43 | }
|
| 44 | } : {}),
|
| 45 | };
|
| 46 |
|
| 47 | const [entries, total] = await Promise.all([
|
| 48 | prisma.sleepRecord.findMany({
|
| 49 | where,
|
| 50 | orderBy: { date: 'desc' },
|
| 51 | take: limit,
|
| 52 | skip,
|
| 53 | }),
|
| 54 | prisma.sleepRecord.count({ where }),
|
| 55 | ]);
|
| 56 |
|
| 57 | const totalPages = Math.ceil(total / limit);
|
| 58 |
|
| 59 | return {
|
| 60 | entries,
|
| 61 | total,
|
| 62 | page,
|
| 63 | nextPage: page < totalPages ? page + 1 : null,
|
| 64 | };
|
| 65 | };
|
| 66 |
|
| 67 | export const destroySleepRecordById = async (
|
| 68 | userId: number, id: number
|
| 69 | ): Promise<SleepRecord> => {
|
| 70 | return await prisma.sleepRecord.delete({
|
| 71 | where: {
|
| 72 | id,
|
| 73 | userId
|
| 74 | }
|
| 75 | })
|
| 76 | }
|
| 77 |
|
| 78 | async function enqueueEnergySleepInsight(userId: number): Promise<void> {
|
| 79 | await getQueue('insights').add(
|
| 80 | InsightJobName.EnergySleep,
|
| 81 | { userId, ...rollingPeriod(7) },
|
| 82 | {
|
| 83 | jobId: `energy-sleep-${userId}-${new Date().toDateString()}`,
|
| 84 | removeOnComplete: true,
|
| 85 | }
|
| 86 | );
|
| 87 | }
|