代码之家  ›  专栏  ›  技术社区  ›  Skaronator Jyothi Babu Araja

如何缓存/重用apollo server resolver响应

  •  0
  • Skaronator Jyothi Babu Araja  · 技术社区  · 8 年前

    我想知道是否有一种方法可以避免在我的解析器中进行不必要的调用。

    我的解析器如下所示:(最小化)

    Transaction: {
      bkFrom(transaction) {
        return transaction.getFrom(); //<-- CACHE THIS?
      },
      bkTo(transaction) {
        return transaction.getTo(); //<-- CACHE THIS?
      },
      type(transaction) {
        return new Promise(async function(resolve, reject) {
          const [From, To] = await Promise.all([
            transaction.getFrom(), //<-- CACHE THIS? If bkFrom() is already triggered
            transaction.getTo(),  //<-- CACHE THIS? If is bkTo() already triggered
          ]);
          switch (true) {
            case From.isKonto && To.isKonto:
              resolve(TransactionType.INTERN);
            case !From.isKonto && To.isKonto:
              resolve(TransactionType.INCOMING);
            case From.isKonto && !To.isKonto:
              resolve(TransactionType.OUTGOING);
            default:
              resolve(null);
          }
        });
      },
    },
    

    getTansactions(limit: 10) {
        type
        bkFrom {
          id
          name
          isKonto
        }
        bkTo {
          id
          name
          isKonto
        }
      }
    

    它会呼叫 transaction.getFrom(); transaction.getTo(); 两次有没有办法避免给他们打两次电话?如果它来自同一个请求,比如“缓存”?

    1 回复  |  直到 8 年前
        1
  •  0
  •   Daniel Rearden    8 年前

    同一类型字段的解析器将并行执行,因此 type 无法知道解析程序的用途 bkFrom 已决定。我认为处理这个问题的最好方法是将逻辑向上移动一级,进入解析器 getTansactions .

    getTransactions: async () {
      // Get the transactions first
      const transactions = await someCallToGetTransactions()
      // Grab all our additional calls and use Promise.all to call them concurrently
      const promises = transactions.reduce((memo, t) => {
        memo.push(t.getTo())
        memo.push(t.getFrom())
        return memo
      }, [])
      const toFrom = await Promise.all(promises)
      // Merge the results into one array
      return transactions.map((t, index) => {
        const bkTo = toFrom[index * 2]
        const bkFrom = toFrom[(index * 2) + 1]
        const type = getType(bkTo, bkFrom) //calculate type from your other fields
        return Object.assign({}, t, { bkTo, bkFrom, type })
      })
    }
    

    或者,您可以返回事务类的实例,并缓存 getTo() getFrom() 这样:

    class Transaction {
      async getTo () {
        if (!this._to) {
          this._to = await //whatever
        }
        return this._to
      }
    }
    

    这样,第一次 getTo() 调用时,它将获取值并将其保存在内存中。对它的任何后续调用(对于同一实例)都只会从内存中返回值。