Cleaning Unwanted Fields From GraphQL Responses

后端 未结 3 1483
梦如初夏
梦如初夏 2020-12-09 04:49

I have an object that my GraphQL client requests.

It\'s a reasonably simple object:

type Element {
    content: [ElementContent]
    elementId: Strin         


        
3条回答
  •  -上瘾入骨i
    2020-12-09 05:16

    Here's what I did, to support file uploads as well. It's a merge of multiple suggestions I found on the Github thread here: Feature idea: Automatically remove __typename from mutations

    import { parse, stringify } from 'flatted';
    
    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);
    });
    

    Hooking up the rest of my client.tsx file, simplified:

    import { InMemoryCache } from 'apollo-cache-inmemory';
    import { createUploadLink } from 'apollo-upload-client';
    import { ApolloClient } from 'apollo-client';
    import { setContext } from 'apollo-link-context';
    import { ApolloLink } from 'apollo-link';
    
    const authLink = setContext((_, { headers }) => {
        const token = localStorage.getItem(AUTH_TOKEN);
        return {
            headers: {
            ...headers,
            authorization: token ? `Bearer ${ token }` : '',
            },
        };
    });
    
    
    
    const httpLink = ApolloLink.from([
        cleanTypename,
        authLink.concat(upLoadLink),
    ]);
    
    const client = new ApolloClient({
        link: httpLink,
        cache,
    });
    
    export default client;
    

    Now when I call mutations that are of type upload, I simply set the context hasUpload to true, as shown here:

    UpdateStation({variables: { input: station }, context: {hasUpload: true }}).then()
    

提交回复
热议问题