Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: the edge case problem #275

Merged
merged 2 commits into from
Mar 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 66 additions & 0 deletions src/actions/refresh-db/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
'use server';
import db from '@/db';
import { Cache } from '@/db/Cache';
import { getAllCourses } from '@/db/course';
import { checkUserEmailForPurchase } from '@/utiles/appx-check-mail';
import { Course } from '@prisma/client';

type RefreshDbFn = (args: { userId: string; email: string }) => Promise<{
error: boolean;
message: string;
}>;

export const refreshDb: RefreshDbFn = async ({ userId, email }) => {
// Only allow user to refetch every minute
if (Cache.getInstance().get('rate-limit', [userId])) {
return {
error: true,
message: 'Wait sometime before refetching',
};
}

const allCourses = (await getAllCourses()) as Course[];

// Check which course the user has purchased
const userCourses = await db.userPurchases.findMany({
where: {
userId,
},
});

const coursesWithoutUser = allCourses.filter((course) => {
return !userCourses.some((userCourse) => userCourse.courseId === course.id);
});

const responses: Course[] = [];

const promises = coursesWithoutUser
.filter((x) => !x.openToEveryone)
.map(async (course) => {
const courseId = course.appxCourseId.toString();
const data = await checkUserEmailForPurchase(email, courseId);
if (data.data === '1') {
responses.push(course);
}
});

await Promise.all(promises);

responses.forEach(async (res) => {
try {
await db.userPurchases.create({
data: {
userId,
courseId: res.id,
},
});
} catch {
return { error: true, message: 'Unable to insert courses' };
}
});

Cache.getInstance().evict('courses', [email]);
Cache.getInstance().set('rate-limit', [userId], true, 60);

return { error: false, message: 'Refetched Courses' };
};
40 changes: 22 additions & 18 deletions src/components/Courses.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,27 +3,31 @@
import { Course } from '@prisma/client';
import { CourseCard } from './CourseCard';
import { useRouter } from 'next/navigation';
import { RefreshDb } from './RefreshDb';

export const Courses = ({ courses }: { courses: Course[] }) => {
const router = useRouter();
return (
<div className="max-w-screen-xl w-full mx-auto py-6 px-6 cursor-pointer grid grid-cols-1 gap-5 md:grid-cols-3">
{courses?.map((course) => (
<CourseCard
key={course.id}
course={course}
onClick={() => {
if (
course.title.includes('Machine Learning') ||
course.title.includes('Harnoor')
) {
router.push('https://harkirat.classx.co.in/');
} else {
router.push(`/courses/${course.id}`);
}
}}
/>
))}
</div>
<section className="flex flex-col items-center w-full">
<div className="max-w-screen-xl w-full mx-auto py-6 px-6 cursor-pointer grid grid-cols-1 gap-5 md:grid-cols-3">
{courses?.map((course) => (
<CourseCard
key={course.id}
course={course}
onClick={() => {
if (
course.title.includes('Machine Learning') ||
course.title.includes('Harnoor')
) {
router.push('https://harkirat.classx.co.in/');
} else {
router.push(`/courses/${course.id}`);
}
}}
/>
))}
</div>
<RefreshDb />
</section>
);
};
31 changes: 31 additions & 0 deletions src/components/RefreshDb.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
'use client';
import { refreshDb } from '@/actions/refresh-db';
import { Button } from './ui/button';
import { toast } from 'sonner';
import { useSession } from 'next-auth/react';

export function RefreshDb() {
const session = useSession();
console.log(session);

const handleClick = async () => {
// @ts-ignore
const res = await refreshDb({ userId: session.data.user.id });
if (res.error) {
toast.error(res.message);
} else {
toast.info(res.message);
}
};

if (session.status === 'loading') return <>Loading...</>;

return (
<div className="flex flex-col gap-2">
<h1>Don't see all your courses?</h1>
<Button className="dark:text-white" onClick={handleClick}>
Refresh Database
</Button>
</div>
);
}
6 changes: 5 additions & 1 deletion src/db/Cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,5 +51,9 @@ export class Cache {
return entry.value;
}

evict() {}
evict(type: string, args: string[]) {
const key = `${type} ${JSON.stringify(args)}`;
this.inMemoryDb.delete(key);
return null;
}
}
24 changes: 24 additions & 0 deletions src/utiles/appx-check-mail.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
const APPX_AUTH_KEY = process.env.APPX_AUTH_KEY;
const APPX_CLIENT_SERVICE = process.env.APPX_CLIENT_SERVICE;
const APPX_BASE_API = process.env.APPX_BASE_API;

const baseUrl = `${APPX_BASE_API}/get/checkemailforpurchase`;

const headers = {
'Client-Service': APPX_CLIENT_SERVICE,
'Auth-Key': APPX_AUTH_KEY,
};

export async function checkUserEmailForPurchase(
email: string,
courseId: string,
) {
const params = new URLSearchParams({
email,
itemtype: '10',
itemid: courseId,
});
//@ts-ignore
const response = await fetch(`${baseUrl}?${params}`, { headers });
return await response.json();
}
22 changes: 3 additions & 19 deletions src/utiles/appx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,8 @@ import { Course } from '@/store/atoms';
import { getServerSession } from 'next-auth';
import { Cache } from '@/db/Cache';
import prisma from '@/db';
import { checkUserEmailForPurchase } from './appx-check-mail';

const APPX_AUTH_KEY = process.env.APPX_AUTH_KEY;
const APPX_CLIENT_SERVICE = process.env.APPX_CLIENT_SERVICE;
const APPX_BASE_API = process.env.APPX_BASE_API;
const LOCAL_CMS_PROVIDER = process.env.LOCAL_CMS_PROVIDER;

export async function getPurchases(email: string) {
Expand Down Expand Up @@ -86,27 +84,13 @@ export async function getPurchases(email: string) {
return allCourses;
}

const baseUrl = `${APPX_BASE_API}/get/checkemailforpurchase`;

const headers = {
'Client-Service': APPX_CLIENT_SERVICE,
'Auth-Key': APPX_AUTH_KEY,
};

const responses: Course[] = [];

const promises = courses
.filter((x) => !x.openToEveryone)
.map(async (course) => {
const params = new URLSearchParams({
email,
itemtype: '10',
itemid: course.appxCourseId.toString(),
});
//@ts-ignore
const response = await fetch(`${baseUrl}?${params}`, { headers });
const data = await response.json();

const courseId = course.appxCourseId.toString();
const data = await checkUserEmailForPurchase(email, courseId);
if (data.data === '1') {
responses.push(course);
}
Expand Down
Loading