question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

apollo-link-batch-http (batch) queries are not getting intercepted

See original GitHub issue

Environment

Name Version
msw 0.24.2
browser chrome Version 87.0.4280.88 (Official Build) (x86_64)
OS macOS Big Sur 11.0.1 (20B29)

Request handlers


export const handlers = [
  graphql.operation((req, res, ctx) => {
    console.log({ req, res, ctx });
    return res(
      ctx.data({
        user: {
          username: 'test',
          firstName: 'John',
        },
      })
    );
  }),

  graphql.query('getTest', (req, res, ctx) => {
    return res(
      ctx.data({
        user: {
          username: 'test',
          firstName: 'John',
        },
      })
    );
  }),
];

Actual request

https://www.apollographql.com/docs/link/links/batch-http/ Using Apollo Client to perform a normal batch query

ie.

import { BatchHttpLink } from "apollo-link-batch-http";
const link = new BatchHttpLink({ uri: "/graphql" });

Current behavior

batch queries are not getting intercepted but if I switch from BatchHttpLink to a regular HttpLink, the interception works as expected.

Expected behavior

batch queries get intercepted

Issue Analytics

  • State:open
  • Created 3 years ago
  • Reactions:2
  • Comments:21 (6 by maintainers)

github_iconTop GitHub Comments

5reactions
logaretmcommented, Mar 7, 2021

Hello, I maintain a GraphQL client for Vue.js and used the following workaround for the batched requests test.

As @antoniosZ pointed out, it requires intercepting it as a rest request, but I utilized the handlers you typically define earlier

export const handlers = [
  // some graphql handlers ...
  // add this to the end of GQL handlers
  rest.post('https://test.com/graphql', async (req, res) => {
    if (!Array.isArray(req.body)) {
      throw new Error('Unknown operation');
    }

    // map the requests to responses using their handlers
    const data = await Promise.all(
      req.body.map(async op => {
        const partReq = { ...req, body: op };
        const handler = handlers.find(h => h.test(partReq));
        // no handler matched that operation
        if (!handler) {
          return Promise.reject(new Error(`Cannot handle operation ${op}`));
        }

        // execute and return the response-like object
        return handler.run(partReq);
      })
    );

    return res(res => {
      res.headers.set('content-type', 'application/json');

      // responses need extraction from the individual requests
      // and we stitch them into a single array response
      res.body = JSON.stringify(
        data.map(d => {
          return JSON.parse(d?.response?.body) || {};
        })
      );

      return res;
    });
  }),
];

I realize this might not cover most cases, but works for me for now.

4reactions
kettanaitocommented, Mar 7, 2021

@msutkowski did some incredible job on the initial support phase. We’ve merged a major refactoring to how the request handlers work internally, so that pull request needs to be adjusted. I will try to resolve the conflicts and leave it at the same state for any volunteers to collaborate.

Thank you for your interest in this. We’d love to make batched operations support happen.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Batch HTTP Link - Apollo GraphQL Docs
The BatchHttpLink is a terminating link that batches an array of individual GraphQL operations into a single HTTP request that's sent to a...
Read more >
Migrating to Apollo Client 3.0
This article walks you through migrating your application to Apollo Client 3.0 from ... apollo-link-batch-http is now @apollo/client/link/batch-http ...
Read more >
Apollo batch http ( apollo-link-batch-http ) call creates multiple ...
Currently, my react app is making GraphQl call to endpoint /api/graphql and there are 9 individual http calls ( graphql queries ) going...
Read more >
sysgears/apollo-fullstack-starter-kit - Gitter
You can pass custom fetch implementation into apollo-link-batch-http : ... I only get some not so meaningful webpack errors not sure how to...
Read more >
Deep Dive into Apollo GraphQL Http Server | by E.Y. - Medium
Apollo Server accepts both GET and POST requests. ... Batching: a batch of queries can be sent by simply sending a JSON-encoded array...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found