eletrotupi / tcc/ commit / 4dba6a8

api: rig update for triggers + sleep records

Pedro Lucas Porcellis porcellis@eletrotupi.com 1 month ago 4dba6a8c834bf68ca293b235e85eae141a8c99ba
Parents: 26b3197
9 file(s) changed
  • api/src/controllers/sleepRecords.ts +22 -2
  • api/src/controllers/triggers.ts +22 -2
  • api/src/routes/sleepRecords.ts +1 -0
  • api/src/routes/triggers.ts +1 -0
  • api/src/schemas/index.ts +4 -0
  • api/src/schemas/sleepRecord.schema.ts +4 -0
  • api/src/schemas/trigger.schema.ts +4 -0
  • api/src/services/sleepRecord.service.ts +17 -1
  • api/src/services/trigger.service.ts +17 -1
api/src/controllers/sleepRecords.ts
1 1
import { Request, Response, NextFunction } from 'express';
2 2
import { AuthenticatedRequest } from '@app/middleware/auth';
3 3
import {
4 4
  createSleepRecord,
5 5
  getSleepRecordsByUserId,
6 6
  destroySleepRecordById,
7 -
  getSleepRecordById
7 +
  getSleepRecordById,
8 +
  updateSleepRecordById
8 9
} from '@app/services/sleepRecord.service';
9 10

10 11
import {
11 -
  CreateSleepRecordSchema
12 +
  CreateSleepRecordSchema,
13 +
  UpdateSleepRecordSchema
12 14
} from '@app/schemas'
13 15

14 16
export const SleepRecordsController = {
15 17
  create: async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
16 18
    try {
▸ 43 unchanged lines
60 62
  destroy: async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
61 63
    try {
62 64
      const result = await destroySleepRecordById(req.userId!, Number(req.params.id!));
63 65

64 66
      return res.status(200).json({})
67 +
    } catch (err) {
68 +
      next(err);
69 +
    }
70 +
  },
71 +

72 +
  update: async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
73 +
    try {
74 +
      const parsed = UpdateSleepRecordSchema.safeParse(req.body.sleepRecord);
75 +

76 +
      if (!parsed.success) {
77 +
        return res.status(400).json({
78 +
          errors: parsed.error!.issues
79 +
        });
80 +
      }
81 +

82 +
      const sleepRecord = await updateSleepRecordById(req.userId!, Number(req.params.id!), parsed.data);
83 +

84 +
      return res.status(200).json({ sleepRecord });
65 85
    } catch (err) {
66 86
      next(err);
67 87
    }
68 88
  }
69 89
};
api/src/controllers/triggers.ts
1 1
import { Request, Response, NextFunction } from 'express';
2 2
import { AuthenticatedRequest } from '@app/middleware/auth';
3 3
import {
4 4
  createTrigger,
5 5
  getTriggersByUserId,
6 6
  destroyTriggerById,
7 -
  getTriggerById
7 +
  getTriggerById,
8 +
  updateTriggerById
8 9
} from '@app/services/trigger.service';
9 10

10 11
import {
11 -
  CreateTriggerSchema
12 +
  CreateTriggerSchema,
13 +
  UpdateTriggerSchema
12 14
} from '@app/schemas'
13 15

14 16
export const TriggersController = {
15 17
  create: async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
16 18
    try {
▸ 43 unchanged lines
60 62
  show: async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
61 63
    try {
62 64
      const trigger = await getTriggerById(Number(req.userId!), Number(req.params.id!));
63 65

64 66
      return res.status(200).json(trigger)
67 +
    } catch (err) {
68 +
      next(err);
69 +
    }
70 +
  },
71 +

72 +
  update: async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
73 +
    try {
74 +
      const parsed = UpdateTriggerSchema.safeParse(req.body.trigger);
75 +

76 +
      if (!parsed.success) {
77 +
        return res.status(400).json({
78 +
          errors: parsed.error!.issues
79 +
        });
80 +
      }
81 +

82 +
      const trigger = await updateTriggerById(req.userId!, Number(req.params.id!), parsed.data);
83 +

84 +
      return res.status(200).json({ trigger });
65 85
    } catch (err) {
66 86
      next(err);
67 87
    }
68 88
  }
69 89
};
api/src/routes/sleepRecords.ts
1 1
import { Router } from "express";
2 2
import { SleepRecordsController } from '@app/controllers/sleepRecords'
3 3
import { requireAuth } from '@app/middleware/auth';
4 4

5 5
const router = Router();
6 6

7 7
router.get('/', requireAuth, SleepRecordsController.index);
8 8
router.post('/', requireAuth, SleepRecordsController.create);
9 9
router.get('/:id', requireAuth, SleepRecordsController.show);
10 +
router.put('/:id', requireAuth, SleepRecordsController.update);
10 11
router.delete('/:id', requireAuth, SleepRecordsController.destroy);
11 12

12 13
export default router;
api/src/routes/triggers.ts
1 1
import { Router } from "express";
2 2
import { TriggersController } from '@app/controllers/triggers'
3 3
import { requireAuth } from '@app/middleware/auth';
4 4

5 5
const router = Router();
6 6

7 7
router.get('/', requireAuth, TriggersController.index);
8 8
router.get('/:id', requireAuth, TriggersController.show);
9 9
router.post('/', requireAuth, TriggersController.create);
10 +
router.put('/:id', requireAuth, TriggersController.update);
10 11
router.delete('/:id', requireAuth, TriggersController.destroy);
11 12

