GraphQL实践(三)-结果统一处理

GraphQL返回结果处理,由于提供的是REST接口,所以优先返回JSON格式数据,对执行结果使用JSON进行序列化。相关代码如下

package com.zte.sunquan.demo.graph.util;

import java.util.Map;

import lombok.extern.slf4j.Slf4j;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Preconditions;

/**
 * GraphResult class
 *
 * @author 10184538
 * @date 2019/6/25
 */
@Slf4j
public class GraphResult {

    private static final String ERRORS = "errors";
    private static final String DATA = "data";

    public static String resolve(Map<String, Object> result) {
        Preconditions.checkNotNull(result, "Result can not be null.");
        String data = null;
        try {
            if (result.containsKey(ERRORS)) {
                return JacksonJsonConverter.getInstance().serialize(result.get(ERRORS));
            } else {
                data = JacksonJsonConverter.getInstance().serialize(result.get(DATA));
            }
        } catch (JsonProcessingException e) {
            log.error("error", e);
        }
        return data;
    }


}

class JacksonJsonConverter {
    private static final JacksonJsonConverter instance = new JacksonJsonConverter();
    private ObjectMapper mapper = null;

    public static JacksonJsonConverter getInstance() {
        return instance;
    }

    private JacksonJsonConverter() {
        this.mapper = new ObjectMapper();
        this.mapper.configure(JsonGenerator.Feature.QUOTE_FIELD_NAMES, true);
        this.mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    public ObjectMapper getMapper() {
        return this.mapper;
    }

    public <T> String serialize(T object) throws JsonProcessingException {
        return this.mapper.writeValueAsString(object);

    }

}

调用方:

        Map<String, Object> variable = Maps.newHashMap();
        variable.put("first", "11");
        ExecutionInput executionInput = ExecutionInput.newExecutionInput().variables(variable).
                query("{user(first:1){name,gender,intro}}").build();
        //查询
        String resolve = GraphResult.resolve(graphQL.execute(executionInput).toSpecification());
        System.out.println(resolve);

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值