express graphQL 开发前端中间件

安装前置依赖

javascript 复制代码
 npm i express
 // 转化es 
 npm i babel-preset-env babel-cli babel-preset-stage-0
 // 添加watch
 npm i -D nodemon
 // 添加graphql
 npm i graphql graphql-http

添加启动命令

javascript 复制代码
"start": "nodemon index.js --exec babel-node --presets env stage-0"

创建入口文件

在根目录下创建index.js

javascript 复制代码
import express from 'express'; // yarn add express

const app = express();

app.listen({ port: 4000 });

json-server可以模拟接口

以下为模拟的数据,学生的基本信息和基本学习成绩

javascript 复制代码
{
  "user": [
    {
      "id": 1,
      "name": "张三",
      "age": "30",
      "gender": 1
    },
    {
      "id": 2,
      "name": "李四",
      "age": "23",
      "gender": 0
    }
  ],
  "grade": [
    {
      "id": 1,
      "Language": 53,
      "Maths": 100,
      "science": 60
    },
    {
      "id": 2,
      "Language": 39,
      "Maths": 40,
      "science": 34
    }
  ]
}

/**
 package.json 添加命令,来创建mock接口   
 分别为 http://localhost:3300/user 和 http://localhost:3300/grade
**/
"json-server": "json-server --watch ./mock/index.json --port 3300"

创建query请求

假设要将两个接口合并成一个,查询所有学生以及他们对应的成绩

./router下创建query.js

javascript 复制代码
import axios from 'axios'
// 引入所需的类型,graphQL只能用他自己的类型
import {
  GraphQLObjectType,
  GraphQLString,
  GraphQLList,
  GraphQLInt,
  GraphQLInputObjectType
} from 'graphql';

// 学生基础信息的类型
const userArgs = {
  id: {type: GraphQLInt},
  name: {type: GraphQLString},
  age: {type: GraphQLString},
  gender: {type: GraphQLInt}
}

// 请求时入参的类型声明
const queryParamsType = new GraphQLInputObjectType({
  name: 'queryParamsType',
  fields: userArgs
})

// 返回成绩的声明
const GradeType = new GraphQLObjectType({
  name: 'GradeType',
  fields: {
    id: {type: GraphQLInt},
    Language: {type: GraphQLInt},
    Maths: {type: GraphQLInt},
    science: {type: GraphQLInt}
  }
})

// 返回的学生声明
const UserType = new GraphQLObjectType({
  name: 'UserType',
  fields: {
    id: {type: GraphQLInt},
    name: {type: GraphQLString},
    age: {type: GraphQLString},
    gender: {type: GraphQLInt},
    // 可以直接将要的数据放入声明里
    grade: {
      type: GradeType,
      // 直接通过resolve进行数据请求 parent是父级返回的数据
      resolve(parent) {
        return axios({
          url: `http://localhost:3300/grade`,
          params: { id: parent.id } // 在请求中带上参数
        }).then(result => {
          if(Array.isArray(result.data)){
            return result.data[0]
          }
          return result.data;
        });
      },
    }
  }
})


// 声明的query类型,并把他暴露出去
export const QueryType = new GraphQLObjectType({
  name: 'Query',
  fields: {
    user: {
      type: new GraphQLList(UserType),
      // 一定要将args带上,这是入参的声明
      args: {
        queryParams: {
          type: queryParamsType
        }
      },
      resolve(obj, args){
        return axios({
          url: 'http://localhost:3300/user',
          params: args.queryParams
        }).then(result => result.data)
      },
    }
  },
})

在index.js中使用

javascript 复制代码
import express from 'express'; // yarn add express
import { createHandler } from 'graphql-http/lib/use/express';
import {QueryType} from './router/query'
import {GraphQLSchema} from "graphql/index";

const app = express();
const schema = new GraphQLSchema({
  query: QueryType,
});

app.all('/graphql', createHandler({
  schema
}));

app.listen({ port: 4000 });

此时请求时的query

javascript 复制代码
// queryParams 中可以放我们的入参
{
  user(queryParams: {}) {
    id
    name
    age
    gender
    grade {
      id
      Language
      Maths
      science
    }
  }
}

创建mutation请求

操作和query请求基本没什么区别

javascript 复制代码
const PostUserType = new GraphQLInputObjectType({
  name: 'PostUserType',
  fields: {
    name: {type: GraphQLString},
    age: {type: GraphQLString},
    gender: {type: GraphQLInt},
  }
})
export const MutationType = new GraphQLObjectType({
  name: 'Mutation',
  fields: {
    createUser: {
      type: GraphQLBoolean, 
      args: {
        postParams: { type: PostUserType}
      },
      resolve(parent, args) {
        return axios.post('http://localhost:3300/user', args.postParams)
          .then((response) => {
            return true
          })
          .catch(error => {
            // 处理错误情况
            console.error('Error creating user:', error.message);
            throw new Error('Failed to create user.');
          });
      }
    }
  }
});

然后再index.js中使用

javascript 复制代码
const schema = new GraphQLSchema({
  query: QueryType,
  mutation: MutationType
});
相关推荐
passerby606121 分钟前
完成前端时间处理的另一块版图
前端·github·web components
掘了28 分钟前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
崔庆才丨静觅31 分钟前
实用免费的 Short URL 短链接 API 对接说明
前端
崔庆才丨静觅1 小时前
5分钟快速搭建 AI 平台并用它赚钱!
前端
崔庆才丨静觅1 小时前
比官方便宜一半以上!Midjourney API 申请及使用
前端
Moment1 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
崔庆才丨静觅2 小时前
刷屏全网的“nano-banana”API接入指南!0.1元/张量产高清创意图,开发者必藏
前端
剪刀石头布啊2 小时前
jwt介绍
前端
爱敲代码的小鱼2 小时前
AJAX(异步交互的技术来实现从服务端中获取数据):
前端·javascript·ajax
Cobyte2 小时前
AI全栈实战:使用 Python+LangChain+Vue3 构建一个 LLM 聊天应用
前端·后端·aigc