How to add custom API methods to Vue Storefront 2

jacobandrewsky

Jakub Andrzejewski

Posted on August 29, 2022

How to add custom API methods to Vue Storefront 2

Vue Storefront allows you to scaffold your next E-Commerce website in minutues. You can choose from a variety of platforms like Magento, Shopify, Commercetools, and many more!

In this tutorial, I would like to guide you through the process of adding a custom API method to create a new function for your E-Commerce. It will allow you to have a completely new endpoint extension that could send a new request, a GraphQL query/mutation, or something completely different as well.

For this tutorial, I will be using Vendure integration, but you are free to choose any E-Commerce integration you want. The process is the same for all these integration with a small difference depending on the API client that the integration is using (either Apollo GraphQL or Axios REST).

Code

First of all, you would need to register a new extension in a middleware.config.js file:

module.exports = {
  integrations: {
    vendure: {
      location: '@vue-storefront/vendure-api/server',
      configuration: {
        api: {
          uri: process.env.GRAPHQL_API,
          // to be used later with authentication
          tokenMethod: process.env.TOKEN_METHOD
        }
      },
      extensions: (extensions) => [
        ...extensions,
        {
          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)
            }
          }
        }
      ]
    }
  }
};
Enter fullscreen mode Exit fullscreen mode

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)
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

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()
});
Enter fullscreen mode Exit fullscreen mode

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.

💖 💪 🙅 🚩
jacobandrewsky
Jakub Andrzejewski

Posted on August 29, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related