@apollo/client#DocumentNode TypeScript Examples

The following examples show how to use @apollo/client#DocumentNode. 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: CGraphQLClient.ts    From Cromwell with MIT License 6 votes vote down vote up
/** @internal */
    public createGetById<TEntity>(entityName: TDBEntity, nativeFragment: DocumentNode, nativeFragmentName: string) {
        const path = GraphQLPaths[entityName].getOneById;

        return (id: number, customFragment?: DocumentNode, customFragmentName?: string): Promise<TEntity | undefined> => {
            const fragment = customFragment ?? nativeFragment;
            const fragmentName = customFragmentName ?? nativeFragmentName;

            return this.query({
                query: gql`
              query core${path}($id: Int!) {
                  ${path}(id: $id) {
                      ...${fragmentName}
                  }
              }
              ${fragment}
          `,
                variables: {
                    id,
                }
            }, path);
        }
    }
Example #2
Source File: useBlockTimestampsDocument.ts    From mStable-apps with GNU Lesser General Public License v3.0 6 votes vote down vote up
useBlockTimestampsDocument = (dates: Date[]): DocumentNode =>
  useMemo(
    () => gql`query BlockTimestamps {
      ${dates
        .map(ts => {
          const unixTs = getUnixTime(ts)
          return `t${unixTs}: blocks(first: 1, orderBy: timestamp, orderDirection: asc, where: {timestamp_gt: ${unixTs}, timestamp_lt: ${
            unixTs + 60000
          } }) { number }`
        })
        .join('\n')}
  }`,
    [dates],
  )
Example #3
Source File: useDailyApysForBlockTimes.ts    From mStable-apps with GNU Lesser General Public License v3.0 6 votes vote down vote up
useDailyApysDocument = (savingsContractAddress: string | undefined, blockTimes: BlockTime[]): DocumentNode =>
  useMemo(() => {
    const withId = `where: { id: "${savingsContractAddress}" }`
    const currentApy = `t${nowUnix}: savingsContracts(${withId}) { ...DailySaveAPY }`
    const blockApys = blockTimes
      .map(
        ({ timestamp, number }) => `
              t${timestamp}: savingsContracts(${withId}, block: { number: ${number} }) {
                ...DailySaveAPY
              }`,
      )
      .join('\n')

    return gql`
      fragment DailySaveAPY on SavingsContract {
          dailyAPY
          utilisationRate {
              simple
          }
          latestExchangeRate {
              rate
          }
      }
      query DailyApys {
          ${currentApy}
          ${blockApys}
      }
  `
  }, [savingsContractAddress, blockTimes])
Example #4
Source File: useQuery.ts    From lexicon with MIT License 6 votes vote down vote up
export function useQuery<TData, TVariables = OperationVariables>(
  query: DocumentNode,
  options?: QueryHookOptions<TData, TVariables>,
  errorAlert: ErrorAlertOptionType = 'SHOW_ALERT',
): QueryResult<TData, TVariables> {
  const onErrorDefault = (error: ApolloError) => {
    errorHandlerAlert(error);
  };

  const { fetchPolicy = 'cache-and-network', ...others } = options ?? {};

  const {
    onError = errorAlert === 'SHOW_ALERT' ? onErrorDefault : undefined,
    nextFetchPolicy = fetchPolicy === 'cache-and-network'
      ? 'cache-first'
      : undefined,
    notifyOnNetworkStatusChange = fetchPolicy === 'network-only',
    ...otherOptions
  } = others;

  let queryResult = useQueryBase<TData, TVariables>(query, {
    fetchPolicy,
    nextFetchPolicy,
    notifyOnNetworkStatusChange,
    onError,
    ...otherOptions,
  });

  return queryResult;
}
Example #5
Source File: useMutation.ts    From lexicon with MIT License 6 votes vote down vote up
export function useMutation<TData, TVariables = OperationVariables>(
  query: DocumentNode,
  options?: MutationHookOptions<TData, TVariables>,
  errorAlert: ErrorAlertOptionType = 'SHOW_ALERT',
): MutationTuple<TData, TVariables> {
  const { navigate } = useNavigation<TabNavProp<'Home'>>();

  const onErrorDefault = (error: ApolloError) => {
    errorHandlerAlert(error, navigate);
  };

  const { ...others } = options ?? {};

  const {
    onError = errorAlert === 'SHOW_ALERT' ? onErrorDefault : undefined,
    ...otherOptions
  } = others;

  let [mutationFunction, mutationResult] = useMutationBase<TData, TVariables>(
    query,
    {
      onError,
      ...otherOptions,
    },
  );

  return [mutationFunction, mutationResult];
}
Example #6
Source File: useLazyQuery.ts    From lexicon with MIT License 6 votes vote down vote up
export function useLazyQuery<TData, TVariables = OperationVariables>(
  query: DocumentNode,
  options?: LazyQueryHookOptions<TData, TVariables>,
  errorAlert: ErrorAlertOptionType = 'SHOW_ALERT',
): QueryTuple<TData, TVariables> {
  const onErrorDefault = (error: ApolloError) => {
    errorHandlerAlert(error);
  };

  const { fetchPolicy = 'cache-and-network', ...others } = options ?? {};

  const {
    onError = errorAlert === 'SHOW_ALERT' ? onErrorDefault : undefined,
    nextFetchPolicy = fetchPolicy === 'cache-and-network'
      ? 'cache-first'
      : undefined,
    notifyOnNetworkStatusChange = fetchPolicy === 'network-only',
    ...otherOptions
  } = others;

  let [queryFunction, queryResult] = useLazyQueryBase<TData, TVariables>(
    query,
    {
      fetchPolicy,
      nextFetchPolicy,
      notifyOnNetworkStatusChange,
      onError,
      ...otherOptions,
    },
  );

  return [queryFunction, queryResult];
}
Example #7
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 #8
Source File: Apollo.ts    From graphql-ts-client with MIT License 6 votes vote down vote up
export function useTypedQuery<
    TData extends object,
    TVariables extends object
