2

我正在尝试使用以下 graphql 查询 stardog 服务器是我的代码。

import {
  GraphQLSchema,
  GraphQLObjectType,
  GraphQLInt,
  GraphQLString,
  GraphQLList,
  GraphQLNonNull,
  GraphQLID,
  GraphQLFloat
} from 'graphql';

import axios from 'axios';

var stardog = require("stardog");

let Noun = new GraphQLObjectType({
      name: "Noun",
      description: "Basic information on a GitHub user",
      fields: () => ({
          "c": {
       type: GraphQLString,
       resolve: (obj) => {
        console.log(obj);
          }
        }
     })
});

const query = new GraphQLObjectType({
      name: "Query",
      description: "First GraphQL for Sparql Endpoint Adaptive!",
      fields: () => ({
        noun: {
          type: Noun,
          description: "Noun data from fibosearch",
          args: {
            noun_value: {
              type: new GraphQLNonNull(GraphQLString),
              description: "The GitHub user login you want information on",
            },
          },
          resolve: (_,{noun_value}) => {
              var conn = new stardog.Connection();

              conn.setEndpoint("http://stardog.edmcouncil.org");
              conn.setCredentials("xxxx", "xxxx");
                conn.query({
                    database: "jenkins-stardog-load-fibo-30",
                    query: `select ?c  where {?s rdfs:label '${noun_value}'. ?c rdfs:subClassOf ?s}`,  
                    limit: 10,
                    offset: 0
                },
                function (data) {
                       console.log(data.results.bindings);
                       return data.results.bindings;
                });  
              }
            },
          })
      });

const schema = new GraphQLSchema({
  query
});

export default schema;

查询成功执行,我可以在控制台上看到结果,但return data.results.bindings;内部function(data)没有将此结果返回到Noun下的类型系统, resolve: (obj) => { console.log(obj); } 并且obj返回显示 null 而不是bindingsGraphQL 查询返回的结果。如果有人可以帮助我弄清楚我在这里缺少什么,那就太好了。

提前致谢, 亚什帕尔

4

1 回答 1

5

在您的查询中,字段的resolve功能noun是异步操作(查询部分)。但是您的代码是同步的。因此,resolve 函数实际上并没有立即返回任何内容。这导致没有任何东西传递给NounGraphQL 对象类型的解析函数。这就是为什么你在 print 时得到 null 的原因obj

如果函数中的异步操作resolve,您必须返回一个承诺对象,该对象会根据您的预期结果进行解析。你也可以使用 ES7 的 async/await 特性;在这种情况下,您必须声明resolve: async (_, {noun_value}) => { // awaited code}.

使用Promise,代码将如下所示:

resolve: (_,{noun_value}) => {
  var conn = new stardog.Connection();

  conn.setEndpoint("http://stardog.edmcouncil.org");
  conn.setCredentials("xxxx", "xxxx");
  return new Promise(function(resolve, reject) {
    conn.query({
      database: "jenkins-stardog-load-fibo-30",
      query: `select ?c  where {?s rdfs:label '${noun_value}'. ?c rdfs:subClassOf ?s}`,  
      limit: 10,
      offset: 0
    }, function (data) {
      console.log(data.results.bindings);
      if (data.results.bindings) {
        return resolve(data.results.bindings);
      } else {
        return reject('Null found for data.results.bindings');
      }
    });
  });
}
于 2016-06-14T16:08:59.587 回答