NutzCN Logo
精华 有没有nutzboot 整合graphql的例子
发布于 1882天前 作者 kidultx 1971 次浏览 复制 上一个帖子 下一个帖子
标签:

老大给点思路,应该怎么整合

12 回复

看了看官网的demo https://www.graphql-java.com/tutorials/getting-started-with-spring-boot/#graphql-in-3-minutes

把spring的注解稍微改造一下, 应该就可以了吧

@IocBean(create="init")
public class GraphQLProvider {

    private GraphQL graphQL;

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

    public void init() throws IOException {
        URL url = Resources.getResource("schema.graphqls");
        String sdl = Resources.toString(url, Charsets.UTF_8);
        GraphQLSchema graphQLSchema = buildSchema(sdl);
        this.graphQL = GraphQL.newGraphQL(graphQLSchema).build();
    }

    private GraphQLSchema buildSchema(String sdl) {
      // TODO: we will create the schema here later 
    }
}

试了一下,但是访问/graphql并不能进到这里面

NUTZ 整合 方案

	/**
	 * 查询业务列表
	 */
	@At("/graphql")
	@Ok("json")
	@POST
	@AdaptBy(type = GraphQLAdaptor.class)
	public Object graphql(@Param("..")String sql ,
			HttpServletRequest req) {
		init();

		GraphQL graphQL = new GraphQL.Builder(schema).build();

        ExecutionResult result = graphQL.execute(sql);

		return result;

	}
       static GraphQLSchema schema = null;
	public GraphQLSchema init(){
		if(schema!=null){
			return schema;
		}
		schema =new GraphQLSchemaGenerator()
				.withBasePackages("io.leangen")
				.withOperationsFromSingleton(apiService) //register the service
				.generate();
		return schema;
	}

个人手写: Adapter

package cn.tico.iot.configmanger.common.adaptor;

import org.nutz.json.Json;
import org.nutz.lang.Lang;
import org.nutz.lang.Streams;
import org.nutz.mvc.HttpAdaptor;
import org.nutz.mvc.adaptor.PairAdaptor;
import org.nutz.mvc.adaptor.ParamInjector;
import org.nutz.mvc.adaptor.injector.JsonInjector;
import org.nutz.mvc.adaptor.injector.VoidInjector;
import org.nutz.mvc.annotation.Param;
import org.nutz.mvc.impl.AdaptorErrorContext;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Reader;a
import java.lang.reflect.Type;

public class GraphQLAdaptor extends PairAdaptor {

        protected ParamInjector evalInjector(Type type, Param param) {
            if (param == null || "..".equals(param.value())) {

                return new GraphQLInjector(type);
            }
            return super.evalInjector(type, param);
        }

        public Object getReferObject(ServletContext sc,
                                     HttpServletRequest req,
                                     HttpServletResponse resp, String[] pathArgs) {
            try {
                Reader reader = Streams.utf8r(req.getInputStream());
                return Streams.read(reader).toString();
            }
            catch (Exception e) {
                throw Lang.wrapThrow(e);
            }
        }
    }

POST MAN 导出请求

