@apollo/client#ApolloCache TypeScript Examples

The following examples show how to use @apollo/client#ApolloCache. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: useDeleteBtnCallback.ts    From jmix-frontend with Apache License 2.0 6 votes vote down vote up
function defaultOnConfirm<
  TEntity,
  TData,
  TVariables extends HasId = HasId
  >(
  entityInstance: EntityInstance<TEntity, HasId>,
  executeDeleteMutation: GraphQLMutationFn<TData, TVariables>,
  queryName: string
) {
  return () => {
    if (entityInstance.id != null) {
      // noinspection JSIgnoredPromiseFromCall
      executeDeleteMutation({
        variables: { id: entityInstance.id } as TVariables,
        update(cache: ApolloCache<TData>) {
          // Remove deleted item from cache
          cache.modify({
            fields: {
              [queryName](existingRefs, { readField }) {
                return existingRefs.filter(
                  (ref: Reference) => entityInstance.id !== readField("id", ref)
                );
              }
            }
          });
        }
      });
    }
  };
}
Example #2
Source File: Apollo.ts    From graphql-ts-client with MIT License 6 votes vote down vote up
export function useTypedMutation<
    TData extends object,
    TVariables extends object,
    TContext = DefaultContext, 
	TCache extends ApolloCache<any> = ApolloCache<any>
>(
    fetcher: Fetcher<"Mutation", TData, TVariables>,
    options?: MutationHookOptions<TData, TVariables, TContext> & {
        readonly operationName?: string
	}
): MutationTuple<
    TData, 
    TVariables, 
    TContext, 
    TCache
> {
    const body = requestBody(fetcher);

    const request = useMemo<DocumentNode>(() => {
		const operationName = options?.operationName ?? `mutation_${util.toMd5(body)}`;
		return gql`mutation ${operationName}${body}`;
	}, [body, options?.operationName]);

	const response = useMutation<
		TData, 
		TVariables, 
		TContext, 
		TCache
	>(request, options);
	const responseData = response[1].data;
	const newResponseData = useMemo(() => util.exceptNullValues(responseData), [responseData]);
	return newResponseData === responseData ? response : [
        response[0],
        { ...response[1], data: newResponseData }
    ];
}
Example #3
Source File: UpdootSection.tsx    From lireddit with MIT License 6 votes vote down vote up
updateAfterVote = (
  value: number,
  postId: number,
  cache: ApolloCache<VoteMutation>
) => {
  const data = cache.readFragment<{
    id: number;
    points: number;
    voteStatus: number | null;
  }>({
    id: "Post:" + postId,
    fragment: gql`
      fragment _ on Post {
        id
        points
        voteStatus
      }
    `,
  });

  if (data) {
    if (data.voteStatus === value) {
      return;
    }
    const newPoints =
      (data.points as number) + (!data.voteStatus ? 1 : 2) * value;
    cache.writeFragment({
      id: "Post:" + postId,
      fragment: gql`
        fragment __ on Post {
          points
          voteStatus
        }
      `,
      data: { points: newPoints, voteStatus: value },
    });
  }
}
Example #4
Source File: Apollo.ts    From jmix-frontend with Apache License 2.0 5 votes vote down vote up
export function initializeApolloClient<TCacheShape>(config: JmixApolloConfig<TCacheShape> = {}): ApolloClient<TCacheShape> {

  const {
    customApolloOptions = {},
    storage = window.localStorage,
    graphqlEndpoint = '/graphql',
    // TODO Rename to jmixAccessToken once REST is dropped
    tokenStorageKey = 'jmixRestAccessToken',
    localeStorageKey = 'jmixLocale'
  } = config;

  const uploadLink = createUploadLink({
    uri: graphqlEndpoint
  });

  const authLink = setContext((_, { headers }) => {
    const token = storage.getItem(tokenStorageKey);
    const locale = storage.getItem(localeStorageKey);
    return {
      headers: {
        ...headers,
        authorization: token ? `Bearer ${token}` : "",
        'Accept-Language': locale
      }
    };
  });

  return new ApolloClient<TCacheShape>({
    link: authLink.concat(uploadLink),
    cache: new InMemoryCache({
      addTypename: false
    }) as unknown as ApolloCache<TCacheShape>,
    defaultOptions: {
      query: {
        fetchPolicy: 'network-only'
      },
      watchQuery: {
        fetchPolicy: "cache-and-network"
      }
    },
    ...customApolloOptions
  });
}
Example #5
Source File: persistEntity.ts    From jmix-frontend with Apache License 2.0 5 votes vote down vote up
export function persistEntity<
  TEntity = unknown,
  TData extends Record<string, any> = Record<string, any>,
  TVariables = unknown
  >(
  upsertItem: GraphQLMutationFn<TData, TVariables>,
  upsertInputName: string,
  updatedEntity: TEntity,
  updateResultName: string,
  listQueryName: string,
  entityName: string,
  isNewEntity: boolean,
  goToParentScreen: () => void,
  metadata: Metadata,
  persistEntityCallbacks?: PersistEntityCallbacks
) {
  upsertItem({
    variables: {
      [upsertInputName]: jmixFront_to_jmixGraphQL(updatedEntity, entityName, metadata)
    } as any,
    update(cache: ApolloCache<TData>, result: FetchResult<TData>) {
      const updateResult = result.data?.[updateResultName];
      // Reflect the update in Apollo cache
      cache.modify({
        fields: {
          [listQueryName](existingRefs = []) {
            const updatedItemRef = cache.writeFragment({
              id: `${entityName}:${updateResult.id}`,
              data: updatedEntity,
              fragment: gql(`
                      fragment New_${dollarsToUnderscores(entityName)} on ${dollarsToUnderscores(entityName)} {
                        id
                        type
                      }
                    `)
            });
            return [...existingRefs, updatedItemRef];
          }
        }
      });
    }
  }).then(action(({errors}: FetchResult<TData, Record<string, any>, Record<string, any>>) => {
    if (errors == null || errors.length === 0) {
      isNewEntity ? persistEntityCallbacks?.onCreate?.() : persistEntityCallbacks?.onEdit?.()
      goToParentScreen();
    } else {
      console.error(errors);
      persistEntityCallbacks?.onError?.();
    }
  }))
    .catch((e: Error | ApolloError) => {
      const constraintViolations = (e as ApolloError)
        ?.graphQLErrors
        ?.[0]
        ?.extensions
        ?.constraintViolations;
      if (constraintViolations != null) {
        return; // Bean validation error
      }

      console.error(e);
      persistEntityCallbacks?.onError?.();
    });
}