当前位置: 首页>>代码示例>>TypeScript>>正文


TypeScript firestore.CollectionReference类代码示例

本文整理汇总了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;
    }
  }
开发者ID:StarshipVendingMachine,项目名称:android-play-billing,代码行数:64,代码来源:PurchasesManager.ts

示例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;
   }
 }
开发者ID:StarshipVendingMachine,项目名称:android-play-billing,代码行数:14,代码来源:PurchasesManager.ts

示例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);
        }
      }
    }
  }
开发者ID:StarshipVendingMachine,项目名称:android-play-billing,代码行数:60,代码来源:PurchasesManager.ts

示例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;
    }
  }
开发者ID:StarshipVendingMachine,项目名称:android-play-billing,代码行数:54,代码来源:UserManager.ts

示例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;
    }
  }
开发者ID:StarshipVendingMachine,项目名称:android-play-billing,代码行数:52,代码来源:PurchasesManager.ts


注:本文中的@google-cloud/firestore.CollectionReference类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。