美文网首页
网站 express-graphql - 其他笔记

网站 express-graphql - 其他笔记

作者: 自走炮 | 来源:发表于2020-08-10 00:57 被阅读0次
    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 })
    

    相关文章

      网友评论

          本文标题:网站 express-graphql - 其他笔记

          本文链接:https://www.haomeiwen.com/subject/gdegrktx.html