Home > Software engineering >  Gradle: Create an hashmap with values and access in build.gradle
Gradle: Create an hashmap with values and access in build.gradle

Time:11-08

I'm running a Spring boot application, this is what current code looks like.

swagger {
    apiSource {
        locations = [ 'com.test.TestControllerV1' ]
        schemes = [ 'http', 'https' ]
        swaggerDirectory = "${buildDir}/documentation/v1/"
    }
    apiSource {
        locations = [ 'com.test.TestControllerV2' ]
        schemes = [ 'http', 'https' ]
        swaggerDirectory = "${buildDir}/v2/"
    }

    apiSource {
        locations = [ 'com.test.DummyControllerV1' ]
        schemes = [ 'http', 'https' ]
        swaggerDirectory = "${buildDir}/v1/"
    }
}

Instead of repeating the apiSource every time I want to run this in a loop, something like this. (The syntax is not correct here).

swagger {

  for(swaggerDetail in details){
    apiSource {
        locations = [ "$swaggerDetail.path" ]
        schemes = [ 'http', 'https' ]
        swaggerDirectory = "$swaggerDetail.buildPath"
      }
   }
}

Is there any good way to achieve this? Where can I store the values for details hashmap?

CodePudding user response:

Gradle build script are code, so you can use Groovy language features like Maps (or equivalent Kotlin features if you use Kotlin DSL)

You could create a simple map-based structure containing the main apiSource properties for each API version, and iterate other this structure to configure the swagger extension; a very simple example below:

// array containing your different API configs    
def apiConfigs = [
        [basePath: "/v1", location: "com.test.v1", swaggerDirectory: "${buildDir}/v1/"],
        [basePath: "/v2", location: "com.test.v2", swaggerDirectory: "${buildDir}/v2/"]
]

swagger {
    apiConfigs.forEach { config ->
        apiSource {
            // groovy lets you access the config map using notation config["$fieldName"]
            locations = [config["location"]]
            swaggerDirectory = config["swaggerDirectory"]
            basePath = config["basePath"]

            springmvc = true
            schemes = ['http', 'https']
            host = 'www.example.com:8080'
            // ...
        }
    }
}
  • Related