Apollo-server: apollo-datasource-rest and avoid loading the same object multiple times during a single GraphQL request

Created on 1 Mar 2019  路  3Comments  路  Source: apollographql/apollo-server

I understand that while dataloader use case is more related for batching however its helpfull also since it avoids loading the same object multiple times during a single GraphQL request.
And i can't figure out how if possible at all doing the same with apollo-datasource-rest take for example the sample query

{
  usera:user(id: 184) {
    username,

  }

  userb: user(id: 184) {
    username
  }
}

assuming user data comes from a REST endpoint,
using a DataLoader would make a single request for this example while with datasource-rest it would make two assuming the REST api doesn't send any http cache headers, am i missing something here.

Most helpful comment

apollo-datasource-rest will always cache requests to REST APIs made during a single GraphQL request, irrespective of the caching headers. If this is not the behavior you're seeing, please reopen this issue and include a reproduction.

All 3 comments

apollo-datasource-rest will always cache requests to REST APIs made during a single GraphQL request, irrespective of the caching headers. If this is not the behavior you're seeing, please reopen this issue and include a reproduction.

So it means that I don鈥檛 need to use data loader if I use Apollo datasource rest. Am I right? We say, two fields use the same API at resolver, when Gql resolves the scheme type which contains the two fields. Is there only a single restful api call? Thanks.

@AlexSun98 You're exactly right. When the first request is made, its promise is immediately put into cache:

https://github.com/apollographql/apollo-server/blob/815c77afe847c84a1215f06b06e188eba2a2f8d2/packages/apollo-datasource-rest/src/RESTDataSource.ts#L272-L274

When the second resolver runs, the same promise is returned immediately, without making another HTTP request:

https://github.com/apollographql/apollo-server/blob/815c77afe847c84a1215f06b06e188eba2a2f8d2/packages/apollo-datasource-rest/src/RESTDataSource.ts#L269-L270

Was this page helpful?
0 / 5 - 0 ratings