>( 
    fetcher: Fetcher<"Query", TData, TVariables>,
    options?: QueryHookOptions<TData, TVariables> & {
        readonly operationName?: string,
		readonly registerDependencies?: boolean | { readonly fieldDependencies: readonly Fetcher<string, object, object>[] }
	}
) : QueryResult<TData, TVariables> {

    const body = requestBody(fetcher);

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

	const [dependencyManager, config] = useContext(dependencyManagerContext);
	const register = options?.registerDependencies !== undefined ? !!options.registerDependencies : config?.defaultRegisterDependencies ?? false;
	if (register && dependencyManager === undefined) {
		throw new Error("The property 'registerDependencies' of options requires <DependencyManagerProvider/>");
	}
	useEffect(() => {
		if (register) {
			dependencyManager!.register(
				operationName, 
				fetcher, 
				typeof options?.registerDependencies === 'object' ? options?.registerDependencies?.fieldDependencies : undefined
			);
			return () => { dependencyManager!.unregister(operationName); };
		}// eslint-disable-next-line
	}, [register, dependencyManager, operationName, options?.registerDependencies, request]); // Eslint disable is required, becasue 'fetcher' is replaced by 'request' here.
	const response = useQuery<TData, TVariables>(request, options);
	const responseData = response.data;
	const newResponseData = useMemo(() => util.exceptNullValues(responseData), [responseData]);
	return newResponseData === responseData ? response : { ...response, data: newResponseData };
}
Example #9
Source File: createDeleteMutation.ts    From jmix-frontend with Apache License 2.0 6 votes vote down vote up
export function createDeleteMutationForSomeEntities(entityName: string, entityIds: string[]): DocumentNode | TypedDocumentNode {
  const graphqlSafeEntityName = dollarsToUnderscores(entityName);

  const deleteEntities = entityIds.map((entityId, index)=> `${graphqlSafeEntityName}${index}: delete_${graphqlSafeEntityName}(id: "${entityId}")`).join('\n')

  const mutationString = `
    mutation Delete_some_${graphqlSafeEntityName} {
      ${deleteEntities}
    }
  `;

  return gql(mutationString);
}
Example #10
Source File: createDeleteMutation.ts    From jmix-frontend with Apache License 2.0 6 votes vote down vote up
export function createDeleteMutation(entityName: string): DocumentNode | TypedDocumentNode {
  const graphqlSafeEntityName = dollarsToUnderscores(entityName);

  const mutationString = `
    mutation Delete_${graphqlSafeEntityName}($id: String!) {
      delete_${graphqlSafeEntityName}(id: $id)
    }
  `;

  return gql(mutationString);
}
Example #11
Source File: CGraphQLClient.ts    From Cromwell with MIT License 6 votes vote down vote up
public getCouponsByCodes = async (codes: string[],
        customFragment?: DocumentNode, customFragmentName?: string): Promise<TCoupon[] | undefined> => {
        const path = GraphQLPaths.Coupon.getCouponsByCodes;
        const fragment = customFragment ?? this.CouponFragment;
        const fragmentName = customFragmentName ?? 'CouponFragment';

        return this.query({
            query: gql`
                query coreGetCouponsByCodes($codes: String[]!) {
                    ${path}(codes: $codes, pagedParams: $pagedParams) {
                        ...${fragmentName}
                    }
                }
                ${fragment}
            `,
            variables: {
                codes,
            }
        }, path);
    }
