定义

graphql介绍

使用

第一步:初始化一个项目,不用做太多配置,我们只是为了测试graphql,所以创建项目的话一路回车就行

  1. npm init

第二步:下载graphql相关,因为我们想要在node中潜入graphql,使用框架是express,所以需要express和express-graphql

  1. yarn add graphql express express-graphql

第三步:下载babel相关,因为我写graphql可能需要用到一些es6写法(暂时不用)

  1. yarn add @babel/cli @babel/core @babel/node

第四步配置package.json

  1. "scripts": {
  2. // nodemon如果没有,需要下载
  3. "dev": "nodemon index.js --exec babel-node --presets @babel/preset-env",
  4. "test": "echo \"Error: no test specified\" && exit 1"
  5. }

第五步,创建一个index.js,用express启动一个服务:http://localhost:5000

  1. import express from 'express';
  2. const app = express();
  3. app.use((req, res) => {
  4. res.send('welcome');
  5. })
  6. app.listen(5000);

下面,我们就可以进行graphql配置了

  1. // index.js
  2. import {
  3. graphqlHTTP
  4. } from 'express-graphql';
  5. import GraphqlSchema from './GraphqlSchema';
  6. const app = express();
  7. // 启动一个graphql服务,可以进行可视化查询操作
  8. app.use(
  9. '/graphql',
  10. graphqlHTTP({
  11. schema: GraphqlSchema,
  12. graphiql: true,
  13. }),
  14. );
  15. app.listen(5000);

新建一个GraphqlSchema.js文件,进行graphql的schema配置

  1. import {
  2. graphql,
  3. GraphQLSchema,
  4. GraphQLObjectType,
  5. GraphQLString,
  6. GraphQLList,
  7. GraphQLInt
  8. } from 'graphql';
  9. var schema = new GraphQLSchema({
  10. query: new GraphQLObjectType({
  11. name: 'RootQueryType',
  12. fields: {
  13. hello: {
  14. type: GraphQLString,
  15. resolve() {
  16. return 'world';
  17. },
  18. }
  19. }
  20. })
  21. });
  22. export default schema;

启动命令:
npm run dev
在浏览器中输入:http://localhost:5000/graphql即可启动graphql服务器,同时输入查询语句,则可以进行可视化查询,如图
image.png
我们还可以配置一些更复杂的数据

  1. // GraphqlSchema.js
  2. let HelloType = new GraphQLObjectType({
  3. name: 'HelloType',
  4. fields: {
  5. name: {
  6. type: GraphQLString
  7. },
  8. age: {
  9. type: GraphQLInt
  10. },
  11. phone: {
  12. type: GraphQLString
  13. }
  14. }
  15. })
  16. var schema = new GraphQLSchema({
  17. query: new GraphQLObjectType({
  18. name: 'RootQueryType',
  19. fields: {
  20. hello: {
  21. type: new GraphQLList(HelloType),
  22. resolve() {
  23. return [
  24. {
  25. name: 'tom',
  26. age: 18,
  27. phone: '323243434'
  28. },
  29. {
  30. name: 'jerry',
  31. age: 10,
  32. phone: '1123333'
  33. },
  34. {
  35. name: 'hahah',
  36. age: 48,
  37. phone: '222233444'
  38. }
  39. ];
  40. }
  41. }
  42. }
  43. })
  44. });