Importing Clients from VTEX package
Importing a Client into your application
Introduction
In this step, you will learn how to search for ready-made Clients that abstract the Core Commerce APIs, as well as how to import them into your app on VTEX IO. We will import the Client Catalog
which will allow us to search for details about an SKU within the VTEX platform.
Clients
Clients, in VTEX IO, are abstractions for external services and are used natively to make external requests in backend services. You can read a little about them here.
VTEX IO Commerce Clients
The Commerce Clients package is a Typescript library that offers several clients already configured for access VTEX Core Commerce APIs. To use it in your app, just install it in the node/
folder running:
yarn add @vtex/clients
Custom Clients
If you don't find the Client you want for a Core Commerce service from VTEX, we recommend that you send a Pull Request to the commerce-clients
repository. We will be happy to review and eventually dive into your contribution.
But, if the service you are trying to access is an external provider (ex: Here Maps API), we recommend that you create Client in your own app by following these steps.
Activity
-
We will now import a Client from the Catalog module into our app. After you have cloned the boilerplate app, open the app code that was downloaded in the
service-example
folder in your editor. -
As the Client that we will use is offered in the Commerce Clients package, we will perform the installation. Inside the
node
folder, run the following command:
yarn add @vtex/clients
-
Now that the package has been installed, we need to configure Client to use it in the resolvers and middlewares of our app. For that, we need you to open the file
node/clients/index.ts
in your editor. -
Import the Client
Catalog
from the@vtex/clients
library. -
Add the getter
catalog
, similar to the method above in theClients
class.
+ import { Catalog } from '@vtex/clients'
...
+ public get catalog() {
+ return this.getOrSet('catalog', Catalog)
+ }
Done! Now, any of the resolver GraphQL or middlewares service functions can use this Client via ctx.clients.catalog
. Because of Typescript, it is possible to have autocomplete of the methods and see details of the types needed in the parameters.
Any questions?
See the answersheet for this step or check our [office hours] on the VTEX Developers channel(https://www.youtube.com/c/VTEXDevelopers)
Help us make this content better!
VTEX IO courses are open source. If you see something wrong, you can open a pull request!
Make a contributionUpdated 9 months ago