I need a list of files in folder, returned with GraphQL query. Can someone explain, how to configure the type and resolver the list? I have some configuration with fs() method, but it doesn't return the list of files. There's a code of schema and resolvers below. To shorten the code, I removed some resolvers that are not related to files. Will be very grateful for any help!
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;
});
}
};
The solution is to configure the File type and query in 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
}
`);