【问题标题】:How to fetch the data from database for resolver in graphql如何从数据库中为graphql中的解析器获取数据
【发布时间】:2021-06-17 02:22:31
【问题描述】:

我创建了两个文件

index.js

const {ApolloServer,gql} = require('apollo-server');
const fs = require('fs');
const path = require('path');

const typedefs = gql`
        type Query {
            info: String!
            ask: [Person!]
        }
        type Person {
            name: String!
            age: Int!
        }
`;
const resolvers = {
    Query: {
        info: () => `Hello World from Linux Fan`,
        ask: () => {
            return [fs.readFileSync(__dirname+path.join('/db.db'),'utf-8')]
        }
    }
}

const server = new ApolloServer({
    typedefs,
    resolvers
}).listen().then(({url}) => console.log(url)).catch(err => console.log(err));

还有一个用于存储数据库的文件

db.db

{
    name:"Linux Age",
    age: 19
}

但问题是每次我查询获取姓名和年龄时

{
  info
  ask{
    name
  }
}

有问题存在并说

“不能为不可为空的字段 Person.name 返回 null”

如何解决??

【问题讨论】:

  • return [{ name:"Linux Age", age: 19 }]; ... db 开头?没有 db ...而且您不知道从文件中读取数据
  • 尝试按照本教程进行操作:apollographql.com/docs/tutorial/introduction。同样对于“开始”使用console.log 这个语句的输出是什么? console.log(fs.readFileSync(__dirname+path.join('/db.db'),'utf-8'))(这里不知道)。返回的数据必须与架构匹配(在您的情况下是人员对象数组)。

标签: node.js express graphql apollo apollo-server


【解决方案1】:

根据 Node.js 文档 (https://nodejs.org/api/fs.html#fs_fs_readfilesync_path_options),fs.readFileSync() 返回一个字符串或缓冲区。然而,从模式中, ask() 返回一个 Person 类型的数组,它是一个对象。 fs.readFileSync() 的结果应该在返回之前转换为对象:

ask: () => {
  const person = JSON.parse(JSON.stringify(
    fs.readFileSync(__dirname + path.join('/db.db'), 'utf-8').toString()
  ));
  return [person];
}

请注意,我在使用 JSON.parse() 解析它之前调用了 JSON.stringify()。原因是文件 db.db 有一个 javascript 对象(键、名称和年龄,它们周围没有双引号)而不是 JSON 对象(带引号的键,如下所示):

{
  "name":"Linux Age",
  "age": 19
}

否则,JSON.parse() 在解析无效的 JSON 格式时会出现问题:

{
  name:"Linux Age",
  age: 19
}

另外,调用readFileSync()后需要toString()将Buffer转成字符串:

fs.readFileSync(__dirname + path.join('/db.db'), 'utf-8').toString()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-28
    • 2018-09-01
    • 2017-04-01
    • 1970-01-01
    相关资源
    最近更新 更多