POST /api/graphql HTTP/1.1
Host: localhost:8090
Content-Type: application/json
User-Agent: PostmanRuntime/7.16.3
Accept: */*
Cache-Control: no-cache
Postman-Token: 5ac382e5-7626-46b6-957a-780b10d3f02b,8ec1bc92-9421-421c-af1a-3ce306a60e57
Host: localhost:8090
Accept-Encoding: gzip, deflate
Content-Length: 1441
Cookie: sid=t690h754v0iv9rt3j0upsl7nli
Connection: keep-alive
cache-control: no-cache

query{
	device(sno:"FD154430C49FD7")  {
		id,sno
		,order_time,quality,discard_time
		,asset_status,alert_status
		,i18n
		,cn_name
		,en_name
		,price
		,gateway{
			id,i18n,cn_name,en_name
			,env
			,sno
			,git_path
			,desription
			,subgateway{
				id,ext_sno,sno,ext_ip
			}
			,i18n
			,env
			,dept{
				id
				,dept_name
				,order_num
				,leader
				,phone
				,email
			}
			,tags{i18n,cn_name,en_name}
			,kind{i18n,cn_name,en_name}
			,location{i18n,cn_name,en_name}
		}
		,env
		,tags{
			id,i18n,cn_name,en_name
			,dept{
				id
				,dept_name
			
			}
		}
		,kinds{id,i18n,cn_name,en_name,level,order_num}
		,locations{id,i18n,cn_name,en_name,level,order_num}

		,dept{
			id
			,dept_name
			,order_num
			,leader
			,phone
			,email
		}
		,driver{
			id,i18n,cn_name,en_name
			,normals{
				id,i18n,cn_name,en_name
				,operate_key
				,unit
				,order_num
				,status
				,person(sno:"FD154430C49FD7"){
					id,i18n,cn_name,en_name
					,status
					,grades{
						id,i18n,cn_name,en_name
						,grade
						,order_num				
						,rulers{
							id,i18n,logic,val,symble
							,order_num	
							,normal{
								id,i18n,cn_name,en_name
								,unit
							}
						}
					}
				}
				,grades{
					id,i18n,cn_name,en_name
					,grade
					,order_num
					,rulers{
						id,i18n,logic,val,symble
						,order_num	
						,normal{
							id,i18n,cn_name,en_name
							,unit
						}
	
					}
				}
			}
			
			
		}




}}

POST MAN 导出Java

OkHttpClient client = new OkHttpClient();

MediaType mediaType = MediaType.parse("text/plain");
RequestBody body = RequestBody.create(mediaType, "query{\n\tdevice(sno:\"FD154430C49FD7\")  {\n\t\tid,sno\n\t\t,order_time,quality,discard_time\n\t\t,asset_status,alert_status\n\t\t,i18n\n\t\t,cn_name\n\t\t,en_name\n\t\t,price\n\t\t,gateway{\n\t\t\tid,i18n,cn_name,en_name\n\t\t\t,env\n\t\t\t,sno\n\t\t\t,git_path\n\t\t\t,desription\n\t\t\t,subgateway{\n\t\t\t\tid,ext_sno,sno,ext_ip\n\t\t\t}\n\t\t\t,i18n\n\t\t\t,env\n\t\t\t,dept{\n\t\t\t\tid\n\t\t\t\t,dept_name\n\t\t\t\t,order_num\n\t\t\t\t,leader\n\t\t\t\t,phone\n\t\t\t\t,email\n\t\t\t}\n\t\t\t,tags{i18n,cn_name,en_name}\n\t\t\t,kind{i18n,cn_name,en_name}\n\t\t\t,location{i18n,cn_name,en_name}\n\t\t}\n\t\t,env\n\t\t,tags{\n\t\t\tid,i18n,cn_name,en_name\n\t\t\t,dept{\n\t\t\t\tid\n\t\t\t\t,dept_name\n\t\t\t\n\t\t\t}\n\t\t}\n\t\t,kinds{id,i18n,cn_name,en_name,level,order_num}\n\t\t,locations{id,i18n,cn_name,en_name,level,order_num}\n\n\t\t,dept{\n\t\t\tid\n\t\t\t,dept_name\n\t\t\t,order_num\n\t\t\t,leader\n\t\t\t,phone\n\t\t\t,email\n\t\t}\n\t\t,driver{\n\t\t\tid,i18n,cn_name,en_name\n\t\t\t,normals{\n\t\t\t\tid,i18n,cn_name,en_name\n\t\t\t\t,operate_key\n\t\t\t\t,unit\n\t\t\t\t,order_num\n\t\t\t\t,status\n\t\t\t\t,person(sno:\"FD154430C49FD7\"){\n\t\t\t\t\tid,i18n,cn_name,en_name\n\t\t\t\t\t,status\n\t\t\t\t\t,grades{\n\t\t\t\t\t\tid,i18n,cn_name,en_name\n\t\t\t\t\t\t,grade\n\t\t\t\t\t\t,order_num\t\t\t\t\n\t\t\t\t\t\t,rulers{\n\t\t\t\t\t\t\tid,i18n,logic,val,symble\n\t\t\t\t\t\t\t,order_num\t\n\t\t\t\t\t\t\t,normal{\n\t\t\t\t\t\t\t\tid,i18n,cn_name,en_name\n\t\t\t\t\t\t\t\t,unit\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t,grades{\n\t\t\t\t\tid,i18n,cn_name,en_name\n\t\t\t\t\t,grade\n\t\t\t\t\t,order_num\n\t\t\t\t\t,rulers{\n\t\t\t\t\t\tid,i18n,logic,val,symble\n\t\t\t\t\t\t,order_num\t\n\t\t\t\t\t\t,normal{\n\t\t\t\t\t\t\tid,i18n,cn_name,en_name\n\t\t\t\t\t\t\t,unit\n\t\t\t\t\t\t}\n\t\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t}\n\n\n\n\n}}");
Request request = new Request.Builder()
  .url("http://localhost:8090/api/graphql")
  .post(body)
  .addHeader("Content-Type", "application/json")
  .addHeader("User-Agent", "PostmanRuntime/7.16.3")
  .addHeader("Accept", "*/*")
  .addHeader("Cache-Control", "no-cache")
  .addHeader("Postman-Token", "5ac382e5-7626-46b6-957a-780b10d3f02b,409b7ab7-b910-437b-9096-0a58cfb2376a")
  .addHeader("Host", "localhost:8090")
  .addHeader("Accept-Encoding", "gzip, deflate")
  .addHeader("Content-Length", "1441")
  .addHeader("Cookie", "sid=t690h754v0iv9rt3j0upsl7nli")
  .addHeader("Connection", "keep-alive")
  .addHeader("cache-control", "no-cache")
  .build();

