• GraphQL(7):ConstructingTypes


    1 使用GraphQLObjectType 定义type(类型)

    不使用ConstructingTypes定义方式如下:

    使用ConstructingTypes定义方式如下:

    更接近于构造函数方式

    1. var AccountType = new graphql.GraphQLObjectType({
    2. name: 'Account',
    3. fields: {
    4. name: { type: graphql.GraphQLString },
    5. age: { type: graphql.GraphQLInt },
    6. sex: { type: graphql.GraphQLString },
    7. department: { type: graphql.GraphQLString }
    8. }
    9. });

    2 使用GraphQLObjectType 定义Query(查询)

    不使用ConstructingTypes定义方式如下:

    使用ConstructingTypes定义方式如下:

    1. var queryType = new graphql.GraphQLObjectType({
    2. name: 'Query',
    3. fields: {
    4. account: {
    5. type: AccountType,
    6. // `args` describes the arguments that the `user` query accepts
    7. args: {
    8. username: { type: graphql.GraphQLString }
    9. },
    10. resolve: function (_, { username }) {
    11. const name = username;
    12. const sex = 'man';
    13. const age = 18;
    14. const department = '开发部';
    15. return {
    16. name,
    17. sex,
    18. age,
    19. department
    20. }
    21. }
    22. }
    23. }
    24. });

    3 创建schema

    var schema = new graphql.GraphQLSchema({ query: queryType });

    4 代码实现如下

    1. const express = require('express');
    2. const graphql = require('graphql');
    3. const grapqlHTTP = require('express-graphql').graphqlHTTP;
    4. var AccountType = new graphql.GraphQLObjectType({
    5. name: 'Account',
    6. fields: {
    7. name: { type: graphql.GraphQLString },
    8. age: { type: graphql.GraphQLInt },
    9. sex: { type: graphql.GraphQLString },
    10. department: { type: graphql.GraphQLString }
    11. }
    12. });
    13. var queryType = new graphql.GraphQLObjectType({
    14. name: 'Query',
    15. fields: {
    16. account: {
    17. type: AccountType,
    18. // `args` describes the arguments that the `user` query accepts
    19. args: {
    20. username: { type: graphql.GraphQLString }
    21. },
    22. resolve: function (_, { username }) {
    23. const name = username;
    24. const sex = 'man';
    25. const age = 18;
    26. const department = '开发部';
    27. return {
    28. name,
    29. sex,
    30. age,
    31. department
    32. }
    33. }
    34. }
    35. }
    36. });
    37. var schema = new graphql.GraphQLSchema({ query: queryType });
    38. const app = express();
    39. app.use('/graphql', grapqlHTTP({
    40. schema: schema,
    41. graphiql: true
    42. }))
    43. // 公开文件夹,供用户访问静态资源
    44. app.use(express.static('public'))
    45. app.listen(3000);

  • 相关阅读:
    vscode官方下载太慢解决办法
    为什么选择好的指纹浏览器是跨境电商的第一步?
    java-php-net-python-税务申报系统ssh计算机毕业设计程序
    向量以及矩阵
    算法训练 第四周
    flutter系列之:flutter中的变形金刚Transform
    2024.6.19刷题记录
    图纸管理制度《一》
    mysql-Optimization Overview-数据库调优
    WinCC趋势跨度设置(时间范围)
  • 原文地址:https://blog.csdn.net/u013938578/article/details/139621178