Skip to main content
Version: 3.x

graphql

This documentation cover methods GraphQL-related APIs exposed by `@front-commerce/core`.

createGraphQLModule

Creates a GraphQL module and injects it into Front-Commerce's GraphQL server.

import { createGraphQLModule } from "@front-commerce/core/graphql";
import AcmeModule from "./acmeModule";

export default createGraphQLModule({
namespace: "Acme",
modules: [AcmeModule],
});
ArgumentTypeDescription
namespacestringThe namespace of the GraphQL module
modulesArray<GraphQLModule>The modules to inject in namespace

readGraphQLModules

Reads and parses GraphQLModules generated by codegen.

Example

import { readGraphQLModules } from "@front-commerce/core/graphql";

const generatedSchemaModules = await readGraphQLModules();

schema

Reads the generated GraphQL schema.

import { schema } from "@front-commerce/core/graphql";

const acmeSchema = await schema();

createGraphQLApi

Creates a GraphQL method to executes GraphQL queries and mutations.

import { createGraphQLApi } from "@front-commerce/core/graphql";
import { AcmeQuery } from "~/graphql/graphql";

const AcmeGraphQLApi = createGraphQLApi(request, user, config);

const response = await AcmeGraphQLApi(AcmeQuery);

Arguments:

ArgumentTypeDescription
requestRequestThe request object
userUserThe user context
configConfigThe application configuration

makeErrorLoggerInterceptor

Intercepts and log errors.

import { makeErrorLoggerInterceptor } from "@front-commerce/core/graphql";

const errorLoggerInterceptor = makeErrorLoggerInterceptor({
isMaintenance: (error) =>
error.response &&
(error.response.status === 503 ||
(error.response.status === 500 &&
/maintenance mode .* enabled/.test(error.response.data))),
ignoreForbiddenErrors: ignoreForbiddenErrors,
});

Arguments:

ArgumentTypeDescription
isMaintenancefunctiona function that recieve error as parameter and return a boolean to tell if website is in maintenance mode
ignoreForbiddenErrorsbooleana boolean to tell if forbidden errors
should be ignored

reorderForIds

Reorders an array by ids.

import { reorderForIds } from "@front-commerce/core/graphql";

const orderer = reorderForIds([2, 3, 1], "id");
const reordered = orderer([{ id: 1 }, { id: 2 }, { id: 3 }]);

Arguments:

ArgumentTypeDescription
idsstring[]ids to reorder
keystringkey used to order

reorderForIdsCaseInsensitive

Same as reorderForIds but case insensitive.

makeBatchLoaderFromSingleFetch

Converts a single fetch to a batch loader.

import { makeBatchLoaderFromSingleFetch } from "@front-commerce/core/graphql";

const axiosInstance = axios.create({
baseURL: "https://acme.com/api",
});

const acmeLoader = makeBatchLoaderFromSingleFetch(
(depth) => axiosInstance.get(`/prodcuts`),
(response) => response.data.products
);

Arguments:

ArgumentTypeDescription
fetchfunctionfetch function
responseobjectresponse transformer

maybeValue

Checks if a value is defined, else prints an axios debug message and returns null

import { maybeValue } from "@front-commerce/core/graphql";

const acmeValue = maybeValue(5, "value is not defined");

Arguments:

ArgumentTypeDescription
valueanyvalue to check
noValueDebugMessagestringdebug message

promiseToMutationSuccess

Converts a promise to a mutation success object with a success entry to know if the mutation was successful and a data entry that contains returned datas.

import { promiseToMutationSuccesData } from "@front-commerce/core/graphql";

const result = await promiseToMutationSuccesData(
axios.get("https://acme.com/api/products")
);

Arguments:

ArgumentTypeDescription
promisePromisepromise to execute

Returns:

PropertyTypeDescription
successbooleanmutation success
dataanydata returned

promiseToMutationSuccessWithData

Converts a promise to a mutation success object with a success entry to know if the mutation was successful and a data entry that contains returned transformed by data transformer.

import { promiseToMutationSuccesWithData } from "@front-commerce/core/graphql";

const result = await promiseToMutationSuccesWithData(
axios.get("https://acme.com/api/products"),
(data) => ({
id: product.id,
})
);

Arguments:

ArgumentTypeDescription
promisePromisepromise to evaluate
transformfunctiontransformation function

Returns an object

PropertyTypeDescription
successbooleanmutation success
dataanydata returned

withDefault404Result

Resolves a promise with defaultResult if the promise is rejected with a 404 code.

tip

This is mainly used for axios requests that throw an object with a response.status property. If you want to use it with a promise that doest not come from an axios request, your promise reject object must include a response.status property.

import { withDefault404Result } from "@front-commerce/core/graphql";

const result = await withDefault404Result(
axios.get("https://acme.com/api/products"),
[]
);

Arguments:

ArgumentTypeDescription
promisePromisepromise to evaluate
defaultResultanydefault result to return if the promise is rejected with a 404 code

RestPagesWalker

Retrieves all items from a paginated API.

import axios from "axios";
import { RestPagesWalker } from "@front-commerce/core/graphql";

const axiosInstance = axios.create({
baseURL: "https://acme.com/api",
});

const walker = RestPagesWalker(
axiosInstance,
{
url: "/products",
defaultParams: {
color: "blue",
size: "small",
},
pageParamName: "currentPage",
pageSizeParamName: "pageSize",
responseDataKey: "products",
},
(product) => product.id
);

const allData = await walker.walk();

Arguments:

ArgumentTypeDescription
axiosInstanceaxiosThe axios instance to use
urlstringThe API's url
defaultParamsobjectThe search params to use for request
pageParamNamestringThe name of the search param that contains the page
pageSizeParamNamestringThe name of the search param that contains the page size
responseDataKeystringThe response key that contains data
formatItemfunctionThe function to format each item

makePolymorphicGraphQLTypeLoader

Creates a GraphQL Type Loader that accept multiple types.

import { makePolymorphicGraphQLTypeLoader } from "@front-commerce/core/graphql";

const loader = makePolymorphicGraphQLTypeLoader({
name: "AcmeProduct",
defaultTypename: "NotFound",
});

Arguments:

ArgumentTypeDescription
namestringThe name of the type
defaultTypenamestringThe default typename

makePriceValue

Takes amount, currency and includeTax to create a GraphQL compatible Price type

import { makePriceValue } from "@front-commerce/core/graphql";

const priceValue = makePriceValue(100, "USD", false);

Arguments:

ArgumentTypeDescription
amountnumberThe price's amount.
currencystringThe price's currency
includeTaxbooleanDoes the price include tax