我正在开发一个Web应用程序,该应用程序使用GraphQL查询OrientDB图形数据库。它使用Apollo Server解析传入的GraphQL查询。
我想构建一个查询,该查询将简单地将每个“主题”对象的“名称”字段作为字符串列表返回。例如:
{
"data": {
"allTopicNames": [
"Topic 1",
"Topic 2",
"Topic 3",
"Topic 4"
]
}
}
为此,我创建了一个类型定义:
// Imports: GraphQL
import { gql } from 'apollo-server-express';
// GraphQL: TypeDefs
const TYPEDEFS = gql`
type Query {
allTopics: [Topic]
topic(name: String): [Topic]
allTopicNames: [String] //This is the new Type Definition -- we want a list of Strings
}
type Topic {
name: String
}
`;
// Exports
export default TYPEDEFS;
以及相关的解析器:
//Connect to OrientDB
var OrientJs = require('orientjs');
var server = OrientJs({
host: "localhost",
port: "2424",
username: "root",
password: "root"
});
var db = server.use({
name: 'database',
username: 'root',
password: 'root'
});
// GraphQL: Resolvers
const RESOLVERS = {
Query: {
allTopics: () => {
return db.query('SELECT FROM Topic ORDER BY name');
},
allTopicNames: () => {
return db.query('SELECT name FROM Topic ORDER BY name'); //This is the new resolver
},
topic: (obj, args) => {
return db.query('SELECT FROM Topic WHERE name=\'' + args.name + '\' LIMIT 1');
}
}
};
// Exports
export default RESOLVERS;
但是,当我尝试实现上述类型定义和解析器时,我收到的字符串列表都是“ [object Object]”,而不是实际的字符串:
{
"data": {
"allTopicNames": [
"[object Object]",
"[object Object]",
"[object Object]",
"[object Object]"
]
}
}
我试图向解析器添加一些代码,该代码将遍历每个对象并创建适当的字符串列表以返回:
// GraphQL: Resolvers
const RESOLVERS = {
Query: {
allTopics: () => {
return db.query('SELECT FROM Topic ORDER BY name');
},
allTopicNames: () => {
let the_list_of_records = db.query('SELECT name FROM Topic ORDER BY name').then(res => {
let the_list_of_names = []; //We'll return a List of Strings using this
for(var i = 0; i < res.length; i++){
the_list_of_names.push(res[i]['name']);
}
console.log(the_list_of_names);
return the_list_of_names;
});
},
topic: (obj, args) => {
return db.query('SELECT FROM Topic WHERE name=\'' + args.name + '\' LIMIT 1');
}
}
};
但是这不起作用,导致返回空值:
{
"data": {
"allTopicNames": null
}
}
我很困惑为什么我无法通过此解析器获得简单的字符串列表。也许我缺少明显的东西-任何见解都将不胜感激!
答案 0 :(得分:1)
您的初始方法未按预期工作,因为您要返回一个对象数组。您的第二次尝试返回null,因为您在解析器内部未返回任何内容。您的解析器应始终返回一个值或将解析为该值的Promise,否则该字段的解析值将始终为null。
the_list_of_records
的值将是一个Promise,因此您只需返回它就足够了。但是我们可以像这样使用map
使此代码更易于阅读:
allTopicNames: () => {
return db.query('SELECT name FROM Topic ORDER BY name').then(res => {
return res.map(topic => topic.name)
})
}
// using async/await
allTopicNames: async () => {
await topics = await db.query('SELECT name FROM Topic ORDER BY name')
return topics.map(topic => topic.name)
}