我试图使用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而不是从GraphQL查询返回的结果bindings
。如果有人能帮助我弄清楚我在这里缺少什么,那就太好了。
提前谢谢,Yashpal
在您的查询中,resolve
字段的noun
函数是一个异步操作(查询部分)。但是你的代码是同步的。因此,实际上不会立即从resolve函数返回任何内容。这导致没有传递给Noun
GraphQL对象类型的resolve函数。这就是为什么当你打印obj
时你得到null。
如果在resolve
函数中进行异步操作,则必须返回一个与您的预期结果一起解析的promise对象。您还可以使用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');
}
});
});
}