graphql
This documentation cover methods GraphQL-related APIs exposed by `@front-commerce/core`.
createGraphQLModule
Create a GraphQL module.
Parameters
Name | Type | Description |
---|---|---|
namespace | string | The namespace of the GraphQL module |
dependencies | string[] | The dependencies of the GraphQL module |
loadRuntime | function | The import that will load GraphQL runtime |
typeDefs | string | The GraphQL custom type definitions |
schemaDirectives | object | The GraphQL custom directives |
scalars | ScalarMap | Extends 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
Name | Type | Description |
---|---|---|
resolvers | object | GraphQL resolvers |
contextEnhancer | function(context) | function to enhance the GraphQL context |
contextEnhancer
function
The context enhancer function recieves the following arguments
Argument | Type | Description |
---|---|---|
config | Config | The application configuration |
user | User | The actual user session |
services | Service | The registered services |
loader | Loader | Loaders 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:
Argument | Type | Description |
---|---|---|
request | Request | The request object |
user | User | The user context |
config | Config | The 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:
Argument | Type | Description |
---|---|---|
isMaintenance | function | a function that recieve error as parameter and return a boolean to tell if website is in maintenance mode |
ignoreForbiddenErrors | boolean | a 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:
Argument | Type | Description |
---|---|---|
ids | string[] | ids to reorder |
key | string | key 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:
Argument | Type | Description |
---|---|---|
fetch | function | fetch function |
response | object | response 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:
Argument | Type | Description |
---|---|---|
value | any | value to check |
noValueDebugMessage | string | debug 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:
Argument | Type | Description |
---|---|---|
promise | Promise | promise to execute |
Returns:
Property | Type | Description |
---|---|---|
success | boolean | mutation success |
data | any | data 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:
Argument | Type | Description |
---|---|---|
promise | Promise | promise to evaluate |
transform | function | transformation function |
Returns an object
Property | Type | Description |
---|---|---|
success | boolean | mutation success |
data | any | data returned |
withDefault404Result
Resolves a promise with defaultResult
if the promise is rejected with a 404
code.
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:
Argument | Type | Description |
---|---|---|
promise | Promise | promise to evaluate |
defaultResult | any | default 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:
Argument | Type | Description |
---|---|---|
axiosInstance | axios | The axios instance to use |
url | string | The API's url |
defaultParams | object | The search params to use for request |
pageParamName | string | The name of the search param that contains the page |
pageSizeParamName | string | The name of the search param that contains the page size |
responseDataKey | string | The response key that contains data |
formatItem | function | The 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:
Argument | Type | Description |
---|---|---|
name | string | The name of the type |
defaultTypename | string | The 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:
Argument | Type | Description |
---|---|---|
amount | number | The price's amount. |
currency | string | The price's currency |
includeTax | boolean | Does 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:
Argument | Type | Description |
---|---|---|
options.max | number | The max request for duration |
options.duration | StringValue | The duration of the rate limiting |
resolver | FieldResolver | The resolver function |