graphql dgs springboot gradle学习

简介: https://dgraphql dgs springboot gradle学习
1.gradle相关信息

import org.jetbrains.kotlin.gradle.tasks.KotlinCompile

plugins {
  id("org.springframework.boot") version "2.5.6"
  id("io.spring.dependency-management") version "1.0.11.RELEASE"
  kotlin("jvm") version "1.6.21"
  kotlin("plugin.spring") version "1.6.21"
  id("com.netflix.dgs.codegen") version "5.1.16"
}

group = "com.ityu"
version = "0.0.1-SNAPSHOT"
java.sourceCompatibility = JavaVersion.VERSION_11

configurations {
  compileOnly {
    extendsFrom(configurations.annotationProcessor.get())
  }
}

repositories {
  mavenCentral()
}

dependencies {
  implementation("org.springframework.boot:spring-boot-starter-web")
  implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
  implementation("org.jetbrains.kotlin:kotlin-reflect")
  implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")


  implementation(platform("com.netflix.graphql.dgs:graphql-dgs-platform-dependencies:latest.release"))
  implementation ("com.netflix.graphql.dgs:graphql-dgs-spring-boot-starter")
  implementation("com.netflix.graphql.dgs:graphql-dgs-extended-scalars")
  implementation("com.github.javafaker:javafaker:1.+")

  implementation ("org.springframework.boot:spring-boot-starter-test")
  developmentOnly("org.springframework.boot:spring-boot-devtools")
  annotationProcessor("org.springframework.boot:spring-boot-configuration-processor")
  testImplementation("org.springframework.boot:spring-boot-starter-test")
}

tasks.withType<KotlinCompile> {
  kotlinOptions {
    freeCompilerArgs = listOf("-Xjsr305=strict")
    jvmTarget = "11"
  }
}
//
tasks.withType<com.netflix.graphql.dgs.codegen.gradle.GenerateJavaTask> {
  generateClient = true
  packageName = "com.ityu.demo.generated"
}

tasks.withType<Test> {
  useJUnitPlatform()
}

2. 添加resources/schema/schema.graphql
type Query {
    #方法返回数组
    events:[Event!]!
}

type Mutation {
   createEvent(eventInput:EventInput!):Event!
}

input EventInput{
    title:String!
    description:String!
    price:String!
    data:String!
}


type Event{
    id:ID!
    title:String!
    description:String!
    price:String!
    data:String!
}
3. java代码
@DgsComponent
class EventDataFetcher {

    private val events = mutableListOf<Event>()

    @DgsQuery
    fun events(): MutableList<Event> {
        return events
    }

    @DgsMutation
    fun createEvent(@InputArgument eventInput: EventInput): Event {
        val event = Event(
            UUID.randomUUID().toString(),
            eventInput.title,
            eventInput.description,
            eventInput.price,
            eventInput.data
        )
        events.add(event)
        return event

    }
}
4.打开浏览器工具

graphiql

graphql

mutation{
  createEvent(eventInput:{
     title:"title2",
    description:"description 2",
    price:"50.99",
    data:"2222",
  }){
    id
    description
    price
    data
  }
}

# 添加对象
query{
  events{
    id
    title
  }
}


5. OKhttp调用
   fun testGraphql() {
  //query
  val apply = getObjectNode().apply {
        put(
            "query", """query{
  uses{
    id
  }
}"""
        )
    }
    
    //mutation
    val apply2 = getObjectNode().apply {
        put(
            "query", """mutation{
  createUser(userInput:{
    email:"test@test4",
    password:"testest3"
  }){
    id
    password
  }
}"""
        )
    }

    //带参数
    val apply3 = getObjectNode().apply {
        put(
            "query", """mutation cU(${'$'}email:String!,${'$'}password:String!){
  createUser(userInput:{
    email:${'$'}email,
    password:${'$'}password
  }){
    id
    password
  }
}""").put("variables", getObjectNode().put("email","3@3.com").put("password","99999"))
    }

    val toRequestBody = apply3.toString().toRequestBody("application/json; charset=utf-8".toMediaType())
    val post = Request.Builder().url("http://localhost:8081/graphql").post(toRequestBody).build()
    val client = getOkHttpClient().newCall(post).execute()
    //0x0000000000000000000000000000000000000000
    println(client.body?.string() ?: "====")
}

