question

atlars avatar image
atlars asked

Get GraphQL query with NodeJS

I'm new to Node.JS and GraphQL. I need to add a GraphQL query to the getRemoteData function below.

GraphQL query:

  query {
      posts (first: 10) { 
        edges { 
          node { 
            id
            name
          }
        }
      }
    }

getRemoteData Handler:

const GetRemoteDataHandler = {
  canHandle(handlerInput) {
    return handlerInput.requestEnvelope.request.type === 'LaunchRequest'
      || (handlerInput.requestEnvelope.request.type === 'IntentRequest'
      && handlerInput.requestEnvelope.request.intent.name === 'GetRemoteDataIntent');
  },
  async handle(handlerInput) {
    let outputSpeech = 'This is the default message.';

    await getRemoteData('https://example.com/api/graphql')
      .then((response) => {
        const data = JSON.parse(response);
        outputSpeech = `... `;

getRemoteData:

  const getRemoteData = function (url) {
      return new Promise((resolve, reject) => {
        const client = url.startsWith('https') ? require('https') : require('http');
        const request = client.get(url, (response) => {
          if (response.statusCode < 200 || response.statusCode > 299) {
            reject(new Error('Failed with status code: ' + response.statusCode));
          }
          const body = [];
          response.on('data', (chunk) => body.push(chunk));
          response.on('end', () => resolve(body.join('')));
        });
        request.on('error', (err) => reject(err))
      })
    };

How to add a GraphQL query to the getRemoteData function?

Any help is really appreciated, thank you.

alexa skills kitalexaapinodejsrequest
10 |5000

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

1 Answer

Rokas avatar image
Rokas answered

I haven't worked too much with graphql myself, so I don't know if there is native methods in node to do a graphql request, but I would probably use this package: here. It has an example how to use graphql queries.

One more thing, you don't need to await a promise, that you use then() on, at line 10 in first example.

1 comment
10 |5000

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Thank you, graphql-request seems the way to go. I posted a follow up question here: https://forums.developer.amazon.com/questions/207898/graphql-query-in-nodejs-fails-with-there-was-a-pro.html Any help is really appreciated

0 Likes 0 ·