Erro api node-vtex

Pessoal, tentei instalar o modulo de API conforme consta na documentação de requests por node, com npm install api --save. Mas quando rodo VTEX link, me aparece o erro abaixo:

@readme/openapi-parser@2.2.0: The engine “node” is incompatible with this module. Expected version “>=14”. Got "12.16.1"

example de método que precisaria usar com o modulo:

  const sdk = require("api")('@vtex-rest-api/v2.1#1i5odymzkzihwg3i');

return sdk.Searchdocuments({
  _fields: {_fields},
  _sort: '{{field ASC}',
  data_entity_name: '{acronym}',
  Accept: 'application/vnd.vtex.ds.v10+json',
  'REST-Range': 'resources%3D0-10',
  'X-VTEX-API-AppKey': APP_KEY,
  'X-VTEX-API-AppToken': APP_TOKEN
}).then((res: any) => console.log(res))
  .catch((err: any) => console.error(err));

Alguém sabe como resolver isso?
Antes de tentar a request no node usando o que é orientado na documentação, eu tentei com axios, mas só me retorna pending (se faço a mesma request no front-end ou post-man funciona).
Alguém tem alguma dica de como resolver isso?

Você deve atualizar sua versão do node.

minha versão está atualizada, eu uso o nvm, então consigo trocar para várias. já coloquei pra ultima e ainda assim da esse erro

Hi @Marinho
Service Course, please go through this link.
This might help you.

Regards,
Tanishq

Hi Tanish, thanks for your answer, but I already saw this link, and don’t see anything about my problem :confused:

Is your function Async?
and are you using the service-course-template?

export const resolvers = {
    Query:{
        myFamily: async(_:any,{email}:{email:String},ctx:any)=>{    
            const {
                clients:{masterdata}
            } = ctx

            const data= await masterdata.searchDocuments({
                dataEntity:DataEntity,
                fields :['memberName','memberEmail'],
                schema:SCHEMA,
                pagination: {
                    page: 1,
                    pageSize: 1,
                  }, 
                  where: `memberEmail = ${email}`
            })

            return data
        },
}

This is how I use it to create GraphQl Resolvers.

You can connect with me on LinkedIn and we can look into it

Try installing open-api with yarn npm install sometimes throws this error.

The request function:

const getInstitutions = async (fields: string): Promise<InstitutionsModel[]> => {

    const headers =  {
          'Content-Type': 'application/json',
          Accept: 'application/vnd.vtex.ds.v10+json',
          "REST-Range": "resources=0-100",
          'X-VTEX-API-AppKey': APP_KEY,
          'X-VTEX-API-AppToken': APP_TOKEN
        };
      
      try {
          const institutions: InstitutionsModel[]  = (await axios.get(`/api/dataentities/IS/search?_fields=${fields}&_sort=name ASC`, {
              headers: headers
          })).data;
          return institutions;
      }catch (e) {
          throw e;
      }
}

the service that call this function when my front-end call the service

export default new Service<IOClients, State, ParamsContext>({
  clients: {
    options: {
      events: {
        exponentialTimeoutCoefficient: 2,
        exponentialBackoffCoefficient: 2,
        initialBackoffDelay: 50,
        retries: 1,
        timeout: TREE_SECONDS_MS,
        concurrency: CONCURRENCY,
      },
    },
  },
  events: {
    getEvent,
  },
  routes: {
    hcheck: (ctx: ServiceContext<IOClients, State, ParamsContext>) => {
      let fields = getParamsRequest(ctx);
      setCacheContext(ctx)
      ctx.set('Cache-Control', 'no-cache')
      ctx.status = 200
      ctx.body = "OK"
      if(fields) {
        let institutions = getInstitutions(fields).then(res => return) // here I'M using .then because if I'm put this hcheck with async and using await instead this will get proxy time out error;
        console.log('institutions',institutions)
        ctx.response.body = institutions
      } else {
        ctx.response.body = errorNoParams;
      }
     
    },
  },
})

When i Install with yarn, the installation dont complete, only completed when use npm.

Basically, what I’M trying to do, is make this request: Search documents in node/VTEX service. When do it in frontend or postman return the answer, the main problem is when I make this in node, that only return Promise

Hi @Marinho
Clone a new service course template. You have the VTEX api declared in the package.json so you don’t have to.

inside your handlers folder declare a file MasterData.ts

export async function MasterDataCall(ctx: Context, next: () => Promise<any>) {
    const {
      clients: { masterdata },
    } = ctx
    ctx.status = 200
   const data = await masterdata.searchDocuments({
        dataEntity:"organizations",
                fields :["_all"],
                schema:"v0.0.6",
                pagination: {
                  page: 1,
                  pageSize: 1,
                }, 
                where:`name=ABC`
                

    })
    ctx.body = data
    ctx.set('cache-control', 'no-cache')
    await next()
  }

Add this in the policies

 {
      "name": "ADMIN_DS"
    },
    {
      "name": "outbound-access",
      "attrs": {
        "host": "api.vtex.com",
        "path": "/dataentities/*"
      }
    },

manifest.json

index.ts

Handler

1 Like

This works, you don’t need to create an SDK or anything.

Regards,
Tanishq

Thank you for so many details in your anwser. I will try it. In the previous way that I was trying, in my service.json, the routes call the hcheck function, in your way, I need to pass only the path?

service.json:

 "routes": {
    "hcheck": {
      "path": "/_v/app/service/institutions",
      "public": true
    }
  }

previous way:

// function sendEventWithTimer() {
//   setInterval(function () {
//     const context = getCacheContext()

//     if (!context) {
//       console.log('no context in memory')

//       return
//     }

//     return createSendEvent(context)
//   }, 30000)
//   console.log('FIRED HERE')
// }

// sendEventWithTimer()

// export default new Service<IOClients, State, ParamsContext>({
//   clients: {
//     options: {
//       events: {
//         exponentialTimeoutCoefficient: 2,
//         exponentialBackoffCoefficient: 2,
//         initialBackoffDelay: 50,
//         retries: 1,
//         timeout: TREE_SECONDS_MS,
//         concurrency: CONCURRENCY,
//       },
//     },
//   },
//   events: {
//     getEvent,
//   },
//   routes: {
//     hcheck: (ctx: ServiceContext<IOClients, State, ParamsContext>) => {
     
//       // let fields = getParamsRequest(ctx);
//       setCacheContext(ctx)
//       ctx.set('Cache-Control', 'no-cache')
//       ctx.status = 200
//       ctx.body = "OK"
//       // if(fields) {
//       //   let institutions = await getInstitutions(fields);
//       //   ctx.response.body = institutions
//       // } else {
//       //   ctx.response.body = errorNoParams;
//       // }
     
//     },
//   },
// })

Yes, just the path