如何使用GraphQL查询返回目录中的文件列表?

问题描述 投票:1回答:2

我需要使用GraphQL查询返回的文件夹中的文件列表。有人可以解释一下,如何配置此查询文件吗?我使用fs()方法进行了一些配置,但未返回文件列表。下面是架构和解析器的代码。为了缩短代码,我删除了一些与文件无关的解析器。非常感谢您的帮助!

schema.js

const { buildSchema } = require('graphql');

module.exports = buildSchema(`
type Hero {
  _id: ID!
  title: String!
  description: String
  date: String!
}
type File {
  path: String
}
input HeroInput {
  title: String!
  description: String!
  date: String!
}
input HeroUpdate {
  _id: ID!
  title: String!
  description: String
  date: String!
} 
input HeroRemove {
  _id: ID! 
} 
type RootQuery {
  heroes: [Hero!]!
  findHero(id: ID!): Hero
  files: File
}
type RootMutation {
  createHero(heroInput: HeroInput): Hero
  deleteHero(heroRemove: HeroRemove): Hero
  updateHero(heroUpdate: HeroUpdate): Hero
}
schema {
  query: RootQuery
  mutation: RootMutation
}
`);

resolvers.js

const Hero = require('./models/hero');
const path = require('path');
const fs = require('fs');

module.exports = {
  files: () => {
    const filesPath = path.join(__dirname, './files');
    return fs.readdir(filesPath, function (err, files) {
      if (err) {
        return console.log('Unable to scan directory: ' + err);
      }  
      console.log(files);    
      return files.map(file => {
        return {
          path: file
        };
      });
    });
  },
  heroes: () => {
    return Hero.find()
      .then(heroes => {
        return heroes.map(hero => {
          return { 
            ...hero._doc, 
            _id: hero.id,
            date: new Date(hero.date).toISOString()
          };
        });
      })
      .catch(err => {
        throw err;
      });
  }
};
javascript node.js graphql
2个回答
0
投票

您的files解析器无法正常工作,因为您要返回fs.readdir。但是,该函数是异步的,因此将立即返回undefined而不是回调函数的结果。

为了避免此问题,您可以使用fs.readdirSync代替fs.readdir

files: () => {
  const filesPath = path.join(__dirname, './files');
  const files = fs.readdirSync(filesPath);  
  return files.map(file => ({path: file}));
}

注意:我为map函数使用了一种简写形式,以便立即返回该对象!

fs.readdirSync的文档:https://nodejs.org/api/fs.html#fs_fs_readdirsync_path_options

希望这可以解决您的问题:)

干杯,derbenoo


0
投票

解决方案是配置文件类型并在schema.js中进行查询

const { buildSchema } = require('graphql');

module.exports = buildSchema(`
type Hero {
  _id: ID!
  title: String!
  description: String
  date: String!
}
type File {
  path: String
}
input HeroInput {
  title: String!
  description: String!
  date: String!
}
input HeroUpdate {
  _id: ID!
  title: String!
  description: String
  date: String!
} 
input HeroRemove {
  _id: ID! 
} 
type RootQuery {
  heroes: [Hero!]!
  findHero(id: ID!): Hero
  files: [File]
}
type RootMutation {
  createHero(heroInput: HeroInput): Hero
  deleteHero(heroRemove: HeroRemove): Hero
  updateHero(heroUpdate: HeroUpdate): Hero
}
schema {
  query: RootQuery
  mutation: RootMutation
}
`);
© www.soinside.com 2019 - 2024. All rights reserved.