Example #12
Source File: CGraphQLClient.ts    From Cromwell with MIT License 6 votes vote down vote up
public getOrdersOfUser = async (userId: number, pagedParams: TPagedParams<TOrder>,
        customFragment?: DocumentNode, customFragmentName?: string): Promise<TPagedList<TOrder> | undefined> => {
        const path = GraphQLPaths.Order.getOrdersOfUser;
        const fragment = customFragment ?? this.OrderFragment;
        const fragmentName = customFragmentName ?? 'OrderFragment';

        return this.query({
            query: gql`
                query coreGetOrdersOfUser($userId: Int!, $pagedParams: PagedParamsInput) {
                    ${path}(userId: $userId, pagedParams: $pagedParams) {
                        pagedMeta {
                            ...PagedMetaFragment
                        }
                        elements {
                            ...${fragmentName}
                        }
                    }
                }
                ${fragment}
                ${this.PagedMetaFragment}
            `,
            variables: {
                userId,
                pagedParams
            }
        }, path);
    }
Example #13
Source File: CGraphQLClient.ts    From Cromwell with MIT License 6 votes vote down vote up
public getUserByEmail = (email: string, customFragment?: DocumentNode, customFragmentName?: string): Promise<TUser | undefined> => {
        const path = GraphQLPaths.User.getOneByEmail;
        const fragment = customFragment ?? this.UserFragment;
        const fragmentName = customFragmentName ?? 'UserFragment';

        return this.query({
            query: gql`
              query core${path}($email: String!) {
                  ${path}(email: $email) {
                      ...${fragmentName}
                  }
              }
              ${fragment}
          `,
            variables: {
                email,
            }
        }, path);
    }
Example #14
Source File: CGraphQLClient.ts    From Cromwell with MIT License 6 votes vote down vote up
// < Generic CRUD >

    /** 
     * Get all records of a generic entity 
     * @auth admin
     */
    public getAllEntities = async <EntityType>(entityName: string, fragment: DocumentNode, fragmentName: string): Promise<EntityType[]> => {
        const path = GraphQLPaths.Generic.getMany + entityName;
        return this.query({
            query: gql`
                query coreGenericGetEntities {
                    ${path} {
                        ...${fragmentName}
                    }
                }
                ${fragment}
            `
        }, path);
    }
Example #15
Source File: CGraphQLClient.ts    From Cromwell with MIT License 6 votes vote down vote up
/** @internal */
    public createGetMany<TEntity>(entityName: TDBEntity, nativeFragment: DocumentNode, nativeFragmentName: string) {
        const path = GraphQLPaths[entityName].getMany;

        return (pagedParams?: TPagedParams<TEntity>, customFragment?: DocumentNode, customFragmentName?: string): Promise<TPagedList<TEntity>> => {
            const fragment = customFragment ?? nativeFragment;
            const fragmentName = customFragmentName ?? nativeFragmentName;

            return this.query({
                query: gql`
                    query core${path}($pagedParams: PagedParamsInput!) {
                        ${path}(pagedParams: $pagedParams) {
                            pagedMeta {
                                ...PagedMetaFragment
                            }
                            elements {
                                ...${fragmentName}
                            }
                        }
                    }
                    ${fragment}
                    ${this.PagedMetaFragment}
                `,
                variables: {
                    pagedParams: pagedParams ?? {},
                }
            }, path);
        }
    }