Response response = client.newCall(request).execute();

数据库查寻

package cn.tico.iot.configmanger.module.iot.graphql;

import cn.tico.iot.configmanger.module.iot.models.base.Kind;
import cn.tico.iot.configmanger.module.iot.models.base.Location;
import cn.tico.iot.configmanger.module.iot.models.device.*;
import cn.tico.iot.configmanger.module.iot.models.driver.Driver;
import cn.tico.iot.configmanger.module.iot.models.driver.Grade;
import cn.tico.iot.configmanger.module.iot.models.driver.Normal;
import cn.tico.iot.configmanger.module.iot.models.driver.Ruler;
import cn.tico.iot.configmanger.module.iot.services.DeviceService;
import cn.tico.iot.configmanger.module.iot.services.DriverService;
import io.leangen.graphql.annotations.GraphQLArgument;
import io.leangen.graphql.annotations.GraphQLContext;
import io.leangen.graphql.annotations.GraphQLQuery;
import org.nutz.boot.starter.caffeine.Cache;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Lang;
import org.nutz.lang.Strings;

import java.util.Iterator;
import java.util.List;


@IocBean
public class ApiService {
    @Inject
    private DeviceService device;

    @Inject
    private DriverService driver;

    @Inject
    private Dao dao;

    @GraphQLQuery(name = "device")
    public Device getDeviceBySno(@GraphQLArgument(name = "sno") String sno) {
        System.out.println("maodajun ---> sno:" + sno);
        if (Strings.isBlank(sno)) {
            return null;
        }
        Cnd cnd = Cnd.NEW();
        cnd.and("t_iot_devices.sno", "=", sno);
        cnd.and("t_iot_devices.delflag","=","false");
        List<Device> devices = dao.queryByJoin(Device.class, "^dept|kind|location|driver|gateway|tags$", cnd);
        Iterator<Device> it = devices.iterator();
        if (it.hasNext()) {
            return devices.get(0);
        }
        return null;
    }


