当前位置:网站首页>Code generation of DGS
Code generation of DGS
2022-07-23 23:39:00 【Hello y】
Code generation plug-in for the first time
DGS Code generation plug-ins are in the process of building your project , According to your Domain Graph Service Of GraphQL Schema file generates code . The plug-in generates the following .
- type 、 Input type 、 Enumeration and interface data types .
- A containing type and field name DgsConstants class
- An example of a data extractor
- A type safe query that represents your query API
// Using plugins DSL
plugins {
id "com.netflix.dgs.codegen" version "5.2.4"
}
The plug-in adds a generateJava Of Gradle Mission , Run as part of the project build . generateJava In the construction of the project / Generate code under the generation directory . Please note that , stay Kotlin In the project ,generateJava Tasks are generated by default Kotlin Code ( Yes , This name is very confusing ). This folder will be automatically added to the project classpath in . Type is as packageName.types Part of the specified package , Among them, you specify packageName The value of build.gradle Configuration in file . Please make sure that the source code of your project uses the specified package name to reference the generated code .
generateJava Generate data extractor , And put it in build/generated-examples in .
generateJava{
schemaPaths = ["${projectDir}/src/main/resources/schema"] // List of directories containing schema files
packageName = 'com.openbayes.testDgs' // The package name to use to generate sources
generateClient = true // Enable generating the type safe query API
}
generateJava The data extractor it generates will not be added to your project source . These fetchers are mainly used as basic template code , You need to further realize .
You can exclude some parts of the schema from code generation , The way is to put them in a different schema directory , This directory is not for plug-ins schemaPaths Part of is designated .
Repair "Could not initialize class graphql.parser.antlr.GraphqlLexer " problem
Gradle Our plug-in system uses a flat classpath, This makes it easy to encounter classpath Conflict .Codegen A dependency of the plug-in is ANTLR, Unfortunately , Other plug-ins are also using it . If you see a mistake , For example, unable to initialize graphql.parser.antlr.GraphqlLexer class , This usually indicates that there is a classpath Conflict . If this happens , Please change the order of plug-ins in your build script .ANTLR It is usually backward compatible , But not forward compatible .
For multi module projects, it means that you need to declare in the root build file Codegen plug-in unit , Instead of using it .
plugins {
id("com.netflix.dgs.codegen") version "[REPLACE_WITH_CODEGEN_PLUGIN_VERSION]" apply false
//other plugins
}
In the module where the plug-in should be applied , You specify the plug-in again in the plug-in block , But there is no version .
plugins {
id("com.netflix.dgs.codegen")
}
Map existing types
Codegen Try to generate a type for each type it finds in the schema , But there are a few exceptions .
- Basic scalar type – Mapped to the corresponding Java/Kotlin type (String, Integer etc. ).
- Date and time type – Mapped to the corresponding java.time class .
- PageInfo and RelayPageInfo– Mapped to graphql.relay class .
- use typeMapping Configure the type of mapping
When you have an existing class you want to use , Instead of generating a class for a type , You can use typeMapping To configure the plug-in .typeMapping Configuration is a Map, Each of these keys is GraphQL type , Each value is a fully qualified Java/Kotlin type .
generateJava{
typeMapping = ["MyGraphQLType": "com.mypackage.MyJavaType"]
}
Generate client API
Code generators can also create clients API class . You can use these classes to start with Java Of GraphQL Endpoint query data , Or use in unit tests QueryExecutor.Java GraphQL The client is very useful for server to server communication .GraphQL Java The client is available as part of the framework .
Code generation creates a field name for each query and mutation field GraphQLQuery.GraphQLQuery The query class contains each parameter of the field . For each type returned by query or mutation , Code generation creates a ProjectionRoot. A projection is a builder class , It specifies which fields will be returned .
Here is a generated API Use example of .
GraphQLQueryRequest graphQLQueryRequest =
new GraphQLQueryRequest(
new TicksGraphQLQuery.Builder()
.first(first)
.after(after)
.build(),
new TicksConnectionProjection()
.edges()
.node()
.date()
.route()
.name()
.votes()
.starRating()
.parent()
.grade());
This API It is generated based on the following pattern . The type of edge and node is because this mode uses paging . The API Allow queries to be written in a fluent style , It's almost the same as writing a query as String It feels the same , But there are additional benefits of code completion and type safety .
type Query @extends {
ticks(first: Int, after: Int, allowCached: Boolean): TicksConnection
}
type Tick {
id: ID
route: Route
date: LocalDate
userStars: Int
userRating: String
leadStyle: LeadStyle
comments: String
}
type Votes {
starRating: Float
nrOfVotes: Int
}
type Route {
routeId: ID
name: String
grade: String
style: Style
pitches: Int
votes: Votes
location: [String]
}
type TicksConnection {
edges: [TickEdge]
}
type TickEdge {
cursor: String!
node: Tick
}
Generate queries for external services API
Generate the above query API For testing your own DGS Very useful . With another GraphQL When services interact , Same type API It's also very useful. , Your code is the client of the service . This is usually done with DGS The client finished .
When you use code generation for your own patterns and internal patterns , You may want to use different code generation configurations for both . It is recommended to create a separate module in your project , Include patterns and... Of external services codegen To configure , Only one query is generated API. The following is generate query only API Configuration instance of .
generateJava {
schemaPaths = ["${projectDir}/composed-schema.graphqls"]
packageName = "some.other.service"
generateClient = true
generateDataTypes = false
skipEntityQueries = true
includeQueries = ["hello"]
includeMutations = [""]
shortProjectionNames = true
maxProjectionDepth = 2
}
Restrict client API Build code for
If your pattern is large or has many cycles , Generate clients for the entire schema API Not ideal , Because you will eventually have a lot of projections . This may cause code generation to slow down significantly , Or run out of memory according to your mode . We have some configuration parameters to help adjust , So you can put the client API The generation of is limited to only the required parts .
generateJava {
...
generateClient = true
skipEntityQueries = true
includeQueries = ["hello"]
includeMutations = [""]
includeSubscriptions = [""]
maxProjectionDepth = 2
}
First , You can go through includeQueries、includeMutations and includeSubscriptions To specify which queries to generate / variation / subscribe . skipEntityQueries Only if you build a union for testing purposes _entities Use when querying , So you can also set it to limit the amount of code generated . Last ,maxProjectionDepth Will instruct codegen Stop generation. It starts from the root of the query and exceeds 2 Graphics of layers . The default value is 10. This will also help further limit the number of projections .
Configure code generation
Code generation has many configuration switches . The following table shows Gradle Configuration options , But the same options are on the command line and Maven It's also available in .


