• 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);

  • 相关阅读:
    【MySQL】【数据库】如何进行严格的四舍五入
    Lua中如何实现类似gdb的断点调试—07支持通过函数名称添加断点
    百叶帘系统内置于玻璃内,分为手动和电动两种控制方式
    遇到项目难点
    xml文件操作
    网关限流功能性能优化
    【SQL】SQLAlchemy:如何使用Python ORM框架来操作MySQL?
    CASS11.0.0.4 for AutoCAD2010-2023免狗使用方法
    asp.net core webapi signalR通信
    数据库作为信息系统基础底座软件
  • 原文地址:https://blog.csdn.net/u013938578/article/details/139621178