    @GraphQLQuery(name = "normals")
    public List<Normal> getNormals(@GraphQLContext Driver driver) {
        Cnd cnd = Cnd.NEW();
        cnd.and("driver_id", "=", driver.getId());
        cnd.and("delflag","=","false");

        cnd.orderBy("order_num", "asc");

        List<Normal> result = dao.query(Normal.class, cnd);
        return result;
    }



    @GraphQLQuery(name = "kinds")
    public List<Kind> getKinds(@GraphQLContext Device device) {
        Kind kind = dao.fetch(Kind.class, device.getKindid());
        String ids[] = kind.getAncestors().split(",");
        Cnd cnd = Cnd.NEW();
        cnd.and("id", "in", ids);
        cnd.and("level", ">", "0");
        cnd.and("delflag","=","false");

        cnd.orderBy("level", "asc");

        List<Kind> result = dao.query(Kind.class, cnd);
        result.add(kind);
        return result;
    }

    @GraphQLQuery(name = "locations")
    public List<Location> getlocations(@GraphQLContext Device device) {
        Location location = dao.fetch(Location.class, device.getLocationid());
        String ids[] = location.getAncestors().split(",");
        Cnd cnd = Cnd.NEW();
        cnd.and("id", "in", ids);
        cnd.and("level", ">", "0");
        cnd.and("delflag","=","false");

        cnd.orderBy("level", "asc");
        List<Location> result = dao.query(Location.class, cnd);
        result.add(location);
        return result;
    }

    @GraphQLQuery(name = "persons")
    public List<Person> getPersons(@GraphQLContext Device device) {
        Cnd cnd = Cnd.NEW();
        cnd.and("t_iot_persons.device_id", "=", device.getId());
        cnd.and("t_iot_persons.delflag","=","false");

        List<Person> result = dao.queryByJoin(Person.class, "^person|grades|device|normal$", cnd);
        return result;
    }

    @GraphQLQuery(name = "person")
    public Person onePerson(@GraphQLContext Normal normal, @GraphQLArgument(name = "sno") String sno) {
        List<Device> devices = dao.query(Device.class
                , Cnd.NEW()
                        .and("sno", "=", sno)
                        .and("delflag","=","false"));
        if (Lang.isEmpty(devices)) {
            return null;
        }
        Device device = devices.get(0);

        Cnd cnd = Cnd.NEW();
        cnd.and("normal_id", "=", normal.getId());
        cnd.and("device_id", "=", device.getId());
        cnd.and("delflag","=","false");

        List<Person> persons = dao.query(Person.class, cnd);
        if (Lang.isEmpty(persons)) {
            return null;
        }
        return persons.get(0);
    }

    @GraphQLQuery(name = "grades")
    public List<PersonGrade> gradesByPerson(@GraphQLContext Person person) {
        Cnd cnd = Cnd.NEW();
        cnd.and("person_id", "=", person.getId());
        cnd.and("delflag","=","false");

        List<PersonGrade> result = dao.query(PersonGrade.class, cnd);
        return result;

    }

    @GraphQLQuery(name = "grades")
    public List<Grade> getGrades(@GraphQLContext Normal normal) {
        Cnd cnd = Cnd.NEW();
        cnd.and("normal_id", "=", normal.getId());
        cnd.and("delflag","=","false");

        List<Grade> result = dao.query(Grade.class, cnd);
        return result;
    }

    @GraphQLQuery(name = "rulers")
    public List<Ruler> getDriver(@GraphQLContext Grade grade) {
        Cnd cnd = Cnd.NEW();
        cnd.and("t_iot_rulers.grade_id", "=", grade.getId());
        cnd.and("t_iot_rulers.delflag","=","false");

        List<Ruler> result = dao.queryByJoin(Ruler.class, "^normal$", cnd);
        return result;
    }


