Skip to content

Commit

Permalink
Added api limits for a free user
Browse files Browse the repository at this point in the history
  • Loading branch information
hemantwasthere committed Jul 31, 2023
1 parent d33aa0a commit 7c65bfe
Show file tree
Hide file tree
Showing 10 changed files with 153 additions and 29 deletions.
12 changes: 6 additions & 6 deletions app/api/code/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { NextResponse } from "next/server";
import { ChatCompletionRequestMessage, Configuration, OpenAIApi } from "openai";

// import { checkSubscription } from "@/lib/subscription";
// import { incrementApiLimit, checkApiLimit } from "@/lib/api-limit";
import { incrementApiLimit, checkApiLimit } from "@/lib/api-limit";

const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
Expand Down Expand Up @@ -34,20 +34,20 @@ export async function POST(req: Request) {
return new NextResponse("Messages are required", { status: 400 });
}

// const freeTrial = await checkApiLimit();
const freeTrial = await checkApiLimit();
// const isPro = await checkSubscription();

// if (!freeTrial && !isPro) {
// return new NextResponse("Free trial has expired. Please upgrade to pro.", { status: 403 });
// }
if (!freeTrial) {
return new NextResponse("Free trial has expired. Please upgrade to pro.", { status: 403 });
}

const response = await openai.createChatCompletion({
model: "gpt-3.5-turbo",
messages: [instructionMessage, ...messages]
});

// if (!isPro) {
// await incrementApiLimit();
await incrementApiLimit();
// }

return NextResponse.json(response.data.choices[0].message);
Expand Down
11 changes: 6 additions & 5 deletions app/api/conversation/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { NextResponse } from "next/server";
import { Configuration, OpenAIApi } from "openai";

// import { checkSubscription } from "@/lib/subscription";
// import { incrementApiLimit, checkApiLimit } from "@/lib/api-limit";
import { incrementApiLimit, checkApiLimit } from "@/lib/api-limit";

const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
Expand All @@ -30,20 +30,21 @@ export async function POST(req: Request) {
return new NextResponse("Messages are required", { status: 400 });
}

// const freeTrial = await checkApiLimit();
const freeTrial = await checkApiLimit();
// const isPro = await checkSubscription();

// if (!freeTrial && !isPro) {
// return new NextResponse("Free trial has expired. Please upgrade to pro.", { status: 403 });
// }
if (!freeTrial) {
return new NextResponse("Free trial has expired. Please upgrade to pro.", { status: 403 });
}

const response = await openai.createChatCompletion({
model: "gpt-3.5-turbo",
messages
});

// if (!isPro) {
// await incrementApiLimit();
await incrementApiLimit();
// }

return NextResponse.json(response.data.choices[0].message);
Expand Down
12 changes: 6 additions & 6 deletions app/api/image/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { NextResponse } from "next/server";
import { Configuration, OpenAIApi } from "openai";

// import { checkSubscription } from "@/lib/subscription";
// import { incrementApiLimit, checkApiLimit } from "@/lib/api-limit";
import { incrementApiLimit, checkApiLimit } from "@/lib/api-limit";

const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
Expand Down Expand Up @@ -37,12 +37,12 @@ export async function POST(req: Request) {
return new NextResponse("Resolution is required", { status: 400 });
}

// const freeTrial = await checkApiLimit();
const freeTrial = await checkApiLimit();
// const isPro = await checkSubscription();

// if (!freeTrial && !isPro) {
// return new NextResponse("Free trial has expired. Please upgrade to pro.", { status: 403 });
// }
if (!freeTrial) {
return new NextResponse("Free trial has expired. Please upgrade to pro.", { status: 403 });
}

