Setting up a service in VTEX IO to interact with Master Data v1.
This guide provides step-by-step instructions on how to create a VTEX IO service to interact with Master Data v1. This solution is recommended if you need to update Master Data v1 field values based on a trigger or whenever adding or updating a document.
Discover how to effectively leverage Master Data capabilities through your service in the upcoming sections.
Before you begin
Make sure you meet the technical requirements to complete this project:
- Experience developing in Typescript language.
- Having VTEX IO CLI installed.
Step 1: Initializing the project
To begin setting up your service to interact with Master Data v1 on VTEX IO, follow these steps to initialize your project using the service-example template:
- Open the terminal.
- Type the command
vtex init
. - Select the
service-example
template. - Enter a folder name or use the default name, which is the same as the selected template.
Step 2: Setting up policies
Configure permissions for your application to access Master Data by following the steps below:
-
Open the project folder in your preferred code editor.
-
Open the
manifest.json
file located at the root of the project. -
Add the following structure to the
policies
section:_10{_10"name": "outbound-access",_10"attrs": {_10"host": "api.vtex.com",_10"path": "/dataentities/*"_10}_10},_10{_10"name": "ADMIN_DS"_10}
Step 3: Creating a client
Create a client class in TypeScript to extend the functionality of MasterData
from the @vtex/api
module:
-
Inside the
node
folder, create aclients
folder if it does not exist. -
Create a Typescript file in the
clients
folder. In this example, the file will be namedmd.ts
. -
Create a class that extends from the
MasterData
class from the@vtex/api
module._10import { MasterData } from '@vtex/api'_10export default class MD extends MasterData {} -
Modify the class to include the constructor and headers:
In this class, we will call the
constructor
and, within it, thesuper
method, passing thecontext
andoptions
received in theconstructor
class._13import { IOContext, InstanceOptions, MasterData } from '@vtex/api'_13_13export default class MD extends MasterData {_13constructor(context: IOContext, options?: InstanceOptions) {_13super(context, {_13...options,_13headers: {_13{{app-key}}_13{{app-token}}_13},_13})_13}_13}In this class, we will have access to several methods extended from the Master Data class, including:
Method name Description getDocument
Retrieves a document by its ID for a given data entity, with specified fields. createDocument
Creates a new document in the specified data entity. createOrUpdateEntireDocument
Creates or updates an entire document in the specified data entity. createOrUpdatePartialDocument
Partially creates or updates a document in the specified data entity. updateEntireDocument
Updates an entire document by its ID for a given data entity. updatePartialDocument
Partially updates a document by its ID for a given data entity. searchDocuments
Searches for documents in the specified data entity, with various search parameters and pagination. searchDocumentsWithPaginationInfo
Searches for documents and returns data with pagination information. scrollDocuments
Scrolls through documents in the specified data entity with various search parameters. deleteDocument
Deletes a document by its ID for a given data entity. -
Add the desired method. The example below uses the
getDocument
method:_10public getDocumentById(_10dataEntity: string,_10id: string,_10fields: string[]_10): Promise<any> {_10return this.getDocument({ dataEntity, id, fields })_10}
Step 4: Registering the Client
After creating our Client class, you need to register it in the index.ts
file within the same clients
folder:
-
Open the
index.ts
file in theclients
folder. -
Import the new client (e.g.,
MD
) and add it to theClients
class, as exemplified below:_10import { IOClients } from '@vtex/api'_10import MD from './md'_10_10// Extend the default IOClients implementation with our own custom clients_10export class Clients extends IOClients {_10public get MD() {_10return this.getOrSet('MD', MD)_10}_10}
Step 5: Creating the middleware
Implement a middleware function to handle interactions between your service and Master Data, executing the method we created and returning the response based on the context:
-
Inside the
node
folder, create amiddlewares
folder if it does not exist. -
Create a file named
masterdataMiddleware.ts
in themiddlewares
folder. -
Add your TypeScript code to
masterdataMiddleware.ts
.Following the example in the previous sections to illustrate this step, in this middleware, we will return the call to the method created to a variable and then add this variable to the context body. The method expects to receive an entity, a document ID, and an array of fields to be returned in the response.
_22export async function masterdataMiddleware(_22ctx: Context,_22next: () => Promise<any>_22) {_22const {_22clients: { MD },_22} = ctx_22_22const response = await MD.getDocumentById(_22'CL',_22'0807f150-68bb-11Ec-82ac-12fdbe358f3f',_22['id', 'email']_22)_22_22ctx.status = 200_22_22ctx.body = {_22response,_22}_22_22await next()_22}
Step 6: Configuring the route
Configure a dedicated route in your service that will be accessed through your store's endpoint:
-
Open the
service.json
file in thenode
folder. -
In the
routes
section, define theroutes
object as shown below. In this example, we will define thepath
as/_v/md/get-document
and make this route public._10"routes": {_10"masterdata": {_10"path": "/_v/md/get-document",_10"public": true_10}_10} -
Open the
index.ts
file in thenode
folder.In this file, you will see a new instance of service created. You will register your route within the
routes
object. -
Register the route within the
routes
object._10masterdata: method({_10GET: [masterdataMiddleware],_10}),
The
masterdata
attribute is the route ID created in theservice.json
file.
The masterdata
attribute receives a function containing an object where we can pass various middleware mappings. In this case, we will use the HTTP method GET, which receives an array where we must declare the middleware created in previous sections.
Step 7: Running the project
Finalize setup by linking your project to a development workspace and testing the configured service routes:
-
In the terminal, navigate to the root of the project.
-
Run the command
vtex link
.After linking, you should see the following message:
_10**info:** *Available service routes: https://{{workspace}}--{{accountName}}.myvtex.com/{{path}} -
Access the service route from the previous step in your browser.
Following the example of a service to retrieve a document, you should see a response with the fields defined in the middleware:
_10{_10"response": {_10"id": "0807f150-68bb-11Ec-82ac-12fdbe358f3f",_10"email": "john@mail.com"_10}_10}
Conclusion
These instructions enable you to configure clients, middleware, and routes to set up a VTEX IO service for interacting with Master Data v1. Note that there are various methods and configurations beyond this guide to further customize and optimize your integration with VTEX IO and Master Data.