2017-11-06 12 views
0

내 resolver에서 불필요한 호출을 피할 수있는 방법이 있는지 궁금합니다.캐시/아폴로 - 서버 해결 프로그램 응답을 재사용하는 방법

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();을 부를 것이다. 두 번 전화하는 것을 피할 수있는 방법이 있습니까? 동일한 요청 인 경우 "캐싱"과 유사합니까?

답변

0

동일한 유형의 필드에 대한 확인자는 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(), 그것은을 가져옵니다 가치와 그것을 메모리에 지속. 동일한 인스턴스에 대한 후속 호출은 메모리에서 값을 반환합니다.

+0

'type'과'bkFrom' /'bkTo'가 요청되지 않은 경우에도 getTo()와 getFrom()을 트리거 할 것입니다. 맞습니까? – Skaronator

+0

그래, 그건 그 접근 방식의 단점이야. 다른 아이디어를 보려면 편집을 참조하십시오. –