2017-11-06 6 views
0

リゾルバで不要な呼び出しを避ける方法があるのだろうかと思います。apollo-serverリゾルバの応答をキャッシュ/再利用する方法

私のリゾルバは次のようになります(最小化)

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();を呼び出します。それらを2回呼び出すことを避ける方法はありますか?同じリクエストの場合は "キャッシング"と同じですか?同じ型のフィールドのための

答えて

0

リゾルバが並列に実行されようとしているので、typeするレゾルバはbkFromするレゾルバはに解決するものを知る方法はありません。私はこれを処理する最善の方法は、ロジックを1レベル上に移動して、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()は、それがフェッチされますそれをメモリに保存します。これ以降の呼び出し(同じインスタンスの場合)では、メモリから値が返されます。

+0

これは、 'type'と' bkFrom'/'bkTo'がリクエストされていなくても、getTo()とgetFrom()を起動します。 – Skaronator

+0

ええ、それはそのアプローチの欠点です。別のアイデアについては編集を参照してください。 –

関連する問題