Skip to content

Commit

Permalink
Merge pull request #34 from ArhanAnsari/ArhanAnsari-patch-1
Browse files Browse the repository at this point in the history
Update firebaseFunctions.ts
  • Loading branch information
ArhanAnsari authored Sep 21, 2024
2 parents a2057c1 + 6d3bcba commit 70337f5
Showing 1 changed file with 20 additions and 6 deletions.
26 changes: 20 additions & 6 deletions firebaseFunctions.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { db } from "./firebaseConfig";
import { doc, getDoc, updateDoc, increment } from "firebase/firestore";
import { doc, getDoc, updateDoc, setDoc, increment } from "firebase/firestore";

// Define the allowed plans as a union type
type Plan = "free" | "pro" | "enterprise";
Expand All @@ -17,17 +17,31 @@ const requestLimits: Record<Plan, number> = {
enterprise: Infinity, // Unlimited requests for enterprise plan
};

// Function to initialize user data in Firestore if not present
export const initializeUserData = async (email: string): Promise<void> => {
const userDocRef = doc(db, "users", email);
const userDoc = await getDoc(userDocRef);

if (!userDoc.exists()) {
await setDoc(userDocRef, {
plan: "free", // Default to the free plan
requestCount: 0, // Start with 0 requests
});
}
};

// Function to get user data from Firestore
export const getUserData = async (email: string): Promise<UserData | null> => {
try {
const userDocRef = doc(db, "users", email);
const userDoc = await getDoc(userDocRef);

if (!userDoc.exists()) {
return null; // No user data found
await initializeUserData(email); // Initialize the user data if it doesn't exist
return await getUserData(email); // Fetch the newly created data
}

return userDoc.data() as UserData; // Ensure the returned data matches UserData interface
return userDoc.data() as UserData;
} catch (error) {
console.error(`Error fetching user data for ${email}:`, error);
return null; // Return null if an error occurs
Expand All @@ -39,8 +53,8 @@ export const checkUserPlanLimit = async (email: string): Promise<boolean> => {
const userData = await getUserData(email);

if (!userData) {
console.warn(`No user data found for ${email}. Defaulting to free plan.`);
return false; // No user data found, assume no access
console.warn(`No user data found for ${email}.`);
return false;
}

const { plan, requestCount } = userData;
Expand All @@ -50,7 +64,7 @@ export const checkUserPlanLimit = async (email: string): Promise<boolean> => {
return false; // User has reached their limit
}

return true; // User can still generate content
return true;
};

// Function to increment the user's request count after each AI content generation
Expand Down

0 comments on commit 70337f5

Please sign in to comment.