zoukankan      html  css  js  c++  java
  • 第一个GraphQL Demo

    1. 我的环境是mac机器,首先要安装node

    2. 新建一个文件夹,随便起什么名字都OK,我的名字是

      mkdir graphql_with_nodejs

    3. 进入到文件夹中:cd  graphql_with_nodejs

    4. 初始化创建nodejs项目: npm init  ,此时会生成一个package.json文件

    5. 安装环境

    •    npm install express
    • npm install express-graphql graphql

    6. 到此我们的环境就安装好了, 接下来需要写代码了

        首先是我们的server.js代码, 创建一个文件server.js, 复制以下代码进去

    const express = require('express');
    const graphqlHTTP = require('express-graphql');
    const {GraphQLSchema} = require('graphql');
    
    const {queryType} = require('./schema.js');
    
    //setting up the port number and express app
    const port = 8000;
    const app = express();
    
     // Define the Schema
    const schema = new GraphQLSchema({ query: queryType });
    
    //Setup the nodejs GraphQL server
    app.use('/graphql', graphqlHTTP({
        schema: schema,
        graphiql: true,
    }));
    
    app.listen(port);
    console.log(`GraphQL Server Running at localhost:${port}`);

    其次是定义我们的查询文件schema.js

      

    // 定义类型
    const { GraphQLObjectType, GraphQLString, GraphQLInt, GraphQLBoolean } = require('graphql'); //Define the Query const queryType = new GraphQLObjectType({ name: 'Query', fields: { hello: {
    // 查询结果类型 type: GraphQLString, args: { name: { type: GraphQLString, defaultValue: 'Brian' } },
    // 这里使用传参的方式返回值,上面定义了参数的默认值,如果不写就使用默认值; resolve: function(parentValue, args, request) { return 'Hello World ' + args.name + '!'; } }, person: { name: 'personQuery', description: 'query a person', type: new GraphQLObjectType({ // 这里定义查询结果包含name,age,sex三个字段,并且都是不同的类型。 name: 'person', fields: { name: { type: GraphQLString }, age: { type: GraphQLInt }, sex: { type: GraphQLBoolean } } }), args: { name: { type: GraphQLString, defaultValue: 'Charming' } }, resolve(parentValue, args, request) { return { name: args.name, age: args.name.length, sex: Math.random() > 0.5 }; } } } }); exports.queryType = queryType;

     7. 此时,我们就可以运行代码, node server.js

         在浏览器中输入 http://localhost:8000/graphql

         如果环境和代码都正确,就会出现如下所示:

    此时,写入我们需要查询的代码:

    {
      hello,
      person(name:"charming"){
        name,
        sex,
        age
      }
    }

    点击三角符号运行,就会出现如下所示: 我们hello使用的是默认指,2️⃣person使用的是传参的方式;

       到此,我们的第一个Demo就完成了, 刚开始学习,还有很多不懂,在成长的道路上继续前进,加油!

      参考文档: https://blog.csdn.net/qq_41882147/article/details/82966783 

                      https://www.jdon.com/51179

        

  • 相关阅读:
    python第二十四课——set中的函数
    python第二十三课——dict中的函数
    python第二十二课——list函数
    10 编译PHP并与nginx整合
    09 nginx Rewrite(重写)详细解析
    07 nginx Location之正则匹配
    06 nginx Location详解之精准匹配
    JQ 修改样式
    05 nginx定时任务完成日志切割
    linux 时间与本地时间不对应解决办法
  • 原文地址:https://www.cnblogs.com/leavescy/p/11424602.html
Copyright © 2011-2022 走看看