Apollo-client: Feature idea: Automatically remove `__typename` from mutations

Created on 15 Sep 2017  路  17Comments  路  Source: apollographql/apollo-client

I tend to do mutations like this a lot of the time:

// `data` comes from a query result
updateMutation({
  ...data,
  changedValue: "this is a changed value, the rest are the same",
})

This may look unusual, but let's assume that for some reason the database requires you to pass the entire object rather than just modified fields (e.g. a JSONB update)

However, unfortunately data has __typename automatically added to it, which my schema doesn't expect in a mutation!

I've written a helper function to strip __typename recursively just before the mutation is sent off:

const removeTypename = (value: any) => {
  if (value === null || value === undefined) {
    return value;
  } else if (Array.isArray(value)) {
    return value.map(v => removeTypename(v));
  } else if (typeof value === 'object') {
    const newObj = {};
    Object.entries(value).forEach(([key, v]) => {
      if (key !== '__typename') {
        newObj[key] = removeTypename(v);
      }
    });
    return newObj;
  }
  return value;
};

It could be cool if this were integrated into the client, but turned off by default.

What do you think? 馃檪

Most helpful comment

馃憤 This is still very relevant

All 17 comments

Why use a property like __typename instead of something like a symbol property that doesn't break mutations?

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions to Apollo Client!

This issue has been automatically closed because it has not had recent activity after being marked as stale. If you belive this issue is still a problem or should be reopened, please reopen it! Thank you for your contributions to Apollo Client!

馃憤 This is still very relevant

This can be realized through apollo links.

There are lots of people hitting this issue. This issue should definitely not be closed without explanation.

It is a cardinal sin for a library to modify incoming objects and expect developers to implement hacky, manual workarounds to deal with the modification.

Is there any intent for the maintainers to improve the situation?

@stubailo Is there an option/workaround for this currently?

I know in the client config you can specify not to include __typename, globally I believe, but I do need __typename sometimes. It would be nice to be able to specify to not include it per request (I'm using Apollo.client.mutate). There are lots of nested types sometimes. This issue comes up when updating data in stages, complex mutations, using the resulting data in the next mutation, etc.

_Edit_: This code I found on another issue works for me.

-> Is it possible to use an apollo-link only for certain queries?

```js

function createOmitTypenameLink() {
return new ApolloLink((operation, forward) => {
if (operation.variables) {
operation.variables = JSON.parse(JSON.stringify(operation.variables), omitTypename)
}

return forward(operation)

})
}

function omitTypename(key, value) {
return key === '__typename' ? undefined : value
}

@danderson00 How do you handle this finally?

@francoisromain Pretty much as in the code in the comment above by @sbrichardson.

Using @sbrichardson solution without more check breaks file upload from client side, be careful !

I am wondering why I get this error in the console:

Error: You are calling concat on a terminating link, which will have no effect
    at new LinkError (linkUtils.js:47)
    at concat (link.js:38)
    at ApolloLink../node_modules/apollo-link/lib/link.js.ApolloLink.concat (link.js:65)
    at link.js:13
    at Array.reduce (<anonymous>)
    at Function.from (link.js:13)
    at Object../src/graphql/ApolloClient.ts (ApolloClient.ts:20)
    at __webpack_require__ (bootstrap cc8125b9b24223eb2f2d:678)
    at fn (bootstrap cc8125b9b24223eb2f2d:88)
    at Object../src/graphql/index.ts (index.ts:1)
    at __webpack_require__ (bootstrap cc8125b9b24223eb2f2d:678)
    at fn (bootstrap cc8125b9b24223eb2f2d:88)
    at Object../src/containers/Albums.tsx (Albums.tsx:1)
    at __webpack_require__ (bootstrap cc8125b9b24223eb2f2d:678)
    at fn (bootstrap cc8125b9b24223eb2f2d:88)
    at Object../src/pages/AlbumList.tsx (AddAlbum.tsx:116)
    at __webpack_require__ (bootstrap cc8125b9b24223eb2f2d:678)
    at fn (bootstrap cc8125b9b24223eb2f2d:88)
    at Object../src/App.tsx (App.css?ef86:26)
    at __webpack_require__ (bootstrap cc8125b9b24223eb2f2d:678)
    at fn (bootstrap cc8125b9b24223eb2f2d:88)
    at Object../src/index.tsx (index.tsx:1)
    at __webpack_require__ (bootstrap cc8125b9b24223eb2f2d:678)
    at fn (bootstrap cc8125b9b24223eb2f2d:88)
    at Object.0 (album.ts:10)
    at __webpack_require__ (bootstrap cc8125b9b24223eb2f2d:678)
    at bootstrap cc8125b9b24223eb2f2d:724
    at bootstrap cc8125b9b24223eb2f2d:724

Here's my apollo client setup:

import { InMemoryCache, ApolloLink } from "apollo-boost";
import config from "./../config";
import { ApolloClient } from "apollo-client";
import { createUploadLink } from "apollo-upload-client";
const uploadLink = createUploadLink({
  uri: config.graphql.url
});

const createOmitTypenameLink = new ApolloLink((operation, forward) => {
  if (operation.variables) {
    operation.variables = JSON.parse(
      JSON.stringify(operation.variables),
      (key, value) => (key === "__typename" ? undefined : value)
    );
  }
  return forward ? forward(operation) : null;
});

export const apolloClient = new ApolloClient({
  link: ApolloLink.from([uploadLink, createOmitTypenameLink]),
  cache: new InMemoryCache()
});

It seems that createOmitTypenameLink doesn't work. any idea?

Using @sbrichardson solution without more check breaks file upload from client side, be careful !

@ValdoGhafoor, I'm handling file uploads separately because of the client batching issues with file uploads. I've been using for the last few months like this with no issues.

Partial example:

/**
 * Apollo Terminating link
 * The split will skip Batching if an
 * operation's context contains hasUpload = true value
 */
const httpLink = ApolloLink.split(
  o => o.getContext().hasUpload,
  createUploadLink(OPTS),
  ApolloLink.from([createOmitTypenameLink(), new BatchHttpLink(OPTS)])
)

@sbrichardson
I personnaly had to add two more "checks" :
One to check for circular dependencies in variables and one for files.
I personnally never had any issue with file upload

const cleanTypenameLink = new ApolloLink((operation, forward) => {
  const omitTypename = (key, value) => (key === '__typename' ? undefined : value);

  if (operation.variables && !operation.variables.file) {
    // eslint-disable-next-line
    operation.variables = CircularJSON.parse(CircularJSON.stringify(operation.variables), omitTypename);
  }

  return forward(operation);
});

slightly hacky: MyType { Id, SomeProps, __typename @include(if: false) }

I believe this is still relevant.

@sbrichardson
Your idea withgetContext() helped me finally solve it in my use case, as I couldn't keep checking for all unique variable nested objects for file uploads (in my case there was files, file, etc)

const cleanTypename = new ApolloLink((operation, forward) => {
    const omitTypename = (key, value) => (key === '__typename' ? undefined : value);

    if ((operation.variables && !operation.getContext().hasUpload)) {
        operation.variables = parse(stringify(operation.variables), omitTypename);
    }

    return forward(operation);
});

Then in the place where the mutation is called, I explicitly set the hasUploadcontext to true:

UpdateStation({variables: { input: station }, context: {hasUpload: true}).then()
Was this page helpful?
0 / 5 - 0 ratings