refactor: extract some monitor logic into model

This commit is contained in:
moonrailgun 2024-01-06 22:07:58 +08:00
parent 4bd069081a
commit 19e7ed516b
2 changed files with 73 additions and 36 deletions

View File

@ -1,3 +1,61 @@
import { MonitorPublicInfoSchema } from '../../../types';
import { prisma } from '../_client';
import { MonitorManager } from './manager';
export const monitorManager = new MonitorManager();
export async function getMonitorPublicInfos(monitorIds: string[]) {
const res = await prisma.monitor.findMany({
where: {
id: {
in: monitorIds,
},
},
});
return res.map((item) => MonitorPublicInfoSchema.parse(item));
}
export function getMonitorData(
workspaceId: string,
monitorId: string,
startDate: Date,
endDate: Date
) {
return prisma.monitorData.findMany({
where: {
monitor: {
id: monitorId,
workspaceId,
},
createdAt: {
gte: startDate,
lte: endDate,
},
},
select: {
value: true,
createdAt: true,
},
});
}
export function getMonitorRecentData(
workspaceId: string,
monitorId: string,
take: number
) {
return prisma.monitorData.findMany({
where: {
monitor: {
id: monitorId,
workspaceId,
},
},
take: -take,
select: {
value: true,
createdAt: true,
},
});
}

View File

@ -7,7 +7,12 @@ import {
} from '../trpc';
import { prisma } from '../../model/_client';
import { z } from 'zod';
import { monitorManager } from '../../model/monitor';
import {
getMonitorData,
getMonitorPublicInfos,
getMonitorRecentData,
monitorManager,
} from '../../model/monitor';
import {
MonitorInfoWithNotificationIds,
MonitorPublicInfoSchema,
@ -101,15 +106,8 @@ export const monitorRouter = router({
.output(z.array(MonitorPublicInfoSchema))
.query(async ({ input }) => {
const { monitorIds } = input;
const res = await prisma.monitor.findMany({
where: {
id: {
in: monitorIds,
},
},
});
return res.map((item) => MonitorPublicInfoSchema.parse(item));
return getMonitorPublicInfos(monitorIds);
}),
upsert: workspaceOwnerProcedure
.meta(
@ -220,22 +218,12 @@ export const monitorRouter = router({
.query(async ({ input }) => {
const { monitorId, workspaceId, startAt, endAt } = input;
return prisma.monitorData.findMany({
where: {
monitor: {
id: monitorId,
workspaceId,
},
createdAt: {
gte: new Date(startAt),
lte: new Date(endAt),
},
},
select: {
value: true,
createdAt: true,
},
});
return getMonitorData(
workspaceId,
monitorId,
new Date(startAt),
new Date(endAt)
);
}),
changeActive: workspaceOwnerProcedure
.meta(
@ -312,18 +300,9 @@ export const monitorRouter = router({
)
)
.query(async ({ input }) => {
const { monitorId, take } = input;
const { workspaceId, monitorId, take } = input;
return prisma.monitorData.findMany({
where: {
monitorId,
},
take: -take,
select: {
value: true,
createdAt: true,
},
});
return getMonitorRecentData(workspaceId, monitorId, take);
}),
dataMetrics: workspaceProcedure
.meta(