Graphql应用探索

记录一下graphql项目搭建的过程,graphql的原理啥的请参考如下优秀的文章:

http://blog.mygraphql.com/wordpress/?p=108

http://www.zhaiqianfeng.com/2017/06/learn-graphql-action-by-java.html

https://github.com/graphql-java/awesome-graphql-java

一:graphql服务生成

1,从代码构建,如下示例

    /**
     * 从代码生成graphql
     */
    private void LoadGraphQLFromCode() {
        //酒店品牌类型
        GraphQLObjectType brandInfoType = newObject().name("brandInfo").description("品牌信息")
                .field(newFieldDefinition().name("brandId").description("品牌id").type(GraphQLInt).build())
                .field(newFieldDefinition().name("brandName").description("品牌名称").type(GraphQLString).build())
                .field(newFieldDefinition().name("brandUrl").description("品牌url").type(GraphQLString).build())
                .build();
        //酒店设施类型
        GraphQLObjectType hotelFacilityType = newObject().name("hotelFacility").description("酒店设施")
                .field(newFieldDefinition().name("facilityId").description("设施id").type(GraphQLInt).build())
                .field(newFieldDefinition().name("facilityNameCn").description("中文名").type(GraphQLString).build())
                .field(newFieldDefinition().name("facilityTypeId").description("类型id").type(GraphQLInt).build())
                .build();

        //定义客户端使用的酒店详情类型
        GraphQLObjectType hotelDetailType = GraphQLObjectType.newObject()
                .name("HoteleDetailInfo")
                .description("酒店详情")
                .field(newFieldDefinition().name("hotelName").description("酒店名").type(GraphQLString).build())
                .field(newFieldDefinition().name("address").description("地址").type(GraphQLString).build())
                .field(newFieldDefinition().name("description").description("描述").type(GraphQLString).build())
                .field(newFieldDefinition().name("baiduLatitude").description("百度经纬度").type(GraphQLString).build())
                .field(newFieldDefinition().name("baiduLongitude").description("百度经纬度").type(GraphQLString).build())
                .field(newFieldDefinition().name("cityName").description("城市名").type(GraphQLString).build())
                .field(newFieldDefinition().name("trafficInfo").description("交通信息").type(GraphQLString).build())
                .field(newFieldDefinition().name("brandInfo").description("品牌信息").type(brandInfoType).build())
                .field(newFieldDefinition().name("hotelFacilityList").description("设施列表").type(new GraphQLList(hotelFacilityType)).build())
                .build();

//        //客户端看到的输入
//        GraphQLInputType hotelDetalInput = newInputObject()
//                .name("hotelDetailInput")
//                .field(GraphQLInputObjectField.newInputObjectField().name("hotelId").description("酒店id").type(GraphQLString).build())
//                .field(GraphQLInputObjectField.newInputObjectField().name("checkInDate").description("入住日期").type(GraphQLString).build())
//                .field(GraphQLInputObjectField.newInputObjectField().name("checkOutDate").description("离店日期").type(GraphQLString).build())
//                .build();

        //客户端的queryapi
        GraphQLObjectType queryType = GraphQLObjectType.newObject()
                .name("hotelDetailQuery")
                .field(GraphQLFieldDefinition.newFieldDefinition()
                        .type(hotelDetailType)
                        .name("hotelDetail")
                        .argument(GraphQLArgument.newArgument()
                                .name("hotelId")
                                .description("酒店id 必填")
                                .type(new GraphQLNonNull(GraphQLInt))
                                .build())
                        .argument(GraphQLArgument.newArgument()
                                .name("checkInDate")
                                .description("入住日期")
                                .type(GraphQLString)
                                .build())
                        .argument(GraphQLArgument.newArgument()
                                .name("checkOutDate")
                                .description("离店日期")
                                .type(GraphQLString)
                                .build())
                        .dataFetcher(env -> {
                            return hotelDetailDataFetcher(env);
                        })
                        .build())
                .build();

        //创建schema
        GraphQLSchema schema = GraphQLSchema.newSchema()
                .query(queryType)
                .build();

        //创建graphql
        GraphQL graphQL = GraphQL.newGraphQL(schema).build();
        HotelDetailGraphQl = graphQL;
    }

2,从graphql文件生成