const response = await openai.createImage({
prompt,
Expand All @@ -51,7 +51,7 @@ export async function POST(req: Request) {
});

// if (!isPro) {
// await incrementApiLimit();
await incrementApiLimit();
// }

return NextResponse.json(response.data.data);
Expand Down
12 changes: 6 additions & 6 deletions app/api/music/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ import Replicate from "replicate";
import { auth } from "@clerk/nextjs";
import { NextResponse } from "next/server";

// import { incrementApiLimit, checkApiLimit } from "@/lib/api-limit";
// import { checkSubscription } from "@/lib/subscription";
import { incrementApiLimit, checkApiLimit } from "@/lib/api-limit";

const replicate = new Replicate({
auth: process.env.REPLICATE_API_TOKEN!,
Expand All @@ -23,12 +23,12 @@ export async function POST(req: Request) {
return new NextResponse("Prompt is required", { status: 400 });
}

// const freeTrial = await checkApiLimit();
const freeTrial = await checkApiLimit();
// const isPro = await checkSubscription();

// if (!freeTrial && !isPro) {
// return new NextResponse("Free trial has expired. Please upgrade to pro.", { status: 403 });
// }
if (!freeTrial) {
return new NextResponse("Free trial has expired. Please upgrade to pro.", { status: 403 });
}

const response = await replicate.run(
"riffusion/riffusion:8cf61ea6c56afd61d8f5b9ffd14d7c216c0a93844ce2d82ac1c9ecc9c7f24e05",
Expand All @@ -40,7 +40,7 @@ export async function POST(req: Request) {
);

// if (!isPro) {
// await incrementApiLimit();
await incrementApiLimit();
// }

return NextResponse.json(response);
Expand Down
12 changes: 6 additions & 6 deletions app/api/video/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import Replicate from "replicate";
import { auth } from "@clerk/nextjs";
import { NextResponse } from "next/server";

// import { incrementApiLimit, checkApiLimit } from "@/lib/api-limit";
import { incrementApiLimit, checkApiLimit } from "@/lib/api-limit";
// import { checkSubscription } from "@/lib/subscription";

const replicate = new Replicate({
Expand All @@ -23,12 +23,12 @@ export async function POST(req: Request) {
return new NextResponse("Prompt is required", { status: 400 });
}

// const freeTrial = await checkApiLimit();
const freeTrial = await checkApiLimit();
// const isPro = await checkSubscription();

// if (!freeTrial && !isPro) {
// return new NextResponse("Free trial has expired. Please upgrade to pro.", { status: 403 });
// }
if (!freeTrial) {
return new NextResponse("Free trial has expired. Please upgrade to pro.", { status: 403 });
}

const response = await replicate.run(
"anotherjesse/zeroscope-v2-xl:71996d331e8ede8ef7bd76eba9fae076d31792e4ddf4ad057779b443d6aea62f",
Expand All @@ -40,7 +40,7 @@ export async function POST(req: Request) {
);

// if (!isPro) {
// await incrementApiLimit();
await incrementApiLimit();
// }

return NextResponse.json(response);
Expand Down
57 changes: 57 additions & 0 deletions lib/api-limit.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { auth } from "@clerk/nextjs";

import prismadb from "@/lib/prismadb";
import { MAX_FREE_COUNTS } from "@/constants";

export const incrementApiLimit = async () => {
const { userId } = auth();

if (!userId) return

const userApiLimit = await prismadb.userApiLimit.findUnique({
where: { userId: userId },
});

if (userApiLimit) {
await prismadb.userApiLimit.update({
where: { userId: userId },
data: { count: userApiLimit.count + 1 },
});
} else {
await prismadb.userApiLimit.create({
data: { userId: userId, count: 1 },
});
}
};

export const checkApiLimit = async () => {
const { userId } = auth();

if (!userId) return false

const userApiLimit = await prismadb.userApiLimit.findUnique({
where: { userId: userId },
});

if (!userApiLimit || userApiLimit.count < MAX_FREE_COUNTS) {
return true;
} else {
return false;
}
};

export const getApiLimitCount = async () => {
const { userId } = auth();

if (!userId) return 0

const userApiLimit = await prismadb.userApiLimit.findUnique({
where: {
userId
}
});

if (!userApiLimit) return 0;

return userApiLimit.count;
};
10 changes: 10 additions & 0 deletions lib/prismadb.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { PrismaClient } from "@prisma/client";

declare global {
var prisma: PrismaClient | undefined
}

const prismadb = globalThis.prisma || new PrismaClient()
if (process.env.NODE_ENV !== "production") globalThis.prisma = prismadb

export default prismadb;
4 changes: 4 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
"dependencies": {
"@clerk/nextjs": "^4.23.1",
"@hookform/resolvers": "^3.1.1",
"@prisma/client": "^5.0.0",
"@radix-ui/react-avatar": "^1.0.3",
"@radix-ui/react-dialog": "^1.0.4",
"@radix-ui/react-icons": "^1.3.0",
Expand Down Expand Up @@ -40,5 +41,8 @@
"tailwindcss-animate": "^1.0.6",
"typescript": "5.1.6",
"typewriter-effect": "^2.20.1"
},
"devDependencies": {
"prisma": "^5.0.0"
}
}
28 changes: 28 additions & 0 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema

generator client {
provider = "prisma-client-js"
}

datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}

model UserApiLimit {
id String @id @default(cuid())
userId String @unique
count Int @default(0)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}

model UserSubscription {
id String @id @default(cuid())
userId String @unique
stripeCustomerId String? @unique @map(name: "stripe_customer_id")
stripeSubscriptionId String? @unique @map(name: "stripe_subscription_id")
stripePriceId String? @map(name: "stripe_price_id")
stripeCurrentPeriodEnd DateTime? @map(name: "stripe_current_period_end")
}
24 changes: 24 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -322,6 +322,23 @@
picocolors "^1.0.0"
tslib "^2.6.0"

"@prisma/client@^5.0.0":
version "5.0.0"
resolved "https://registry.yarnpkg.com/@prisma/client/-/client-5.0.0.tgz#9f0cd4164f4ffddb28bb1811c27eb7fa1e01a087"
integrity sha512-XlO5ELNAQ7rV4cXIDJUNBEgdLwX3pjtt9Q/RHqDpGf43szpNJx2hJnggfFs7TKNx0cOFsl6KJCSfqr5duEU/bQ==
dependencies:
"@prisma/engines-version" "4.17.0-26.6b0aef69b7cdfc787f822ecd7cdc76d5f1991584"

"@prisma/engines-version@4.17.0-26.6b0aef69b7cdfc787f822ecd7cdc76d5f1991584":
version "4.17.0-26.6b0aef69b7cdfc787f822ecd7cdc76d5f1991584"
resolved "https://registry.yarnpkg.com/@prisma/engines-version/-/engines-version-4.17.0-26.6b0aef69b7cdfc787f822ecd7cdc76d5f1991584.tgz#b36eda5620872d3fac810c302a7e46cf41daa033"
integrity sha512-HHiUF6NixsldsP3JROq07TYBLEjXFKr6PdH8H4gK/XAoTmIplOJBCgrIUMrsRAnEuGyRoRLXKXWUb943+PFoKQ==

"@prisma/[email protected]":
version "5.0.0"
resolved "https://registry.yarnpkg.com/@prisma/engines/-/engines-5.0.0.tgz#5249650eabe77c458c90f2be97d8210353c2e22e"
integrity sha512-kyT/8fd0OpWmhAU5YnY7eP31brW1q1YrTGoblWrhQJDiN/1K+Z8S1kylcmtjqx5wsUGcP1HBWutayA/jtyt+sg==

"@radix-ui/[email protected]":
version "1.0.1"
resolved "https://registry.yarnpkg.com/@radix-ui/number/-/number-1.0.1.tgz#644161a3557f46ed38a042acf4a770e826021674"
Expand Down Expand Up @@ -3086,6 +3103,13 @@ prelude-ls@^1.2.1:
resolved "https://registry.yarnpkg.com/prelude-ls/-/prelude-ls-1.2.1.tgz#debc6489d7a6e6b0e7611888cec880337d316396"
integrity sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==

prisma@^5.0.0:
version "5.0.0"
resolved "https://registry.yarnpkg.com/prisma/-/prisma-5.0.0.tgz#f6571c46dc2478172cb7bc1bb62d74026a2c2630"
integrity sha512-KYWk83Fhi1FH59jSpavAYTt2eoMVW9YKgu8ci0kuUnt6Dup5Qy47pcB4/TLmiPAbhGrxxSz7gsSnJcCmkyPANA==
dependencies:
"@prisma/engines" "5.0.0"

prop-types@^15.0.0, prop-types@^15.8.1:
version "15.8.1"
resolved "https://registry.yarnpkg.com/prop-types/-/prop-types-15.8.1.tgz#67d87bf1a694f48435cf332c24af10214a3140b5"
Expand Down

0 comments on commit 7c65bfe

Please sign in to comment.