Custom Queries
Introduction
Sometimes, you may need to fetch data from the API that is not covered by the default methods. In this case, you can use the the custom queries feature to extend defaults by your own GraphQL queries.
Custom queries in middleware config
To use custom queries, add them to the customQueries object in the integration config file located at apps/storefront-middleware/integrations/commercetools/config.ts.
In the example below, we are adding a custom query called get-me-basic-custom-query:
// apps/storefront-middleware/integrations/commercetools/config.ts
export const config = {
// ...
customQueries: {
'get-me-basic-custom-query': ({ query, variables, metadata }) => ({
variables,
query: `
query getBasicProfile {
me {
activeCart {
${metadata}
}
}
}
`,
}),
},
};
Using custom queries
To use a custom query, pass the custom query descriptor as the second argument to the method. The descriptor contains the custom query name and its metadata.
In our example, we're fetching basic user profile and using the custom GraphQL query from the previous example.
Overwriting the default response interface
Notice how we are using the type parameter to overwrite the default response interface.
type CustomGetMeResponse = {
me: {
activeCart: {
id: string;
version: string;
};
};
};
const { me } = await sdk.ct.getMe<CustomGetMeResponse>(undefined, {
getBasicProfile: 'get-me-basic-custom-query',
metadata: 'id,version',
});
Let's try with another example:
Creating a custom GraphQL query for fetching full user profile in apps/storefront-middleware/integrations/commercetools/config.ts.
// apps/storefront-middleware/integrations/commercetools/config.ts
export const config = {
// ...
customQueries: {
'get-me-full-custom-query': ({ query, variables, metadata }) => ({
variables,
query: `
query getFullProfile {
me {
activeCart {
${metadata.activeCart}
}
customer {
${metadata.customer}
}
}
}
`,
}),
},
};
Fetching full user profile and using the customQuery parameter to leverage the custom GraphQL query from the previous example.
Overwriting the default response interface
Notice how we are using the type parameter to overwrite the default response interface.
type CustomGetMeResponse = {
me: {
activeCart: {
id: string;
};
customer: {
id: string;
};
};
};
const { me } = await sdk.ct.getMe<CustomGetMeResponse>({ customer: true }, {
getFullProfile: 'get-me-full-custom-query',
metadata: { activeCart: 'id', customer: 'id' },
});
By doing that, we've just fetched the full user profile using a custom GraphQL query. me object contains the activeCart and customer objects.
Custom queries for other methods
To check out our examples, how to add a custom query to other methods, check out the API Reference: Functions. Each method has at least one example of how to use a custom query.