Skip to content

Commit

Permalink
Add route to retrieve user's current genre preferences
Browse files Browse the repository at this point in the history
  • Loading branch information
Advayp committed Jan 25, 2025
1 parent 5e41a22 commit 12817cb
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 0 deletions.
37 changes: 37 additions & 0 deletions backend/app/api/genre/me/route.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { verifySession } from '@/lib/session';
import { GET } from './route';
import { prismaMock } from '@/__test__/singleton';

jest.mock('@/lib/session', () => ({
verifySession: jest.fn(),
}));

const mockVerifySession = verifySession as jest.Mock;

test("Preference retrieval fails if session isn't authenticated", async () => {
mockVerifySession.mockResolvedValue({ isAuth: false });

const res = await GET();
const data = await res.json();

expect(data.error).toEqual('Invalid session');
});

test('Preference retrieval succeeds for valid session and returns appropriately', async () => {
mockVerifySession.mockResolvedValue({ isAuth: true, uid: 2 });

prismaMock.user.findFirst.mockResolvedValue({
id: 2,
createdAt: new Date(),
updatedAt: new Date(),
preferences: ['genre 1'],
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any);

const expectedGenres = ['genre 1'];

const res = await GET();
const data = await res.json();

expect(data.genres).toEqual(expectedGenres);
});
30 changes: 30 additions & 0 deletions backend/app/api/genre/me/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import prisma from '@/lib/prisma';
import { verifySession } from '@/lib/session';
import { ErrorResponse } from '@/lib/types';
import { Genre } from '@prisma/client';
import { NextResponse } from 'next/server';

type GetResponse = {
genres: Genre[];
};

export const GET = async (): Promise<
NextResponse<GetResponse | ErrorResponse>
> => {
const session = await verifySession();

if (!session.isAuth) {
return NextResponse.json({ error: 'Invalid session' });
}

const user = await prisma.user.findFirst({
where: {
id: session.uid,
},
include: {
preferences: true,
},
});

return NextResponse.json({ genres: user!.preferences });
};

0 comments on commit 12817cb

Please sign in to comment.