12 13
export default router;
api/src/schemas/index.ts
1 1
export {
2 2
  CreateMoodSchema,
3 3
  MoodComponentSchema,
4 4
} from "@app/schemas/mood.schema";
5 5

▸ 18 unchanged lines
24 24
} from "@app/schemas/auth.schema";
25 25

26 26
export {
27 27
  type CreateSleepRecordInput,
28 28
  CreateSleepRecordSchema,
29 +
  type UpdateSleepRecordInput,
30 +
  UpdateSleepRecordSchema,
29 31
} from "@app/schemas/sleepRecord.schema";
30 32

31 33
export {
32 34
  type CreateTriggerInput,
33 35
  CreateTriggerSchema,
36 +
  type UpdateTriggerInput,
37 +
  UpdateTriggerSchema,
34 38
} from "@app/schemas/trigger.schema";
35 39

36 40
export {
37 41
  InsightsQuerySchema,
38 42
  type InsightsQueryInput,
39 43
} from "@app/schemas/insight.schema";
api/src/schemas/sleepRecord.schema.ts
1 1
import { z } from 'zod';
2 2

3 3
export const CreateSleepRecordSchema = z.object({
4 4
  annotations: z.string().optional(),
5 5
  date: z.coerce.date(),
6 6
  average: z.number().min(0).max(15),
7 7
});
8 8

9 9
export type CreateSleepRecordInput = z.infer<typeof CreateSleepRecordSchema>;
10 +

11 +
export const UpdateSleepRecordSchema = CreateSleepRecordSchema.partial();
12 +

13 +
export type UpdateSleepRecordInput = z.infer<typeof UpdateSleepRecordSchema>;
api/src/schemas/trigger.schema.ts
1 1
import { z } from 'zod';
2 2
import {
3 3
  TriggerType
4 4
} from '@prisma/client';
5 5

▸ 2 unchanged lines
8 8
  moment: z.coerce.date(),
9 9
  category: z.nativeEnum(TriggerType)
10 10
});
11 11

12 12
export type CreateTriggerInput = z.infer<typeof CreateTriggerSchema>;
13 +

14 +
export const UpdateTriggerSchema = CreateTriggerSchema.partial();
15 +

16 +
export type UpdateTriggerInput = z.infer<typeof UpdateTriggerSchema>;
api/src/services/sleepRecord.service.ts
1 1
import { prisma } from '@app/lib/prisma';
2 2
import { SleepRecord } from '@prisma/client';
3 3

4 -
import { CreateSleepRecordInput } from '@app/schemas';
4 +
import { CreateSleepRecordInput, UpdateSleepRecordInput } from '@app/schemas';
5 5
import { rollingPeriod } from "@app/lib/queue/processors/insights/utils";
6 6
import { InsightJobName } from "@app/lib/queue/types";
7 7
import { getQueue } from "@app/lib/queue";
8 8
import { startOfDay } from "date-fns";
9 9

▸ 68 unchanged lines
78 78

79 79
export const getSleepRecordById = async (userId: number, id: number): Promise<SleepRecord | null> => {
80 80
  return await prisma.sleepRecord.findUnique({
81 81
    where: { userId, id }
82 82
  })
83 +
}
84 +

85 +
export const updateSleepRecordById = async (
86 +
  userId: number, id: number, input: UpdateSleepRecordInput
87 +
): Promise<SleepRecord> => {
88 +
  const sleepRecord = await prisma.sleepRecord.update({
89 +
    where: {
90 +
      id,
91 +
      userId
92 +
    },
93 +
    data: input
94 +
  });
95 +

96 +
  void enqueueEnergySleepInsights(userId);
97 +

98 +
  return sleepRecord;
83 99
}
84 100

85 101
async function enqueueEnergySleepInsights(userId: number): Promise<void> {
86 102
  const queue = getQueue("insights");
87 103
  const period = rollingPeriod(7);
▸ 22 unchanged lines
110 126
        removeOnFail: true,
111 127
      },
112 128
    },
113 129
  ]);
114 130
}
api/src/services/trigger.service.ts
1 1
import { prisma } from '@app/lib/prisma';
2 2
import { Trigger } from '@prisma/client';
3 3

4 -
import { CreateTriggerInput } from '@app/schemas';
4 +
import { CreateTriggerInput, UpdateTriggerInput } from '@app/schemas';
5 5
import { rollingPeriod } from "@app/lib/queue/processors/insights/utils";
6 6
import { InsightJobName } from "@app/lib/queue/types";
7 7
import { getQueue } from "@app/lib/queue";
8 8

9 9
export const createTrigger = async (
▸ 71 unchanged lines
81 81

82 82
export const getTriggerById = async (userId: number, id: number): Promise<Trigger | null> => {
83 83
  return await prisma.trigger.findUnique({
84 84
    where: { userId, id }
85 85
  })
86 +
}
87 +

88 +
export const updateTriggerById = async (
89 +
  userId: number, id: number, input: UpdateTriggerInput
90 +
): Promise<Trigger> => {
91 +
  const trigger = await prisma.trigger.update({
92 +
    where: {
93 +
      id,
94 +
      userId
95 +
    },
96 +
    data: input
97 +
  });
98 +

99 +
  void enqueueTriggerPatternInsight(userId);
100 +

101 +
  return trigger;
86 102
}
87 103

88 104
async function enqueueTriggerPatternInsight(userId: number): Promise<void> {
89 105
  await getQueue('insights').add(
90 106
    InsightJobName.TriggerPattern,
▸ 3 unchanged lines
94 110
      removeOnComplete: true,
95 111
      removeOnFail: true,
96 112
    }
97 113
  );
98 114
}