6. doctor compose up

需要在有docker-compose.yml文件的文件夹下执行该命令

7. DgsCustomContextBuilderWithRequest

DgsContext.getCustomContext(DgsDataFetchingEnvironment)

@Component
@Slf4j
class AuthContextBuilder(var userDataFetcher:UserDataFetcher) : DgsCustomContextBuilderWithRequest<AuthContext?> {

    override fun build(extensions: Map<String, Any>?, headers: HttpHeaders?, webRequest: WebRequest?): AuthContext? {
        headers?.let {
            log.warn("AuthContextBuilder${it.getFirst("a_h")}")
            return AuthContext(userDataFetcher.uses().find {
                it.id=="1"
            },false)
        }
        return null
    }
}

8. Resolver 使用

parentType 那个TYPE field 那个属性

对Event的两个属性赋值


    //schema.graphql中定义
   type Event{
    user:User!
  events:[Event!]
   }

    @DgsData(parentType = "Event", field="user")
    fun creator(dfe:DgsDataFetchingEnvironment): User? {
        val event = dfe.getSource<Event>()
        val id =  event.creatorId
        return usersData.find {
            it.id == id.toString()
        }

    }
    
    
     @DgsData(parentType = "User", field = "events")
     fun events(dfe: DgsDataFetchingEnvironment): MutableList<Event>? {
        val user = dfe.getSource<User>()
        val events = eventsData.filter {
            it.creatorId.toString() == user.id
        }
        return events.toMutableList()
    }

9. 查询相关

参数human(id:“1000”)

height(unit:FOOT) 设置返回值类型为float

别名写法 别名:原名 a:hero b:hero

定义fragment xxx on yyy 就是在yyy上面选择一些字段 使用…xxx

query name{} 定义一个名字

… on yyy{}

implements interface

__typename

query variables

request headers

使用变量 query name($filedName:filedType){xxx(fileName:$filedName)}

   mutation cU($email:String!,$password:String!){
      createUser(userInput:{
        email:$email,
        password:$password
      }){
        id
        password
      }
}
     
  {
     "email": "testemail2",
     "password": "fdsafdasf"
}
 //   fragment
fragment  A on Booking{
    id
    event{
        id
    }
}

//interface implements
interface  B {
    id: ID!
    event: Event!
}

type Bb implements B{
    id: ID!
    event: Event!
}
     
     

10. DataLoder
//创建DataLoader
@DgsDataLoader(name = "creators")
class CreatorsDataLoader:BatchLoader<Int, User> {
    override fun load(userIds: MutableList<Int>): CompletionStage<MutableList<User>> {
       return  CompletableFuture.supplyAsync{
           return@supplyAsync usersData.filter {
               userIds.contains(it.id.toInt())
           }.toMutableList()
       }
    }

}

    //使用 该方法还是会调用多次,只不过不会从数据库取数据
    //组合成一起批量获取
    @DgsData(parentType = "Event", field="user")
    fun creator(dfe:DgsDataFetchingEnvironment): CompletableFuture<User> {
        val event = dfe.getSource<Event>()
        val id =  event.creatorId
        val dataLoader = dfe.getDataLoader<Int,User>(CreatorsDataLoader::class.java)
        return  dataLoader.load(id)

    }

11. 代码

gitee

