Copied to Clipboard
Let's focus on the part from the extensions as everything else is just a default value for the certain integration to work properly.
Extensions will accept a parameter called extensions, and it is important to return a spread extensions in the final return. Otherwise, the default extensions in the integration may stop working so just please remember to return them as well. Next, we can see the structure of a new extension. Let's take a look at it with more details:
{
name: 'test',
extendApiMethods: {
testApiMethod: async ({ client, config }) => {
const result = await client.query({ query: gql`
query products {
products {
items {
id
customFields
}
}
}
`, fetchPolicy: 'no-cache' })
console.log(result)
}
}
}
First of all, we need to name our new extension. It is advised to give it some unique name (i.e. fetch-multiple-products) but in this case, I am just showing a test example. Next, we will have an extendApiMethods object where each property can represent its own new or extended API method. Each API method have access to the destructured client parameter. This parameter can then be used to call certain requests, queries, or mutations really easily from the frontend. This example shows how to fetch the multiple products from the GraphQL API by using the custom API method (the new one as Vendure does not have this query implemented - products are being fetched by using different query)
Then, you can use the newly created API method in your component or a page like following:
const { $vendure } = useVSFContext();
onSSR(async () => {
await $vendure.api.testApiMethod()
});
If everything worked correctly, you should see a result of a products query in the console where the project is running.
Summary
Well done! You have just implemented a completely new API method in your Vue Storefront 2 project. This knowledge will allow you to customize it even more to suit your business needs better.