Example #16
Source File: CGraphQLClient.ts    From Cromwell with MIT License 6 votes vote down vote up
/** @internal */
    public createGetBySlug<TEntity>(entityName: TDBEntity, nativeFragment: DocumentNode, nativeFragmentName: string) {
        const path = GraphQLPaths[entityName].getOneBySlug;

        return (slug: string, customFragment?: DocumentNode, customFragmentName?: string): Promise<TEntity | undefined> => {
            const fragment = customFragment ?? nativeFragment;
            const fragmentName = customFragmentName ?? nativeFragmentName;

            return this.query({
                query: gql`
              query core${path}($slug: String!) {
                  ${path}(slug: $slug) {
                      ...${fragmentName}
                  }
              }
              ${fragment}
          `,
                variables: {
                    slug,
                }
            }, path);
        }
    }
Example #17
Source File: CGraphQLClient.ts    From Cromwell with MIT License 6 votes vote down vote up
/** @internal */
    public createUpdateEntity<TEntity, TInput>(entityName: TDBEntity, inputName: string, nativeFragment: DocumentNode, nativeFragmentName: string) {
        const path = GraphQLPaths[entityName].update;

        return (id: number, data: TInput, customFragment?: DocumentNode, customFragmentName?: string): Promise<TEntity> => {
            const fragment = customFragment ?? nativeFragment;
            const fragmentName = customFragmentName ?? nativeFragmentName;

            return this.mutate({
                mutation: gql`
                    mutation core${path}($id: Int!, $data: ${inputName}!) {
                        ${path}(id: $id, data: $data) {
                            ...${fragmentName}
                        }
                    }
                    ${fragment}
                `,
                variables: {
                    id,
                    data,
                }
            }, path);
        }
    }
Example #18
Source File: CGraphQLClient.ts    From Cromwell with MIT License 6 votes vote down vote up
/** @internal */
    public createCreateEntity<TEntity, TInput>(entityName: TDBEntity, inputName: string, nativeFragment: DocumentNode, nativeFragmentName: string) {
        const path = GraphQLPaths[entityName].create;

        return (data: TInput, customFragment?: DocumentNode, customFragmentName?: string): Promise<TEntity> => {
            const fragment = customFragment ?? nativeFragment;
            const fragmentName = customFragmentName ?? nativeFragmentName;

            return this.mutate({
                mutation: gql`
                mutation core${path}($data: ${inputName}!) {
                    ${path}(data: $data) {
                        ...${fragmentName}
                    }
                }
                ${fragment}
            `,
                variables: {
                    data,
                }
            }, path);
        }
    }
Example #19
Source File: CGraphQLClient.ts    From Cromwell with MIT License 6 votes vote down vote up
/** @internal */
    public createGetFiltered<TEntity, TFilter>(entityName: TDBEntity, nativeFragment: DocumentNode,
        nativeFragmentName: string, filterName: string, path?: string): ((options: TGetFilteredOptions<TEntity, TFilter>) => Promise<TPagedList<TEntity>>) {
        path = path ?? GraphQLPaths[entityName].getFiltered;

        return ({ pagedParams, filterParams, customFragment, customFragmentName }) => {
            const fragment = customFragment ?? nativeFragment;
            const fragmentName = customFragmentName ?? nativeFragmentName;

            return this.query({
                query: gql`
                query core${path}($pagedParams: PagedParamsInput, $filterParams: ${filterName}) {
                    ${path}(pagedParams: $pagedParams, filterParams: $filterParams) {
                        pagedMeta {
                            ...PagedMetaFragment
                        }
                        elements {
                            ...${fragmentName}
                        }
                    }
                }
                ${fragment}
                ${this.PagedMetaFragment}
            `,
                variables: {
                    pagedParams: pagedParams ?? {},
                    filterParams,
                }
            }, path as string);
        }
    }
Example #20
Source File: CGraphQLClient.ts    From Cromwell with MIT License 6 votes vote down vote up
/** 
    * Get filtered records of a generic entity 
    * @auth admin
    */
    public getFilteredEntities<TEntity, TFilter>(entityName: string, fragment: DocumentNode,
        fragmentName: string, options: TGetFilteredOptions<TEntity, TFilter>) {
        const path = GraphQLPaths.Generic.getFiltered + entityName;
        return this.createGetFiltered<TEntity, TBaseFilter>('Generic',
            fragment, fragmentName, 'BaseFilterInput', path)(options);
    }
