GraphQL(八)自定义Scalar

背景

Graph-java 在包中提供了除规范要求的几种类型,还新增了几种java特有的类型,比如BigDecimal,Byte。
GraphQL(八)自定义Scalar_第1张图片
当然我们也可以自己定义Scalar,接下来,以LocalDateTime为例,我们来实现自定义的Scalar。

参考其他built-定义的类型,自定义的Type需要实现三个方法,分别来序列化输入和输出。

GraphQLDate

package com.tangbaobao.graphql.service;

import graphql.schema.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author tangxuejun
 * @version 2020/4/5 5:50 下午
 */
public class GraphQLDate extends GraphQLScalarType {
    public static final String YYYY_MM_DD_HH_MM = "yyyy-MM-dd HH:mm";
    public GraphQLDate() {
        super("GraphQLDate", "GraphQLDate type", new Coercing<LocalDateTime, String>() {
            @Override
            public String serialize(Object dataFetcherResult) throws CoercingSerializeException {
                LocalDateTime localDateTime = (LocalDateTime) dataFetcherResult;
                return localDateTime.format(DateTimeFormatter.ofPattern(YYYY_MM_DD_HH_MM));
            }

            @Override
            public LocalDateTime parseValue(Object input) throws CoercingParseValueException {
                String value = String.valueOf(input);
                if ("null".equalsIgnoreCase(value) || "".equalsIgnoreCase(value)) {
                    return null;
                }
                return LocalDateTime.parse(value, DateTimeFormatter.ofPattern(YYYY_MM_DD_HH_MM));
            }

            @Override
            public LocalDateTime parseLiteral(Object input) throws CoercingParseLiteralException {
                String value = String.valueOf(input);
                if ("null".equalsIgnoreCase(value) || "".equalsIgnoreCase(value)) {
                    return null;
                }
                return LocalDateTime.parse(value, DateTimeFormatter.ofPattern(YYYY_MM_DD_HH_MM));
            }
        });

    }
}

CustomerScalar Schema

package com.tangbaobao.graphql.service;

import com.google.common.base.Charsets;
import com.google.common.io.Resources;
import graphql.GraphQL;
import graphql.schema.GraphQLScalarType;
import graphql.schema.GraphQLSchema;
import graphql.schema.StaticDataFetcher;
import graphql.schema.idl.RuntimeWiring;
import graphql.schema.idl.SchemaGenerator;
import graphql.schema.idl.SchemaParser;
import graphql.schema.idl.TypeDefinitionRegistry;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.net.URL;
import java.time.LocalDateTime;

/**
 * @author tangxuejun
 * @version 2020/4/5 4:16 下午
 */
@Component
public class CustomerScalar {

    private GraphQL graphQL;


    @PostConstruct
    public void init() throws IOException {
        URL url = Resources.getResource("customerscalar.graphqls");
        String sdl = Resources.toString(url, Charsets.UTF_8);
        GraphQLSchema graphQLSchema = buildSchema(sdl);

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

    private GraphQLSchema buildSchema(String sdl) {
        TypeDefinitionRegistry typeRegistry = new SchemaParser().parse(sdl);
        RuntimeWiring runtimeWiring = buildWiring();
        SchemaGenerator schemaGenerator = new SchemaGenerator();
        return schemaGenerator.makeExecutableSchema(typeRegistry, runtimeWiring);
    }

    private RuntimeWiring buildWiring() {
        return RuntimeWiring.newRuntimeWiring()
                .scalar(GraphQLScalarType.newScalar(new GraphQLDate()).build())
                .type("Query",
                        builder -> builder.dataFetcher("getCurrentTime", new StaticDataFetcher(LocalDateTime.now()))
                )
                .build();
    }


    @Bean
    public GraphQL graphQL() {
        return graphQL;
    }
}

customerscalar.graphqls

schema {
    query: Query
}

type Query{
    getCurrentTime:GraphQLDate
}
scalar GraphQLDate

结果

GraphQL(八)自定义Scalar_第2张图片

你可能感兴趣的:(GraphQL)