ciekawy
ciekawy

Reputation: 2337

in the apollo-client how I may be able to log or intercept all the operations (queries and mutations)

For analytic purposes I'd like to keep track on the client side of all the graphql operations (including ie @client ones). I was unable to find appropriate options in the API and wonder if this may be doable on the apollo-client level or may I need to introduce some proxy to intercept the calls by my own?

Upvotes: 3

Views: 5267

Answers (2)

ciekawy
ciekawy

Reputation: 2337

As the answer from Yuriy was exactly what I was looking for I marked is as accepted answer - Thanks!

Still for the record here is the code doing a job for me - I believe someone may find it useful, also it is worth to show it's simplicity.

It's worth noting that Apollo links are chainable - thus the argument to a link function are operation: Operation and forward: NextLink which is supposed to be called from our link implementation.

let analytics: Analytics; // this is Fabric.io Analytics to be provided by DI
const analyticsLink = new ApolloLink((
    operation: Operation,
    forward?: NextLink
) => {
    const operationType = operation.query.definitions[0].operation;
    return forward(operation)
        .map((result: FetchResult) => {
            try {
                analytics.sendCustomEvent(`${operationType}.${operation.operationName}`);
            } catch (e) {
                console.error('analytics error', e);
            }
            return result;
        });
});

as a bonus we can also catch errors (i.e. to leverage fabric.io crashlytics) by using apollo-link-error (handling of errors in Apollo is a bit more complex);

const analyticsErrorLink = onError((error: ErrorResponse) => {
    try {
        // it's worth to rethink what we wanna log here
        const message = error.graphQLErrors ? error.graphQLErrors[0].message :
            (error.networkError.name + ': ' + error.networkError.message);
        analytics.sendNonFatalCrash('GraphQL error: ' + message);
    } catch(e) {
        console.error('cannot report error to analytics', e);
    }
});

Finally to compose the links we should put our intercepting implementations at the beginning so we will be able to catch all the GraphQL operations including those marked with @client which are not reaching network link - in my case full link looks like:

ApolloLink.from([
    analyticsErrorLink,
    analyticsLink,
    stateLink,
    auth,
    http])

Upvotes: 2

Yuriy Rypka
Yuriy Rypka

Reputation: 2107

A custom Apollo link is a way to go.

You can use apollo-link-logger in particular to log all operations to console.

Usage (from docs):

import apolloLogger from 'apollo-link-logger';

// ...
ApolloLink.from([
  apolloLogger,
  // ...
]);

Note: Place apolloLogger before other links.

Output example:

enter image description here

Upvotes: 3

Related Questions