Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ext dashboard api #267

Merged
merged 1 commit into from
Jan 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
63 changes: 62 additions & 1 deletion packages/api/src/controllers/dashboard.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
import { differenceBy, uniq } from 'lodash';
import { z } from 'zod';

import type { ObjectId } from '@/models';
import Alert from '@/models/alert';
import Dashboard from '@/models/dashboard';
import { chartSchema, tagsSchema } from '@/utils/zod';

export default async function deleteDashboardAndAlerts(
export async function deleteDashboardAndAlerts(
dashboardId: string,
teamId: ObjectId,
) {
Expand All @@ -14,3 +18,60 @@ export default async function deleteDashboardAndAlerts(
await Alert.deleteMany({ dashboardId: dashboard._id });
}
}

export async function updateDashboardAndAlerts(
dashboardId: string,
teamId: ObjectId,
{
name,
charts,
query,
tags,
}: {
name: string;
charts: z.infer<typeof chartSchema>[];
query: string;
tags: z.infer<typeof tagsSchema>;
},
) {
const oldDashboard = await Dashboard.findOne({
_id: dashboardId,
team: teamId,
});
if (oldDashboard == null) {
throw new Error('Dashboard not found');
}

const updatedDashboard = await Dashboard.findOneAndUpdate(
{
_id: dashboardId,
team: teamId,
},
{
name,
charts,
query,
tags: tags && uniq(tags),
},
{ new: true },
);
if (updatedDashboard == null) {
throw new Error('Could not update dashboard');
}

// Delete related alerts
const deletedChartIds = differenceBy(
oldDashboard?.charts || [],
updatedDashboard?.charts || [],
'id',
).map(c => c.id);

if (deletedChartIds?.length > 0) {
await Alert.deleteMany({
dashboardId: dashboardId,
chartId: { $in: deletedChartIds },
});
}

return updatedDashboard;
}
15 changes: 15 additions & 0 deletions packages/api/src/fixtures.ts
Original file line number Diff line number Diff line change
Expand Up @@ -325,6 +325,21 @@ export const makeChart = (opts?: { id?: string }) => ({
],
});

export const makeExternalChart = (opts?: { id?: string }) => ({
name: 'Test Chart',
x: 1,
y: 1,
w: 1,
h: 1,
series: [
{
type: 'time',
data_source: 'events',
aggFn: 'count',
},
],
});

export const makeAlert = ({
dashboardId,
chartId,
Expand Down
38 changes: 2 additions & 36 deletions packages/api/src/routers/api/__tests__/dashboard.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,44 +3,10 @@ import {
closeDB,
getLoggedInAgent,
getServer,
makeAlert,
makeChart,
} from '@/fixtures';

const randomId = () => Math.random().toString(36).substring(7);

const makeChart = () => ({
id: randomId(),
name: 'Test Chart',
x: 1,
y: 1,
w: 1,
h: 1,
series: [
{
type: 'time',
table: 'metrics',
},
],
});

const makeAlert = ({
dashboardId,
chartId,
}: {
dashboardId: string;
chartId: string;
}) => ({
channel: {
type: 'webhook',
webhookId: 'test-webhook-id',
},
interval: '15m',
threshold: 8,
type: 'presence',
source: 'CHART',
dashboardId,
chartId,
});

const MOCK_DASHBOARD = {
name: 'Test Dashboard',
charts: [makeChart(), makeChart(), makeChart(), makeChart(), makeChart()],
Expand Down
40 changes: 14 additions & 26 deletions packages/api/src/routers/api/dashboards.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@ import { differenceBy, groupBy, uniq } from 'lodash';
import { z } from 'zod';
import { validateRequest } from 'zod-express-middleware';

import deleteDashboardAndAlerts from '@/controllers/dashboard';
import {
deleteDashboardAndAlerts,
updateDashboardAndAlerts,
} from '@/controllers/dashboard';
import Alert from '@/models/alert';
import Dashboard from '@/models/dashboard';
import { chartSchema, objectIdSchema, tagsSchema } from '@/utils/zod';
Expand Down Expand Up @@ -53,9 +56,9 @@ router.post(
'/',
validateRequest({
body: z.object({
name: z.string(),
name: z.string().max(1024),
charts: z.array(chartSchema),
query: z.string(),
query: z.string().max(2048),
tags: tagsSchema,
}),
}),
Expand Down Expand Up @@ -88,10 +91,13 @@ router.post(
router.put(
'/:id',
validateRequest({
params: z.object({
id: objectIdSchema,
}),
body: z.object({
name: z.string(),
name: z.string().max(1024),
charts: z.array(chartSchema),
query: z.string(),
query: z.string().max(2048),
tags: tagsSchema,
}),
}),
Expand All @@ -102,38 +108,20 @@ router.put(
if (teamId == null) {
return res.sendStatus(403);
}
if (!dashboardId) {
return res.sendStatus(400);
}

const { name, charts, query, tags } = req.body ?? {};

// Update dashboard from name and charts
const oldDashboard = await Dashboard.findById(dashboardId);
const updatedDashboard = await Dashboard.findByIdAndUpdate(
const updatedDashboard = await updateDashboardAndAlerts(
dashboardId,
teamId,
{
name,
charts,
query,
tags: tags && uniq(tags),
tags,
},
{ new: true },
);

// Delete related alerts
const deletedChartIds = differenceBy(
oldDashboard?.charts || [],
updatedDashboard?.charts || [],
'id',
).map(c => c.id);

if (deletedChartIds?.length > 0) {
await Alert.deleteMany({
dashboardId: dashboardId,
chartId: { $in: deletedChartIds },
});
}
res.json({
data: updatedDashboard,
});
Expand Down