Skip to content

Commit 53ba1e3

Browse files
authored
feat: Add favorites for dashboads and saved searches (#2021)
## Summary This PR adds per-user favorites for dashboards and saved searches. Users can favorite dashboards or saved searches to see them at the top of the relevant listing page and in the sidebar. The favorites are persisted in Mongo or (in local mode) in local storage. ### Screenshots or video https://github.com/user-attachments/assets/7cc273df-9fd8-4abb-bed3-5df742442ab3 ### How to test locally or on Vercel The local mode favorites can be tested in vercel preview. The mongodb-backed favorites can be tested locally. ### References - Linear Issue: Closes HDX-3455 - Related PRs:
1 parent 308da30 commit 53ba1e3

20 files changed

Lines changed: 1158 additions & 67 deletions

‎.changeset/hip-goats-taste.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
---
2+
"@hyperdx/common-utils": patch
3+
"@hyperdx/api": patch
4+
"@hyperdx/app": patch
5+
---
6+
7+
feat: Add favoriting for dashboards and saved searches

‎packages/api/src/api-app.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import { appErrorHandler } from './middleware/error';
1111
import routers from './routers/api';
1212
import clickhouseProxyRouter from './routers/api/clickhouseProxy';
1313
import connectionsRouter from './routers/api/connections';
14+
import favoritesRouter from './routers/api/favorites';
1415
import savedSearchRouter from './routers/api/savedSearch';
1516
import sourcesRouter from './routers/api/sources';
1617
import externalRoutersV2 from './routers/external-api/v2';
@@ -94,6 +95,7 @@ app.use('/webhooks', isUserAuthenticated, routers.webhooksRouter);
9495
app.use('/connections', isUserAuthenticated, connectionsRouter);
9596
app.use('/sources', isUserAuthenticated, sourcesRouter);
9697
app.use('/saved-search', isUserAuthenticated, savedSearchRouter);
98+
app.use('/favorites', isUserAuthenticated, favoritesRouter);
9799
app.use('/clickhouse-proxy', isUserAuthenticated, clickhouseProxyRouter);
98100
// ---------------------------------------------------------------------
99101

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
import Favorite, { IFavorite } from '@/models/favorite';
2+
3+
export function getFavorites(userId: string, teamId: string) {
4+
return Favorite.find({ user: userId, team: teamId });
5+
}
6+
7+
export function addFavorite(
8+
userId: string,
9+
teamId: string,
10+
resourceType: IFavorite['resourceType'],
11+
resourceId: string,
12+
) {
13+
return Favorite.findOneAndUpdate(
14+
{ user: userId, team: teamId, resourceType, resourceId },
15+
{ user: userId, team: teamId, resourceType, resourceId },
16+
{ upsert: true, new: true },
17+
);
18+
}
19+
20+
export function removeFavorite(
21+
userId: string,
22+
teamId: string,
23+
resourceType: IFavorite['resourceType'],
24+
resourceId: string,
25+
) {
26+
return Favorite.deleteOne({
27+
user: userId,
28+
team: teamId,
29+
resourceType,
30+
resourceId,
31+
});
32+
}
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
import mongoose, { Schema } from 'mongoose';
2+
3+
import type { ObjectId } from '.';
4+
5+
export interface IFavorite {
6+
_id: ObjectId;
7+
user: ObjectId;
8+
team: ObjectId;
9+
resourceType: 'dashboard' | 'savedSearch';
10+
resourceId: string;
11+
createdAt: Date;
12+
updatedAt: Date;
13+
}
14+
15+
const favoriteSchema = new Schema<IFavorite>(
16+
{
17+
user: {
18+
type: mongoose.Schema.Types.ObjectId,
19+
required: true,
20+
ref: 'User',
21+
},
22+
team: {
23+
type: mongoose.Schema.Types.ObjectId,
24+
required: true,
25+
ref: 'Team',
26+
},
27+
resourceType: {
28+
type: String,
29+
required: true,
30+
enum: ['dashboard', 'savedSearch'],
31+
},
32+
resourceId: {
33+
type: String,
34+
required: true,
35+
},
36+
},
37+
{
38+
timestamps: true,
39+
toJSON: { virtuals: true },
40+
},
41+
);
42+
43+
favoriteSchema.index(
44+
{ team: 1, user: 1, resourceType: 1, resourceId: 1 },
45+
{ unique: true },
46+
);
47+
48+
export default mongoose.model<IFavorite>('Favorite', favoriteSchema);
Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
import mongoose from 'mongoose';
2+
3+
import { getLoggedInAgent, getServer } from '@/fixtures';
4+
5+
describe('favorites router', () => {
6+
const server = getServer();
7+
let agent: Awaited<ReturnType<typeof getLoggedInAgent>>['agent'];
8+
9+
beforeAll(async () => {
10+
await server.start();
11+
});
12+
13+
beforeEach(async () => {
14+
const result = await getLoggedInAgent(server);
15+
agent = result.agent;
16+
});
17+
18+
afterEach(async () => {
19+
await server.clearDBs();
20+
});
21+
22+
afterAll(async () => {
23+
await server.stop();
24+
});
25+
26+
it('can add a dashboard favorite', async () => {
27+
const resourceId = new mongoose.Types.ObjectId().toString();
28+
const res = await agent
29+
.put('/favorites')
30+
.send({ resourceType: 'dashboard', resourceId })
31+
.expect(200);
32+
expect(res.body.resourceType).toBe('dashboard');
33+
expect(res.body.resourceId).toBe(resourceId);
34+
});
35+
36+
it('can add a savedSearch favorite', async () => {
37+
const resourceId = new mongoose.Types.ObjectId().toString();
38+
const res = await agent
39+
.put('/favorites')
40+
.send({ resourceType: 'savedSearch', resourceId })
41+
.expect(200);
42+
expect(res.body.resourceType).toBe('savedSearch');
43+
expect(res.body.resourceId).toBe(resourceId);
44+
});
45+
46+
it('can list favorites', async () => {
47+
const id1 = new mongoose.Types.ObjectId().toString();
48+
const id2 = new mongoose.Types.ObjectId().toString();
49+
await agent
50+
.put('/favorites')
51+
.send({ resourceType: 'dashboard', resourceId: id1 })
52+
.expect(200);
53+
await agent
54+
.put('/favorites')
55+
.send({ resourceType: 'savedSearch', resourceId: id2 })
56+
.expect(200);
57+
58+
const res = await agent.get('/favorites').expect(200);
59+
expect(res.body).toHaveLength(2);
60+
expect(res.body.map((f: any) => f.resourceId).sort()).toEqual(
61+
[id1, id2].sort(),
62+
);
63+
});
64+
65+
it('can remove a favorite', async () => {
66+
const resourceId = new mongoose.Types.ObjectId().toString();
67+
await agent
68+
.put('/favorites')
69+
.send({ resourceType: 'dashboard', resourceId })
70+
.expect(200);
71+
72+
await agent.delete(`/favorites/dashboard/${resourceId}`).expect(204);
73+
74+
const res = await agent.get('/favorites').expect(200);
75+
expect(res.body).toHaveLength(0);
76+
});
77+
78+
it('adding duplicate favorite is idempotent', async () => {
79+
const resourceId = new mongoose.Types.ObjectId().toString();
80+
await agent
81+
.put('/favorites')
82+
.send({ resourceType: 'dashboard', resourceId })
83+
.expect(200);
84+
await agent
85+
.put('/favorites')
86+
.send({ resourceType: 'dashboard', resourceId })
87+
.expect(200);
88+
89+
const res = await agent.get('/favorites').expect(200);
90+
expect(res.body).toHaveLength(1);
91+
});
92+
93+
it('removing non-existent favorite returns 204', async () => {
94+
const resourceId = new mongoose.Types.ObjectId().toString();
95+
await agent.delete(`/favorites/dashboard/${resourceId}`).expect(204);
96+
});
97+
98+
it('rejects invalid resourceType', async () => {
99+
const resourceId = new mongoose.Types.ObjectId().toString();
100+
await agent
101+
.put('/favorites')
102+
.send({ resourceType: 'invalid', resourceId })
103+
.expect(400);
104+
});
105+
106+
it('rejects invalid resourceId', async () => {
107+
await agent
108+
.put('/favorites')
109+
.send({ resourceType: 'dashboard', resourceId: 'not-an-objectid' })
110+
.expect(400);
111+
});
112+
});
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
import express from 'express';
2+
import { z } from 'zod';
3+
import { validateRequest } from 'zod-express-middleware';
4+
5+
import {
6+
addFavorite,
7+
getFavorites,
8+
removeFavorite,
9+
} from '@/controllers/favorite';
10+
import { getNonNullUserWithTeam } from '@/middleware/auth';
11+
import { objectIdSchema } from '@/utils/zod';
12+
13+
const router = express.Router();
14+
15+
const resourceTypeSchema = z.enum(['dashboard', 'savedSearch']);
16+
17+
router.get('/', async (req, res, next) => {
18+
try {
19+
const { teamId, userId } = getNonNullUserWithTeam(req);
20+
21+
const favorites = await getFavorites(userId.toString(), teamId.toString());
22+
23+
return res.json(favorites);
24+
} catch (e) {
25+
next(e);
26+
}
27+
});
28+
29+
router.put(
30+
'/',
31+
validateRequest({
32+
body: z.object({
33+
resourceType: resourceTypeSchema,
34+
resourceId: objectIdSchema,
35+
}),
36+
}),
37+
async (req, res, next) => {
38+
try {
39+
const { teamId, userId } = getNonNullUserWithTeam(req);
40+
41+
const favorite = await addFavorite(
42+
userId.toString(),
43+
teamId.toString(),
44+
req.body.resourceType,
45+
req.body.resourceId,
46+
);
47+
48+
return res.json(favorite);
49+
} catch (e) {
50+
next(e);
51+
}
52+
},
53+
);
54+
55+
router.delete(
56+
'/:resourceType/:resourceId',
57+
validateRequest({
58+
params: z.object({
59+
resourceType: resourceTypeSchema,
60+
resourceId: objectIdSchema,
61+
}),
62+
}),
63+
async (req, res, next) => {
64+
try {
65+
const { teamId, userId } = getNonNullUserWithTeam(req);
66+
67+
await removeFavorite(
68+
userId.toString(),
69+
teamId.toString(),
70+
req.params.resourceType,
71+
req.params.resourceId,
72+
);
73+
74+
return res.status(204).send();
75+
} catch (e) {
76+
next(e);
77+
}
78+
},
79+
);
80+
81+
export default router;

‎packages/app/src/DBDashboardPage.tsx‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,7 @@ import EditTimeChartForm from '@/components/DBEditTimeChartForm';
8686
import DBNumberChart from '@/components/DBNumberChart';
8787
import DBTableChart from '@/components/DBTableChart';
8888
import { DBTimeChart } from '@/components/DBTimeChart';
89+
import { FavoriteButton } from '@/components/FavoriteButton';
8990
import FullscreenPanelModal from '@/components/FullscreenPanelModal';
9091
import SectionHeader from '@/components/SectionHeader';
9192
import { TimePicker } from '@/components/TimePicker';
@@ -1559,7 +1560,7 @@ function DBDashboardPage({ presetConfig }: { presetConfig?: Dashboard }) {
15591560
<Anchor component={Link} href="/dashboards/list" fz="sm" c="dimmed">
15601561
Dashboards
15611562
</Anchor>
1562-
<Text fz="sm" c="dimmed">
1563+
<Text fz="sm" c="dimmed" maw={500} truncate="end">
15631564
{dashboard?.name ?? 'Untitled'}
15641565
</Text>
15651566
</Breadcrumbs>
@@ -1578,6 +1579,12 @@ function DBDashboardPage({ presetConfig }: { presetConfig?: Dashboard }) {
15781579
}}
15791580
/>
15801581
<Group gap="xs">
1582+
{!isLocalDashboard && dashboard?.id && (
1583+
<FavoriteButton
1584+
resourceType="dashboard"
1585+
resourceId={dashboard.id}
1586+
/>
1587+
)}
15811588
{!isLocalDashboard && dashboard?.id && (
15821589
<Tags
15831590
allowCreate

‎packages/app/src/DBSearchPage.tsx‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,7 @@ import { ContactSupportText } from '@/components/ContactSupportText';
8282
import { DBSearchPageFilters } from '@/components/DBSearchPageFilters';
8383
import { DBTimeChart } from '@/components/DBTimeChart';
8484
import { ErrorBoundary } from '@/components/Error/ErrorBoundary';
85+
import { FavoriteButton } from '@/components/FavoriteButton';
8586
import { InputControlled } from '@/components/InputControlled';
8687
import OnboardingModal from '@/components/OnboardingModal';
8788
import SearchWhereInput, {
@@ -1582,7 +1583,7 @@ function DBSearchPage() {
15821583
<Anchor component={Link} href="/search/list" fz="sm" c="dimmed">
15831584
Saved Searches
15841585
</Anchor>
1585-
<Text fz="sm" c="dimmed">
1586+
<Text fz="sm" c="dimmed" maw={400} truncate="end">
15861587
{savedSearch.name}
15871588
</Text>
15881589
</Breadcrumbs>
@@ -1599,6 +1600,10 @@ function DBSearchPage() {
15991600
</Stack>
16001601

16011602
<Group gap="xs">
1603+
<FavoriteButton
1604+
resourceType="savedSearch"
1605+
resourceId={savedSearch.id}
1606+
/>
16021607
<Tags
16031608
allowCreate
16041609
values={savedSearch.tags || []}

‎packages/app/src/EditablePageName.tsx‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,16 @@ export function EditablePageName({
6363
</form>
6464
) : (
6565
<div className="d-flex align-items-center" style={{ minWidth: 100 }}>
66-
<Title fw={400} order={3}>
66+
<Title
67+
fw={400}
68+
maw={500}
69+
order={3}
70+
style={{
71+
textOverflow: 'ellipsis',
72+
whiteSpace: 'nowrap',
73+
overflow: 'hidden',
74+
}}
75+
>
6776
{name}
6877
</Title>
6978
{hovered && (

0 commit comments

Comments
 (0)