Skip to content

Commit

Permalink
feat: setup refresh option
Browse files Browse the repository at this point in the history
  • Loading branch information
devsargam committed Mar 25, 2024
1 parent 4333d9a commit 48493ce
Show file tree
Hide file tree
Showing 5 changed files with 129 additions and 20 deletions.
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' };
};
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

0 comments on commit 48493ce

Please sign in to comment.