Skip to content

Commit

Permalink
refactor: Optimize rate limiting checks in stream creation
Browse files Browse the repository at this point in the history
  • Loading branch information
Bot-Rakshit committed Aug 30, 2024
1 parent 6653ab9 commit 49546ab
Showing 1 changed file with 22 additions and 6 deletions.
28 changes: 22 additions & 6 deletions app/api/streams/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,17 +57,26 @@ export async function POST(req: NextRequest) {
const tenMinutesAgo = new Date(Date.now() - 10 * 60 * 1000);
const twoMinutesAgo = new Date(Date.now() - 2 * 60 * 1000);

const recentStreams = await prismaClient.stream.findMany({
const userRecentStreams = await prismaClient.stream.count({
where: {
userId: data.creatorId,
addedBy: user.id,
createAt: {
gte: tenMinutesAgo
}
}
});

// Check for duplicate song in the last 10 minutes
const duplicateSong = recentStreams.find(stream => stream.extractedId === extractedId);
const duplicateSong = await prismaClient.stream.findFirst({
where: {
userId: data.creatorId,
extractedId: extractedId,
createAt: {
gte: tenMinutesAgo
}
}
});
if (duplicateSong) {
return NextResponse.json({
message: "This song was already added in the last 10 minutes"
Expand All @@ -77,18 +86,25 @@ export async function POST(req: NextRequest) {
}

// Rate limiting checks for non-creator users
const userStreams = recentStreams.filter(stream => stream.addedBy === user.id);
const streamsLastTwoMinutes = userStreams.filter(stream => stream.createAt >= twoMinutesAgo);
const streamsLastTwoMinutes = await prismaClient.stream.count({
where: {
userId: data.creatorId,
addedBy: user.id,
createAt: {
gte: twoMinutesAgo
}
}
});

if (streamsLastTwoMinutes.length >= 2) {
if (streamsLastTwoMinutes >= 2) {
return NextResponse.json({
message: "Rate limit exceeded: You can only add 2 songs per 2 minutes"
}, {
status: 429
});
}

if (userStreams.length >= 5) {
if (userRecentStreams >= 5) {
return NextResponse.json({
message: "Rate limit exceeded: You can only add 5 songs per 10 minutes"
}, {
Expand Down

0 comments on commit 49546ab

Please sign in to comment.