Modify GraphQL source code Scalars

When I was learning graphql recently, there was a table with Date type data, but when setting the field type, I found that graphql only supports its basic types.

As shown in the figure:

Does not contain Date type data.

Forcibly use GarphQLString, the output data is as follows

So I thought of writing a method to support the Date type. I took a closer look at the Scalars source code and wrote one myself.

First look at the test results:

The final code is as follows:

MyScalars.java

package com.woodie.modifyoriginal;

import graphql.Scalars;
import graphql.schema.Coercing;
import graphql.schema.CoercingParseLiteralException;
import graphql.schema.GraphQLScalarType;

import java.text.SimpleDateFormat;
import java.util.Date;

public class MyScalars extends Scalars {

    /**
     * 定义一个新的方法
     */
    public static final GraphQLScalarType GraphQLDate = new GraphQLScalarType("Date", "Built-in Date", new Coercing<String, String>() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        public String serialize(Object input) {
            return sdf.format(input);
        }

        public String parseValue(Object input) {
            return this.serialize(sdf.format(input));
        }

        public String parseLiteral(Object input) {
            if (!(input instanceof Date)) {
                throw new CoercingParseLiteralException("Expected AST type 'Date' but was ");
            } else {
                return sdf.format(input);
            }
        }
    });
}

Entity class code:

Employee.java

package com.woodie.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;

import lombok.*;

import java.util.Date;

@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@TableName("employees")
public class Employee {
    // 指定表的id
    // 通过type = IdType.AUTO设置id的自动增长, 由于表employees没有设置id为自动增长,因此这里不能设置这个参数,否则报错
    //@TableId(value = "emp_no", type = IdType.AUTO)
    @TableId(value = "emp_no")
    Integer empNo;
    Date birthDate;
    String firstName;
    String lastName;
    Date hireDate;
    String gender;
}

Test code

GraphqlDemo.java

Here, the Date type field is passed in the custom type of MyScalars.GraphQLDate

package com.woodie;

import com.woodie.entity.Employee;
import com.woodie.modifyoriginal.MyScalars;
import graphql.ExecutionResult;
import graphql.GraphQL;
import graphql.Scalars;
import graphql.schema.GraphQLArgument;
import graphql.schema.GraphQLFieldDefinition;
import graphql.schema.GraphQLObjectType;
import graphql.schema.GraphQLSchema;

import java.text.SimpleDateFormat;
import java.util.Date;

public class GraphqlDemo {
    public static void main(String[] args) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        /**
         * type User { #定义对象
         */
        GraphQLObjectType employeeObjectType = GraphQLObjectType.newObject()
                .name("Employee")
                .field(GraphQLFieldDefinition.newFieldDefinition().name("empNo").type(Scalars.GraphQLInt))
                .field(GraphQLFieldDefinition.newFieldDefinition().name("birthDate").type(MyScalars.GraphQLDate))
                .field(GraphQLFieldDefinition.newFieldDefinition().name("hireDate").type(MyScalars.GraphQLDate))
//                .field(GraphQLFieldDefinition.newFieldDefinition().name("birthDate").type(Scalars.GraphQLString))
//                .field(GraphQLFieldDefinition.newFieldDefinition().name("hireDate").type(Scalars.GraphQLString))
                .field(GraphQLFieldDefinition.newFieldDefinition().name("gender").type(Scalars.GraphQLString))
                .field(GraphQLFieldDefinition.newFieldDefinition().name("firstName").type(Scalars.GraphQLString))
                .field(GraphQLFieldDefinition.newFieldDefinition().name("lastName").type(Scalars.GraphQLString))
                .build();

        /**
         * user : User #指定对象以及参数类型
         */
        GraphQLFieldDefinition userFieldDefinition = GraphQLFieldDefinition.newFieldDefinition()
                .name("employee")
                .type(employeeObjectType)
//                .dataFetcher(new StaticDataFetcher(new User(1L, "张三", 26)))
                .argument(GraphQLArgument.newArgument().name("empNo").type(Scalars.GraphQLLong).build())
                .dataFetcher(environment -> {
                    Long id = environment.getArgument("empNo");
                    // 查询数据库
                    // 这里需要设置modules中的sources中的language level: 为8-Lambdas.....
                    return Employee.builder().birthDate(new Date()).empNo(10001).gender("M").firstName("Woodie").lastName("Wang").hireDate(sdf.parse("2222- 03-14")).build();
                })
                .build();

        /**
         * type UserQuery { #定义查询的类型
         */
        GraphQLObjectType userQueryObjectType = GraphQLObjectType.newObject().name("UserQuery").field(userFieldDefinition).build();

        GraphQLSchema graphQLSchema= GraphQLSchema.newSchema().query(userQueryObjectType).build();

        GraphQL graphQL = GraphQL.newGraphQL(graphQLSchema).build();

//        user(id:1) 这里是设置参数 的意思
        String query = "{employee(empNo:10001){empNo,hireDate}}";
        ExecutionResult result = graphQL.execute(query);

//        System.out.println(result.getErrors());
//        System.out.println(result.getData());
        // graphql标准化输出数据
        System.out.println(result.toSpecification());
    }

}

 

Guess you like

Origin blog.csdn.net/qq_26896085/article/details/104854058