Yas*_*pal 2 javascript rdf node.js stardog graphql
我正在尝试使用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;
Run Code Online (Sandbox Code Playgroud)
查询已成功执行,我可以在控制台上看到结果,但是return data.results.bindings;在内部function(data)并没有将此结果返回给Noun类型系统下的类型, resolve: (obj) => { console.log(obj); }
并且obj返回的结果显示为null,而不是bindings从GraphQL查询返回的结果。如果有人可以帮助我弄清楚我在这里缺少什么,那将是很棒的。
在此先感谢,Yashpal
在您的查询中,字段的resolve功能noun是一个异步操作(查询部分)。但是您的代码是同步的。因此,实际上没有任何东西会立即从resolve函数返回。这导致没有任何内容传递给NounGraphQL对象类型的resolve函数。这就是为什么在打印时得到null的原因obj。
如果resolve函数中进行异步操作,则必须返回一个可以解决预期结果的Promise对象。您还可以使用ES7异步/等待功能;在这种情况下,您必须声明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');
}
});
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
717 次 |
| 最近记录: |