Example #21
Source File: CGraphQLClient.ts    From Cromwell with MIT License 6 votes vote down vote up
public getRootCategories = async (customFragment?: DocumentNode, customFragmentName?: string): Promise<TPagedList<TProductCategory> | undefined> => {
        const path = GraphQLPaths.ProductCategory.getRootCategories;
        const fragment = customFragment ?? this.ProductCategoryFragment;
        const fragmentName = customFragmentName ?? 'ProductCategoryFragment';

        return this.query({
            query: gql`
            query coreGetRootCategories {
                ${path} {
                    pagedMeta {
                        ...PagedMetaFragment
                    }
                    elements {
                        ...${fragmentName}
                    }
                }
            }
            ${fragment}
            ${this.PagedMetaFragment}
        `,
        }, path);
    }
Example #22
Source File: CGraphQLClient.ts    From Cromwell with MIT License 6 votes vote down vote up
/** 
     * Get a record by id of a generic entity 
     * @auth admin
     */
    public getEntityById = async <EntityType>(entityName: string, fragment: DocumentNode, fragmentName: string, entityId: number)
        : Promise<EntityType | undefined> => {
        const path = GraphQLPaths.Generic.getOneById + entityName;
        return this.query({
            query: gql`
                query coreGenericGetEntityById($entityId: Int!) {
                    ${path}(id: $entityId) {
                        ...${fragmentName}
                    }
                }
                ${fragment}
            `,
            variables: {
                entityId,
            }
        }, path);
    }
Example #23
Source File: CGraphQLClient.ts    From Cromwell with MIT License 6 votes vote down vote up
/** 
     * Update a record of a generic entity 
     * @auth admin
     */
    public updateEntity = async <EntityType, EntityInputType>(entityName: string, entityInputName: string, fragment: DocumentNode,
        fragmentName: string, entityId: number, data: EntityInputType): Promise<EntityType | undefined> => {
        const path = GraphQLPaths.Generic.update + entityName;
        return this.mutate({
            mutation: gql`
                mutation coreGenericUpdateEntity($entityId: Int!, $data: ${entityInputName}!) {
                    ${path}(id: $entityId, data: $data) {
                        ...${fragmentName}
                    }
                }
                ${fragment}
            `,
            variables: {
                entityId,
                data,
            }
        }, path);
    }
Example #24
Source File: CGraphQLClient.ts    From Cromwell with MIT License 6 votes vote down vote up
/** 
     * Create a record by id of a generic entity 
     * @auth admin
     */
    public createEntity = async <EntityType, EntityInputType>(entityName: string, entityInputName: string, fragment: DocumentNode,
        fragmentName: string, data: EntityInputType): Promise<EntityType | undefined> => {
        const path = GraphQLPaths.Generic.create + entityName;
        return this.mutate({
            mutation: gql`
                mutation coreGenericCreateEntity($data: ${entityInputName}!) {
                    ${path}(data: $data) {
                        ...${fragmentName}
                    }
                }
                ${fragment}
            `,
            variables: {
                data,
            }
        }, path);
    }
Example #25
Source File: CGraphQLClient.ts    From Cromwell with MIT License 6 votes vote down vote up
public getProductsFromCategory = async (categoryId: number, pagedParams?: TPagedParams<TProduct>,
        customFragment?: DocumentNode, customFragmentName?: string): Promise<TPagedList<TProduct>> => {
        const path = GraphQLPaths.Product.getFromCategory;
        const fragment = customFragment ?? this.ProductFragment;
        const fragmentName = customFragmentName ?? 'ProductFragment';

        return this.query({
            query: gql`
                query coreGetProductsFromCategory($categoryId: Int!, $pagedParams: PagedParamsInput!) {
                    ${path}(categoryId: $categoryId, pagedParams: $pagedParams) {
                        pagedMeta {
                            ...PagedMetaFragment
                        }
                        elements {
                            ...${fragmentName}
                        }
                    }
                }
                ${fragment}
                ${this.PagedMetaFragment}
            `,
            variables: {
                pagedParams: pagedParams ?? {},
                categoryId
            }
        }, path);
    }
Example #26
Source File: CGraphQLClient.ts    From Cromwell with MIT License 6 votes vote down vote up
public getFilteredProducts = async (
        { pagedParams, filterParams, customFragment, customFragmentName }: {
            pagedParams?: TPagedParams<TProduct>;
            filterParams?: TProductFilter;
            customFragment?: DocumentNode;
            customFragmentName?: string;
        }): Promise<TFilteredProductList> => {
        const path = GraphQLPaths.Product.getFiltered;

        const fragment = customFragment ?? this.ProductFragment;
        const fragmentName = customFragmentName ?? 'ProductFragment';

        return this.query({
            query: gql`
                query getFilteredProducts($pagedParams: PagedParamsInput, $filterParams: ProductFilterInput) {
                    ${path}(pagedParams: $pagedParams, filterParams: $filterParams) {
                        pagedMeta {
                            ...PagedMetaFragment
                        }
                        filterMeta {
                            minPrice
                            maxPrice
                        }
                        elements {
                            ...${fragmentName}
                        }
                    }
                }
                ${fragment}
                ${this.PagedMetaFragment}
            `,
            variables: {
                pagedParams: pagedParams ?? {},
                filterParams,
            }
        }, path);
    }