    @GraphQLQuery(name = "rulers")
    public List<PersonRuler> getPersonRulers(@GraphQLContext PersonGrade grade) {
        Cnd cnd = Cnd.NEW();
        cnd.and("t_iot_person_rulers.grade_id", "=", grade.getId());
        cnd.and("t_iot_person_rulers.delflag","=","false");

        List<PersonRuler> result = dao.queryByJoin(PersonRuler.class,"^normal$", cnd);
        return result;
    }
    @GraphQLQuery(name = "subgateway")
    public SubGateway getSubGateWay(@GraphQLContext Gateway gateway) {
        if(Lang.isEmpty(gateway)){
            return null;
        }
        if(Strings.isEmpty(gateway.getSubid())){
            return null;
        }

        SubGateway subGateway = dao.fetch(SubGateway.class,gateway.getSubid());
        if(Lang.isEmpty(subGateway)){
            return null;
        }


        return subGateway;
    }
}

Model

package cn.tico.iot.configmanger.module.iot.models.device;

import cn.tico.iot.configmanger.common.utils.excel.annotation.ExcelField;
import cn.tico.iot.configmanger.module.iot.models.DeviceEnvModel;
import cn.tico.iot.configmanger.module.iot.models.driver.Driver;
import io.leangen.graphql.annotations.GraphQLQuery;
import lombok.*;
import org.nutz.dao.entity.annotation.*;

import java.io.Serializable;
import java.util.List;


@Data
@Table("t_iot_devices")
public class Device extends DeviceEnvModel implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * SNO 机器码
     */
    @Column("sno")
    @Comment("机器码")
    @ColDefine(type = ColType.VARCHAR, width = 32)
    @GraphQLQuery(name = "sno", description = "机器码")
    @ExcelField(title="sno",value="sno")
    private String sno;

    @Column("price")
    @Comment("价格")
    @ColDefine(type = ColType.FLOAT  )
    @GraphQLQuery(name = "price", description = "价格")
    @ExcelField(title="价格",value = "")

    private Double price;


    @Column("order_time")
    @Comment("购买日期")
    @ColDefine(type = ColType.INT, width = 32)
    @GraphQLQuery(name = "order_time", description = "购买日期")
    @ExcelField(title="购买日期")
    private Long orderTime;



    @Column("quality")
    @Comment("使用年限")
    @ColDefine(type = ColType.INT, width = 32)
    @GraphQLQuery(name = "quality", description = "使用年限")
    @ExcelField(title="使用年限")
    private Integer quality;

    @Column("discard_time")
    @Comment("报废时间")
    @ColDefine(type = ColType.INT, width = 32)
    @GraphQLQuery(name = "discard_time", description = "报废时间")
    @ExcelField(title="报废时间")
    private Long discardTime;

    @Column("asset_status")
    @Comment("资产状态,0,1,2")
    @ColDefine(type = ColType.VARCHAR, width = 32)
    @GraphQLQuery(name = "asset_status", description = "资产状态")
    @ExcelField(title="资产状态")
    private String assetStatus ="0";


    @Column("alert_status")
    @Comment("告警状态")
    @ColDefine(type = ColType.VARCHAR, width = 32)
    @GraphQLQuery(name = "alert_status", description = "告警状态")
    @ExcelField(title="告警状态")
    private String alertStatus="normal";

    /**
     * 网关
     */
    @Column("gateway_id")
    @Comment("网关")
    @ExcelField(title="所属网关")
    private String gatewayid;

    /**
     * 所属网关,SNO
     */
    @Column("gateway_extsno")
    @Comment("冗余的SNO")
    private String gatewayExtsno;

    @One(field = "gatewayid",key="id")
    @GraphQLQuery(name = "gateway", description = "网关")
    private Gateway gateway;

    /**
     * 驱动
     */
    @Column("driver_id")
    @Comment("驱动")
    @ExcelField(title = "驱动名称")
    private String driverid;


    @One(field = "driverid",key="id")
    @GraphQLQuery(name = "driver", description = "驱动")
    private Driver driver;


    @Many(field = "deviceid")
    @GraphQLQuery(name = "persons", description = "个性化规则")
    private List<Person> persons;





}

@loveexception 有空做个demo项目?

@loveexception demo源码能否打包上传一下?

添加回复
请先登陆
回到顶部