schema{
    #酒店
    query : hotelDetailQuery
}
type hotelDetailQuery{
    #详情搜索
    hotelDetail(hotelId:Int!,checkInDate:String,checkOutDate:String):HoteleDetailInfo
    #酒店点评概要信息
    hotelComment(hotelId:Int!) : hotelCommentInfo
}
#酒店点评概要信息
type hotelCommentInfo{
    #点评总数
    commentCount:Int
    #点评分数
    commentScore:String
    #语义标签
    hotelDetailCommentTags:[hotelDetailCommentTagsType]
}
#点评标签类型
type hotelDetailCommentTagsType{
    #标签数
    commentCount:Int
    #类型id
    mainTagId:Int
    #类型名
    mainTagName:String
}
#品牌类型
type brandInfo{
    #品牌id
    brandId:Int
    #品牌名
    brandName:String
    #品牌链接
    brandUrl:String
}
#设施
type hotelFacility{
    #设施id
    facilityId:Int
    #设施名
    facilityNameCn:String
    #id
    facilityTypeId:String
}
#酒店详情
type HoteleDetailInfo{
    #名称
    hotelName:String
    #地址
    address:String
    #描述
    description:String
    #经纬度
    baiduLatitude:String
    #经纬度
    baiduLongitude:String
    #城市名
    cityName:String
    #交通信息
    trafficInfo:String
    #品牌信息
    brandInfo:brandInfo
    #设施信息
    hotelFacilityList:[hotelFacility]
}
/**
 * 从文本读取
 */
private void LoadGraphQLFromFile() {
    try {
        InputStream readin = GraphQLHotelDetailDao.class.getResourceAsStream("sdls/hoteldetail.graphql");
        InputStreamReader reader = new InputStreamReader(readin, "utf-8");
        SchemaParser schemaParser = new SchemaParser();
        SchemaGenerator schemaGenerator = new SchemaGenerator();
        TypeDefinitionRegistry typeRegistry = schemaParser.parse(reader);
        RuntimeWiring wiring = buildRuntimeWiring();
        GraphQLSchema schema = schemaGenerator.makeExecutableSchema(typeRegistry, wiring);

        //创建graphql
        GraphQL graphQL = GraphQL.newGraphQL(schema).build();
        HotelDetailGraphQl = graphQL;
    } catch (Exception e) {
        e.printStackTrace();
    }
}
    RuntimeWiring buildRuntimeWiring() {
        return RuntimeWiring.newRuntimeWiring()
                .type("hotelDetailQuery", typeWiring -> typeWiring
                        .dataFetcher("hotelDetail", getHotelDetailDataFetcher())
                )
                .type("hotelDetailQuery", typeWiring -> typeWiring
                        .dataFetcher("hotelComment", getHotelCommentDataFetcher()))
                .build();
    }
    private Object hotelDetailDataFetcher(DataFetchingEnvironment env) {
        int hotelId = env.getArgument("hotelId");
        String checkInDate = env.getArgument("checkInDate");
        String checkOutDate = env.getArgument("checkOutDate");

        Date checkIn;
        Date checkOut;
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            checkIn = format.parse(checkInDate);
            checkOut = format.parse(checkOutDate);
        } catch (Exception e) {
            e.printStackTrace();
            checkIn = new Date();
            Calendar c = Calendar.getInstance();
            c.setTime(checkIn);
            // 今天+1天
            c.add(Calendar.DAY_OF_MONTH, 1);
            checkOut = c.getTime();
        }
        String formatUrl = "****";
        String reqUrl = String.format(formatUrl, hotelId, checkIn.getTime() / 1000, checkOut.getTime() / 1000);
        String result = HttpClientHelper.sendGet2(reqUrl, null, "utf-8");
        HotelInfoBody hotelInfoModel = JSON.parseObject(result, HotelInfoBody.class);
        return hotelInfoModel.getBody().getHotelInfoModel();
    }
    DataFetcher getHotelCommentDataFetcher() {
        return new DataFetcher() {
            @Override
            public Object get(DataFetchingEnvironment env) {
                return hotelCommentInfoDataFetcher(env);
            }
        };
    }


二:预先生成graphql服务注入到controller,有请求进来直接查询就好了

            
阅读更多
文章标签: graphql
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

Graphql应用探索

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