Skip to main content
Version: 3.x

graphql

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

createGraphQLModule

Create a GraphQL module.

Parameters

NameTypeDescription
namespacestringThe namespace of the GraphQL module
dependenciesstring[]The dependencies of the GraphQL module
loadRuntimefunctionThe import that will load GraphQL runtime
typeDefsstringThe GraphQL custom type definitions
schemaDirectivesobjectThe GraphQL custom directives
scalarsScalarMapExtends or overrides the built-in scalars and custom GraphQL scalars to a custom type.

Example

import { createGraphQLModule } from "@front-commerce/core/graphql";
import fooDirective from "./directives/fooDirective";

export default createGraphQLModule({
namespace: "MyModule",
dependencies: ["Front-Commerce/Payment"],
loadRuntime: () => import("./runtime"),
typeDefs: /* GraphQL */ `
extend type Query {
getFoo(input: AcmeScalar!): Foo
}
type Foo {
id: ID!
bar: Int
}
`,
schemaDirectives: {
fooDirective,
},
scalars: {
AcmeScalar: "string | number",
},
});

createGraphQLRuntime

Create a GraphQL runtime.

Parameters

NameTypeDescription
resolversobjectGraphQL resolvers
contextEnhancerfunction(context)function to enhance the GraphQL context

contextEnhancer function

The context enhancer function recieves the following arguments

ArgumentTypeDescription
configConfigThe application configuration
userUserThe actual user session
servicesServiceThe registered services
loaderLoaderLoaders registred in your application

Example

import { createGraphQLRuntime } from "@front-commerce/core/graphql";
import createFooContextEnhancer from "./createFooContextEnhancer";
import resolvers from "./resolvers";

export default createGraphQLRuntime({
resolvers: {
Query: {
getFoo: (_, __, { loaders }) => loaders.Foo.getFoo(),
},
},
contextEnhancer: ({ config, user, services, loader }) => {
return {
Foo: createFooContextEnhancer(config, user, services, loader),
};
},
});

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

limitRateByGraphQLResolver

Wraps a resolver with the rate limiting service.

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

export default {
Query: {
helloWorld: limitRateByGraphQLResolver(options, resolver),
},
};

Arguments:

ArgumentTypeDescription
options.maxnumberThe max request for duration
options.durationStringValueThe duration of the rate limiting
resolverFieldResolverThe resolver function