Skip to content

Commit

Permalink
Add algorithm for recommending songs to users
Browse files Browse the repository at this point in the history
  • Loading branch information
Advayp committed Feb 2, 2025
1 parent c1b231c commit 94faf75
Show file tree
Hide file tree
Showing 2 changed files with 76 additions and 0 deletions.
65 changes: 65 additions & 0 deletions backend/app/api/songs/recommendations/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import { verifySession } from '@/lib/session';
import { ErrorResponse } from '@/lib/types';
import { Song } from '@prisma/client';
import { NextRequest, NextResponse } from 'next/server';
import prisma from '@/lib/prisma';
import { getRandomSegment } from '@/lib/misc';

type GetResponse = {
songs: Song[];
};

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

const searchParams = new URL(req.url).searchParams;
const size = searchParams.get('size');

if (!size) {
return NextResponse.json({ error: 'Size is required' }, { status: 400 });
}

if (!session.isAuth) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}

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

if (!user) {
return NextResponse.json({ error: 'User not found' }, { status: 404 });
}

const songs = await prisma.song.findMany({
where: {
seenBy: {
none: {
id: session.uid,
},
},
genre: {
value: {
in: user.preferences.map((preference) => preference.value),
},
},
},
include: {
genre: true,
seenBy: true,
},
});

console.log('Songs found:', songs.length);

return NextResponse.json({
songs: getRandomSegment(songs, parseInt(size)),
});
};
11 changes: 11 additions & 0 deletions backend/lib/misc.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
export const getRandomSegment = <T>(arr: T[], n: number): T[] => {
const result: T[] = [];
const indices: Set<number> = new Set();

while (indices.size < n && indices.size < arr.length) {
indices.add(Math.floor(Math.random() * arr.length));
}

indices.forEach((i) => result.push(arr[i]));
return result;
};

0 comments on commit 94faf75

Please sign in to comment.