相关文章
|
2月前
|
搜索推荐 JavaScript Java
基于springboot的儿童家长教育能力提升学习系统
本系统聚焦儿童家长教育能力提升,针对家庭教育中理念混乱、时间不足、个性化服务缺失等问题,构建科学、系统、个性化的在线学习平台。融合Spring Boot、Vue等先进技术,整合优质教育资源,提供高效便捷的学习路径,助力家长掌握科学育儿方法,促进儿童全面健康发展,推动家庭和谐与社会进步。
|
9月前
|
监控 Java 应用服务中间件
微服务——SpringBoot使用归纳——为什么学习Spring Boot
本文主要探讨为什么学习Spring Boot。从Spring官方定位来看,Spring Boot旨在快速启动和运行项目,简化配置与编码。其优点包括:1) 良好的基因,继承了Spring框架的优点;2) 简化编码,通过starter依赖减少手动配置;3) 简化配置,采用Java Config方式替代繁琐的XML配置;4) 简化部署,内嵌Tomcat支持一键式启动;5) 简化监控,提供运行期性能参数获取功能。此外,从未来发展趋势看,微服务架构逐渐成为主流,而Spring Boot作为官方推荐技术,与Spring Cloud配合使用,将成为未来发展的重要方向。
355 0
微服务——SpringBoot使用归纳——为什么学习Spring Boot
|
6月前
|
安全 Java 数据库
Spring Boot 框架深入学习示例教程详解
本教程深入讲解Spring Boot框架,先介绍其基础概念与优势,如自动配置、独立运行等。通过搭建项目、配置数据库等步骤展示技术方案,并结合RESTful API开发实例帮助学习。内容涵盖环境搭建、核心组件应用(Spring MVC、Spring Data JPA、Spring Security)及示例项目——在线书店系统,助你掌握Spring Boot开发全流程。代码资源可从[链接](https://pan.quark.cn/s/14fcf913bae6)获取。
1017 2
|
8月前
|
Java Spring
Spring框架的学习与应用
总的来说,Spring框架是Java开发中的一把强大的工具。通过理解其核心概念,通过实践来学习和掌握,你可以充分利用Spring框架的强大功能,提高你的开发效率和代码质量。
201 20
|
Java Maven Spring
springboot学习一:idea社区版本创建springboot项目的三种方式(第三种为主)
这篇文章介绍了在IntelliJ IDEA社区版中创建Spring Boot项目的三种方法,特别强调了第三种方法的详细步骤。
11514 0
springboot学习一:idea社区版本创建springboot项目的三种方式(第三种为主)
|
前端开发 Java 开发者
Spring生态学习路径与源码深度探讨
【11月更文挑战第13天】Spring框架作为Java企业级开发中的核心框架,其丰富的生态系统和强大的功能吸引了无数开发者的关注。学习Spring生态不仅仅是掌握Spring Framework本身,更需要深入理解其周边组件和工具,以及源码的底层实现逻辑。本文将从Spring生态的学习路径入手,详细探讨如何系统地学习Spring,并深入解析各个重点的底层实现逻辑。
314 9
|
数据采集 监控 Java
SpringBoot日志全方位超详细手把手教程,零基础可学习 日志如何配置及SLF4J的使用......
本文是关于SpringBoot日志的详细教程,涵盖日志的定义、用途、SLF4J框架的使用、日志级别、持久化、文件分割及格式配置等内容。
916 2
SpringBoot日志全方位超详细手把手教程,零基础可学习 日志如何配置及SLF4J的使用......
|
存储 开发框架 Java
什么是Spring?什么是IOC?什么是DI?IOC和DI的关系? —— 零基础可无压力学习,带源码
文章详细介绍了Spring、IOC、DI的概念和关系,解释了控制反转(IOC)和依赖注入(DI)的原理,并提供了IOC的代码示例,阐述了Spring框架作为IOC容器的应用。
914 1
什么是Spring?什么是IOC?什么是DI?IOC和DI的关系? —— 零基础可无压力学习,带源码
|
前端开发 Java 数据库
SpringBoot学习
【10月更文挑战第7天】Spring学习
192 9
|
XML Java 数据格式
Spring学习
【10月更文挑战第6天】Spring学习
132 1

热门文章

最新文章

推荐镜像

更多