From 6b2e8a0471f15ecaadc3c290e0eafda8a35f8eb3 Mon Sep 17 00:00:00 2001 From: Enguerrand ARMINJON WINDOWS Date: Fri, 27 Sep 2024 21:26:36 +0200 Subject: [PATCH] feat: migrate date fields from string to Firestore Timestamp --- .gitignore | 3 +++ POSTINSTALL.md | 2 +- functions/src/index.ts | 27 +++++++++++++++++++++++++-- functions/src/types.ts | 8 +++++--- 4 files changed, 34 insertions(+), 6 deletions(-) diff --git a/.gitignore b/.gitignore index fdefdf8..15d8af3 100644 --- a/.gitignore +++ b/.gitignore @@ -67,3 +67,6 @@ node_modules/ # macOS system file .DS_store + +# IDE personal folder +.idea diff --git a/POSTINSTALL.md b/POSTINSTALL.md index f32835c..dffd5d9 100644 --- a/POSTINSTALL.md +++ b/POSTINSTALL.md @@ -67,7 +67,7 @@ getDoc(doc(db, "${param:REVENUECAT_CUSTOMERS_COLLECTION}", getAuth().currentUser .then((snapshot) => { if (snapshot.exists()) { snapshot.subscriptions - .filter(subscription => new Date(subscription.expires_date) >= new Date()) + .filter(subscription => subscription.expires_date.toDate() >= new Date()) .forEach(subscription => console.log(JSON.stringify(subscription))); } }); diff --git a/functions/src/index.ts b/functions/src/index.ts index cbe3a58..01ae470 100644 --- a/functions/src/index.ts +++ b/functions/src/index.ts @@ -44,6 +44,28 @@ const getCustomersCollection = ({ ); }; +const isIso8601Date = (str: string): boolean => moment(str, moment.ISO_8601, true).isValid(); + + +const convertDatesToTimestamps = (obj: any): any => { + if (typeof obj === 'string' && isIso8601Date(obj)) { + return admin.firestore.Timestamp.fromDate(moment(obj).toDate()); + } + + if (Array.isArray(obj)) { + return obj.map(convertDatesToTimestamps); + } + + if (obj !== null && typeof obj === 'object') { + return Object.entries(obj).reduce((acc, [key, value]) => { + acc[key] = convertDatesToTimestamps(value); + return acc; + }, {} as any); + } + + return obj; +}; + const writeToCollection = async ({ firestore, customersCollectionConfig, @@ -63,10 +85,11 @@ const writeToCollection = async ({ userId, }); - const payloadToWrite = { + // Recursively convert all date strings in the customerPayload to Timestamps + const payloadToWrite = convertDatesToTimestamps({ ...customerPayload, aliases, - }; + }); await customersCollection.doc(userId).set(payloadToWrite, { merge: true }); await customersCollection.doc(userId).update(payloadToWrite); diff --git a/functions/src/types.ts b/functions/src/types.ts index 8710e72..670becc 100644 --- a/functions/src/types.ts +++ b/functions/src/types.ts @@ -1,3 +1,5 @@ +import {firestore} from "firebase-admin"; + type EventType = | "INITIAL_PURCHASE" | "RENEWAL" @@ -12,10 +14,10 @@ type EventType = | "EXPIRATION"; interface Entitlement { - expires_date: string; - purchase_date: string; + expires_date: firestore.Timestamp; + purchase_date: firestore.Timestamp; product_identifier: string; - grace_period_expires_date: string; + grace_period_expires_date: firestore.Timestamp; } export interface CustomerInfo {