边栏推荐
- How are you preparing for the Android golden nine silver ten interview? The latest Android Interview Questions Summary helps you prepare for the war
- [ssm] joint debugging of front and rear protocols ①
- 第七章、测试架构元素
- strncat() strncmp()
- FreeRTOS personal notes - create / delete dynamic tasks, start scheduler
- PHP(2)
- STM32 can initialization details
- ciscn_ 2019_ n_ one
- What is the difference between go run, go build and go install
- Tensorflow one layer neural network training handwritten digit recognition
猜你喜欢

Redis集群搭建(Cluster 集群模式,分片集群)

DGS之Mutations

How are you preparing for the Android golden nine silver ten interview? The latest Android Interview Questions Summary helps you prepare for the war
![[OGeek2019]babyrop](/img/7a/18e8b985629488346e596cdf2a215c.png)
[OGeek2019]babyrop

DGS的错误处理
![[第五空间2019 决赛]PWN5](/img/51/03e6078961a8eab991fa08bb178a7b.png)
[第五空间2019 决赛]PWN5

TOPSIS method (matlab)
![[audio and video technology] video quality evaluation MSU vqmt & Netflix vmaf](/img/1c/bc71ba1eb3723cdd80501f2b0ad5ce.png)
[audio and video technology] video quality evaluation MSU vqmt & Netflix vmaf
![[web vulnerability exploration] SQL injection vulnerability](/img/94/dc84d7790d5a1823e4b73d513e86be.png)
[web vulnerability exploration] SQL injection vulnerability

A great open source micro community light forum source code
随机推荐
cannot meet the needs of the people? How can programmers take private jobs to effectively increase their income?
Grey prediction (matlab)
Navicat15 download and installation
[CTF] Tiange team writeup - the first digital space security attack and defense competition (Preliminary)
ret2text
Solidity-delegateCall插槽冲突分析与解决
二,数字逻辑功能单元
jarvisoj_level2
Baidu editor uploads pictures and sets custom directories
No wonder the application effect of ERP in domestic enterprises is generally not ideal
PHP(2)
线程池串行化
Android金九银十的面试你准备的怎么样了?最新Android面试真题汇总助你备战
Chinese NFT? NFR was born
ciscn_ 2019_ n_ one
warmup_ csaw_ two thousand and sixteen
正则表达式及绕过案例
This article will show you what typescript is
Is Zhongyuan securities reliable? Is it legal? Is it safe to open a stock account?
第六章、实现一个持久性适配器