const express = require("express");
const graphqlhttp = require("express-graphql"); // npm i express-graphql graphql
const graphqlschema = require("./schema/default.js");
const app = express();
app.use("/graphql", graphqlhttp){ // http://localhost:3000/graphql
schema: graphqlschema,
graphiql: true,
}
// schema/default.js 文件
const DB = require("./model/db.js");
const {
GraphQLObjectType,
GraphQLString,
GraphQLList,
GraphQLSchema
} = require("graphql");
const CustomSchema = new GraphQLObjectType({
name: "custom",
fields: {
_id: { type: GraphQLString },
title: { type: GraphQLString }
}
})
const RootSchema = new GraphQLObjectType({
name: "root",
fields: {
findOne: {
type: CustomSchema,
args: { id: { type: GraphQLString } },
async resolve(parent, args){
var id = args.id;
var list = await DB.find("custom", { "_id": DB.getobjectId(id)});
return list[0];
}
},
findAll: {
type: GraphQLList(CustomSchema),
async resolve(parent, args){
var list = await DB.find("custom", {});
return list;
}
}
}
})
module.exports = new GraphQLSchema({ query: RootSchema })
网友评论