Example #27
Source File: graphql.ts    From jmix-frontend with Apache License 2.0 5 votes vote down vote up
export function editorQueryIncludesRelationOptions(documentNode: DocumentNode | TypedDocumentNode): boolean {
  if (!('selectionSet' in documentNode.definitions[0])) {
    return false;
  }

  return documentNode.definitions[0].selectionSet.selections.length > 1;
}
Example #28
Source File: Apollo.ts    From graphql-ts-client with MIT License 5 votes vote down vote up
export function useTypedLazyQuery<
    TData extends object,
    TVariables extends object
>( 
    fetcher: Fetcher<"Query", TData, TVariables>,
    options?: QueryHookOptions<TData, TVariables> & {
        readonly operationName?: string,
		readonly registerDependencies?: boolean | { readonly fieldDependencies: readonly Fetcher<string, object, object>[] }
	}
) : QueryTuple<TData, TVariables> {

    const body = requestBody(fetcher);

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

	const [dependencyManager, config] = useContext(dependencyManagerContext);
	const register = options?.registerDependencies !== undefined ? !!options.registerDependencies : config?.defaultRegisterDependencies ?? false;
	if (register && dependencyManager === undefined) {
		throw new Error("The property 'registerDependencies' of options requires <DependencyManagerProvider/>");
	}
	useEffect(() => {
		if (register) {
			dependencyManager!.register(
				operationName, 
				fetcher, 
				typeof options?.registerDependencies === 'object' ? options?.registerDependencies?.fieldDependencies : undefined
			);
			return () => { dependencyManager!.unregister(operationName); };
		}// eslint-disable-next-line
	}, [register, dependencyManager, operationName, options?.registerDependencies, request]); // Eslint disable is required, becasue 'fetcher' is replaced by 'request' here.
	const response = useLazyQuery<TData, TVariables>(request, options);
	const responseData = response[1].data;
	const newResponseData = useMemo(() => util.exceptNullValues(responseData), [responseData]);
	return newResponseData === responseData ? response : [
        response[0],
        { ...response[1], data: newResponseData }
    ] as QueryTuple<TData, TVariables>;
}
Example #29
Source File: CategoryList.tsx    From Cromwell with MIT License 5 votes vote down vote up
CategoryList.withGetProps = (originalGetProps?: TGetStaticProps, options?: {
  customFragment?: DocumentNode;
  customFragmentName?: string;
}) => {
  const getProps: TGetStaticProps<GetStaticPropsData> = async (context) => {
    const originProps: any = (await originalGetProps?.(context)) ?? {};
    const contextSlug = context?.params?.slug;
    const slug = (contextSlug && typeof contextSlug === 'string') && contextSlug;
    const client = getGraphQLClient();

    const category = slug && (await client?.getProductCategoryBySlug(slug).catch((e: TGraphQLErrorInfo) => {
      if (e.statusCode !== 404)
        console.error(`CategoryList::getProps for slug ${slug} get category error: `, e);
    })) || null;

    if (!category) {
      return {
        notFound: true,
      }
    }

    const firstPage = category?.id && (await client?.getProductsFromCategory(category.id,
      { pageSize: 20 },
      options?.customFragment ?? gql`
        fragment ProductShortFragment on Product {
          id
          slug
          isEnabled
          name
          price
          oldPrice
          sku
          mainImage
          rating {
            average
            reviewsNumber
          }
        }`,
      options?.customFragmentName ?? 'ProductShortFragment'
    ).catch(e => {
      console.error(`CategoryList::getProps for slug ${slug} get firstPage error: `, e);
    })) || null;

    return {
      ...originProps,
      props: {
        ...(originProps.props ?? {}),
        ccom_category_list: removeUndefined({
          category,
          firstPage,
          slug,
        })
      }
    }
  }

  return getProps;
}