本文整理匯總了TypeScript中@google-cloud/firestore.CollectionReference類的典型用法代碼示例。如果您正苦於以下問題:TypeScript CollectionReference類的具體用法?TypeScript CollectionReference怎麽用?TypeScript CollectionReference使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
在下文中一共展示了CollectionReference類的5個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的TypeScript代碼示例。
示例1: querySubscriptionPurchaseWithTrigger
/*
* Actual private information of querySubscriptionPurchase(packageName, sku, purchaseToken)
* It's expanded to support storing extra information only available via Realtime Developer Notification,
* such as latest notification type.
* - triggerNotificationType is only neccessary if the purchase query action is triggered by a Realtime Developer notification
*/
private async querySubscriptionPurchaseWithTrigger(packageName: string, sku: string, purchaseToken: string, triggerNotificationType?: NotificationType): Promise<SubscriptionPurchase> {
// STEP 1. Query Play Developer API to verify the purchase token
const apiResponse = await new Promise((resolve, reject) => {
this.playDeveloperApiClient.purchases.subscriptions.get({
packageName: packageName,
subscriptionId: sku,
token: purchaseToken
}, (err, result) => {
if (err) {
reject(this.convertPlayAPIErrorToLibraryError(err));
} else {
resolve(result.data);
}
})
});
try {
// STEP 2. Look up purchase records from Firestore which matches this purchase token
const purchaseRecordDoc = await this.purchasesDbRef.doc(purchaseToken).get();
// Generate SubscriptionPurchase object from Firestore response
const now = Date.now();
const subscriptionPurchase = SubscriptionPurchaseImpl.fromApiResponse(apiResponse, packageName, purchaseToken, sku, now);
// Store notificationType to database if queryPurchase was triggered by a realtime developer notification
if (triggerNotificationType !== undefined) {
subscriptionPurchase.latestNotificationType = triggerNotificationType;
}
// Convert subscriptionPurchase object to a format that to be stored in Firestore
const firestoreObject = subscriptionPurchase.toFirestoreObject();
if (purchaseRecordDoc.exists) {
// STEP 3a. We has this purchase cached in Firstore. Update our cache with the newly received response from Google Play Developer API
await purchaseRecordDoc.ref.update(firestoreObject);
// STEP 4a. Merge other fields of our purchase record in Firestore (such as userId) with our SubscriptionPurchase object and return to caller.
mergePurchaseWithFirestorePurchaseRecord(subscriptionPurchase, purchaseRecordDoc.data());
return subscriptionPurchase;
} else {
// STEP 3b. This is a brand-new subscription purchase. Just save the purchase record to Firestore
await purchaseRecordDoc.ref.set(firestoreObject);
if (subscriptionPurchase.linkedPurchaseToken) {
// STEP 4b. This is a subscription purchase that replaced other subscriptions in the past. Let's disable the purchases that it has replaced.
await this.disableReplacedSubscription(packageName, sku, subscriptionPurchase.linkedPurchaseToken);
}
// STEP 5. This is a brand-new subscription purchase. Just save the purchase record to Firestore and return an SubscriptionPurchase object with userId = null.
return subscriptionPurchase;
}
} catch (err) {
// Some unexpected error has occured while interacting with Firestore.
const libraryError = new Error(err.message);
libraryError.name = PurchaseQueryError.OTHER_ERROR;
throw libraryError;
}
}
示例2: forceRegisterToUserAccount
/*
* Force register a purchase to an user.
* This method is not intended to be called from outside of the library.
*/
private async forceRegisterToUserAccount(purchaseToken: string, userId: string): Promise<void> {
try {
await this.purchasesDbRef.doc(purchaseToken).update({ userId: userId });
} catch (err) {
// console.error('Failed to update purchase record in Firestore. \n', err.message);
const libraryError = new Error(err.message);
libraryError.name = PurchaseUpdateError.OTHER_ERROR;
throw libraryError;
}
}
示例3: disableReplacedSubscription
/*
* There are situations that a subscription is replaced by another subscription.
* For example, an user signs up for a subscription (tokenA), cancel its and re-signups (tokenB)
* We must disable the subscription linked to tokenA because it has been replaced by tokenB.
* If failed to do so, there's chance that a malicious user can have a single purchase registered to multiple user accounts.
*
* This method is used to disable a replaced subscription. It's not intended to be used from outside of the library.
*/
private async disableReplacedSubscription(packageName: string, sku: string, purchaseToken: string): Promise<void> {
console.log('Disabling purchase token = ', purchaseToken);
// STEP 1: Lookup the purchase record in Firestore
const purchaseRecordDoc = await this.purchasesDbRef.doc(purchaseToken).get();
if (purchaseRecordDoc.exists) {
// Purchase record found in Firestore. Check if it has been disabled.
if (purchaseRecordDoc.data().replacedByAnotherPurchase) {
// The old purchase has been. We don't need to take further action
return;
} else {
// STEP 2a: Old purchase found in cache, so we disable it
await purchaseRecordDoc.ref.update({ replacedByAnotherPurchase: true, userId: REPLACED_PURCHASE_USERID_PLACEHOLDER });
return;
}
} else {
// Purchase record not found in Firestore. We'll try to fetch purchase detail from Play Developer API to backfill the missing cache
const apiResponse = await new Promise((resolve, reject) => {
this.playDeveloperApiClient.purchases.subscriptions.get({
packageName: packageName,
subscriptionId: sku,
token: purchaseToken
}, async (err, result) => {
if (err) {
console.warn('Error fetching purchase data from Play Developer API to backfilled missing purchase record in Firestore. ', err.message);
// We only log an warning to console log as there is chance that backfilling is impossible.
// For example: after a subscription upgrade, the new token has linkedPurchaseToken to be the token before upgrade.
// We can't tell the sku of the purchase before upgrade from the old token itself, so we can't query Play Developer API
// to backfill our cache.
resolve();
} else {
resolve(result.data);
}
})
})
if (apiResponse) {
// STEP 2b. Parse the response from Google Play Developer API and store the purchase detail
const now = Date.now();
const subscriptionPurchase = SubscriptionPurchaseImpl.fromApiResponse(apiResponse, packageName, purchaseToken, sku, now);
subscriptionPurchase.replacedByAnotherPurchase = true; // Mark the purchase as already being replaced by other purchase.
subscriptionPurchase.userId = REPLACED_PURCHASE_USERID_PLACEHOLDER;
const firestoreObject = subscriptionPurchase.toFirestoreObject();
await purchaseRecordDoc.ref.set(firestoreObject);
// STEP 3. If this purchase has also replaced another purchase, repeating from STEP 1 with the older token
if (subscriptionPurchase.linkedPurchaseToken) {
await this.disableReplacedSubscription(packageName, sku, subscriptionPurchase.linkedPurchaseToken);
}
}
}
}
示例4: queryCurrentSubscriptions
/*
* Query subscriptions registered to a particular user, that are either active or in account hold.
* Note: Other subscriptions which don't meet the above criteria still exists in Firestore purchase records, but not accessible from outside of the library.
*/
async queryCurrentSubscriptions(userId: string, sku?: string, packageName?: string): Promise<Array<SubscriptionPurchase>> {
const purchaseList = new Array<SubscriptionPurchase>();
try {
// Create query to fetch possibly active subscriptions from Firestore
let query = this.purchasesDbRef
.where('formOfPayment', '==', GOOGLE_PLAY_FORM_OF_PAYMENT)
.where('skuType', '==', SkuType.SUBS)
.where('userId', '==', userId)
.where('isMutable', '==', true)
if (sku) {
query = query.where('sku', '==', sku);
}
if (packageName) {
query = query.where('packageName', '==', packageName);
}
// Do fetch possibly active subscription from Firestore
const queryResult = await query.get();
// Loop through these subscriptions and filter those that are indeed active
for (const purchaseRecordSnapshot of queryResult.docs) {
let purchase: SubscriptionPurchase = SubscriptionPurchaseImpl.fromFirestoreObject(purchaseRecordSnapshot.data())
if (!purchase.isEntitlementActive() && !purchase.isAccountHold()) {
// If a subscription purchase record in Firestore indicates says that it has expired,
// and we haven't confirmed that it's in Account Hold,
// and we know that its status could have been changed since we last fetch its details,
// then we should query Play Developer API to get its latest status
console.log('Updating cached purchase record for token = ', purchase.purchaseToken);
purchase = await this.purchaseManager.querySubscriptionPurchase(purchase.packageName, purchase.sku, purchase.purchaseToken);
}
// Add the updated purchase to list to returned to clients
if (purchase.isEntitlementActive() || purchase.isAccountHold()) {
purchaseList.push(purchase);
}
}
return purchaseList;
} catch (err) {
console.error('Error querying purchase records from Firestore. \n', err.message);
const libraryError = new Error(err.message);
libraryError.name = PurchaseQueryError.OTHER_ERROR;
throw libraryError;
}
}
示例5: queryOneTimeProductPurchase
/*
* Query a onetime product purchase by its package name, product Id (sku) and purchase token.
* The method queries Google Play Developer API to get the latest status of the purchase,
* then merge it with purchase ownership info stored in the library's managed Firestore database,
* then returns the merge information as a OneTimeProductPurchase to its caller.
*/
async queryOneTimeProductPurchase(packageName: string, sku: string, purchaseToken: string): Promise<OneTimeProductPurchase> {
// STEP 1. Query Play Developer API to verify the purchase token
const apiResponse = await new Promise((resolve, reject) => {
this.playDeveloperApiClient.purchases.products.get({
packageName: packageName,
productId: sku,
token: purchaseToken
}, (err, result) => {
if (err) {
reject(this.convertPlayAPIErrorToLibraryError(err));
} else {
resolve(result.data);
}
})
});
// STEP 2. Look up purchase records from Firestore which matches this purchase token
try {
const purchaseRecordDoc = await this.purchasesDbRef.doc(purchaseToken).get();
// Generate OneTimeProductPurchase object from Firestore response
const now = Date.now();
const onetimeProductPurchase = OneTimeProductPurchaseImpl.fromApiResponse(apiResponse, packageName, purchaseToken, sku, now);
// Attempt to save purchase record cache to Firestore
const firestoreObject = onetimeProductPurchase.toFirestoreObject();
if (purchaseRecordDoc.exists) {
// STEP 3a. We have this purchase cached in Firstore. Update our cache with the newly received response from Google Play Developer API
await purchaseRecordDoc.ref.update(firestoreObject);
// STEP 4a. Merge other fields of our purchase record in Firestore (such as userId) with our OneTimeProductPurchase object and return to caller.
mergePurchaseWithFirestorePurchaseRecord(onetimeProductPurchase, purchaseRecordDoc.data());
return onetimeProductPurchase;
} else {
// STEP 3b. This is a brand-new purchase. Save the purchase record to Firestore
await purchaseRecordDoc.ref.set(firestoreObject);
// STEP 4b. Return the OneTimeProductPurchase object.
return onetimeProductPurchase;
}
} catch (err) {
// Some unexpected error has occured while interacting with Firestore.
const libraryError = new Error(err.message);
libraryError.name = PurchaseQueryError.OTHER_ERROR;
throw libraryError;
}
}