diff --git a/samples/server/petstore/scala-cask/.openapi-generator/VERSION b/samples/server/petstore/scala-cask/.openapi-generator/VERSION index 6935482704c1..e58f433b26ef 100644 --- a/samples/server/petstore/scala-cask/.openapi-generator/VERSION +++ b/samples/server/petstore/scala-cask/.openapi-generator/VERSION @@ -1 +1 @@ -7.10.0-SNAPSHOT +7.10.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/scala-cask/jvm/src/main/resources/openapi.json b/samples/server/petstore/scala-cask/jvm/src/main/resources/openapi.json index d62898ebe7b5..5c3f8dec9aa7 100644 --- a/samples/server/petstore/scala-cask/jvm/src/main/resources/openapi.json +++ b/samples/server/petstore/scala-cask/jvm/src/main/resources/openapi.json @@ -1,5 +1,5 @@ { - "openapi" : "3.1.0", + "openapi" : "3.0.0", "info" : { "description" : "This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.", "license" : { @@ -381,7 +381,8 @@ "additionalProperties" : { "format" : "int32", "type" : "integer" - } + }, + "type" : "object" } } }, @@ -838,6 +839,7 @@ } }, "title" : "Pet Order", + "type" : "object", "xml" : { "name" : "Order" } @@ -855,6 +857,7 @@ } }, "title" : "Pet category", + "type" : "object", "xml" : { "name" : "Category" } @@ -891,6 +894,7 @@ } }, "title" : "a User", + "type" : "object", "xml" : { "name" : "User" } @@ -907,6 +911,7 @@ } }, "title" : "Pet Tag", + "type" : "object", "xml" : { "name" : "Tag" } @@ -954,6 +959,7 @@ }, "required" : [ "name", "photoUrls" ], "title" : "a Pet", + "type" : "object", "xml" : { "name" : "Pet" } @@ -972,7 +978,8 @@ "type" : "string" } }, - "title" : "An uploaded response" + "title" : "An uploaded response", + "type" : "object" }, "updatePetWithForm_request" : { "properties" : { @@ -984,7 +991,8 @@ "description" : "Updated status of the pet", "type" : "string" } - } + }, + "type" : "object" }, "uploadFile_request" : { "properties" : { @@ -997,7 +1005,8 @@ "format" : "binary", "type" : "string" } - } + }, + "type" : "object" } }, "securitySchemes" : { diff --git a/samples/server/petstore/scala-cask/jvm/src/main/scala/sample/cask/AppRoutes.scala b/samples/server/petstore/scala-cask/jvm/src/main/scala/sample/cask/AppRoutes.scala index 48e4649ad72e..f519b3ca30fa 100644 --- a/samples/server/petstore/scala-cask/jvm/src/main/scala/sample/cask/AppRoutes.scala +++ b/samples/server/petstore/scala-cask/jvm/src/main/scala/sample/cask/AppRoutes.scala @@ -1,17 +1,18 @@ //> using scala "3.3.1" //> using lib "com.lihaoyi::cask:0.9.2" //> using lib "com.lihaoyi::scalatags:0.8.2" -/** OpenAPI Petstore This is a sample server Petstore server. For this sample, you can use the api - * key `special-key` to test the authorization filters. - * - * OpenAPI spec version: 1.0.0 - * - * Contact: team@openapitools.org - * - * NOTE: This class is auto generated by OpenAPI Generator. - * - * https://openapi-generator.tech - */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator. + * + * https://openapi-generator.tech + */ // this file was generated from app.mustache package cask.groupId.server @@ -20,33 +21,35 @@ import scala.util.Try import _root_.sample.cask.model.* import _root_.sample.cask.api.* -/** This trait encapsulates the business logic (services) and the http routes which handle the http - * requests sent to those services. - * - * There are default 'not implemented' implementations for the service. - * - * If you wanted fine-grained control over the routes and services, you could extend the - * cask.MainRoutes and mix in this trait by using this: - * - * ``` - * override def allRoutes = appRoutes - * ``` - * - * More typically, however, you would extend the 'BaseApp' class - */ +/** + * This trait encapsulates the business logic (services) and the + * http routes which handle the http requests sent to those services. + * + * There are default 'not implemented' implementations for the service. + * + * If you wanted fine-grained control over the routes and services, you could + * extend the cask.MainRoutes and mix in this trait by using this: + * + * ``` + * override def allRoutes = appRoutes + * ``` + * + * More typically, however, you would extend the 'BaseApp' class + */ trait AppRoutes { - def appPetService: PetService[Try] = PetService() - def routeForPet: PetRoutes = PetRoutes(appPetService) + def appPetService : PetService[Try] = PetService() + def routeForPet : PetRoutes = PetRoutes(appPetService) - def appStoreService: StoreService[Try] = StoreService() - def routeForStore: StoreRoutes = StoreRoutes(appStoreService) + def appStoreService : StoreService[Try] = StoreService() + def routeForStore : StoreRoutes = StoreRoutes(appStoreService) - def appUserService: UserService[Try] = UserService() - def routeForUser: UserRoutes = UserRoutes(appUserService) + def appUserService : UserService[Try] = UserService() + def routeForUser : UserRoutes = UserRoutes(appUserService) - def appRoutes = Seq( - routeForPet, - routeForStore, - routeForUser - ) + + def appRoutes = Seq( + routeForPet , + routeForStore , + routeForUser + ) } diff --git a/samples/server/petstore/scala-cask/jvm/src/main/scala/sample/cask/BaseApp.scala b/samples/server/petstore/scala-cask/jvm/src/main/scala/sample/cask/BaseApp.scala index bba61826b27c..7ed98e88bc96 100644 --- a/samples/server/petstore/scala-cask/jvm/src/main/scala/sample/cask/BaseApp.scala +++ b/samples/server/petstore/scala-cask/jvm/src/main/scala/sample/cask/BaseApp.scala @@ -1,17 +1,19 @@ //> using scala "3.3.1" //> using lib "com.lihaoyi::cask:0.9.2" //> using lib "com.lihaoyi::scalatags:0.8.2" -/** OpenAPI Petstore This is a sample server Petstore server. For this sample, you can use the api - * key `special-key` to test the authorization filters. - * - * OpenAPI spec version: 1.0.0 - * - * Contact: team@openapitools.org - * - * NOTE: This class is auto generated by OpenAPI Generator. - * - * https://openapi-generator.tech - */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator. + * + * https://openapi-generator.tech + */ + // this file was generated from app.mustache package cask.groupId.server @@ -20,36 +22,39 @@ import scala.util.Try import _root_.sample.cask.model.* import _root_.sample.cask.api.* -/** This class was created with the intention of being extended by some runnable object, passing in - * the custom business logic services - */ +/** + * This class was created with the intention of being extended by some runnable object, + * passing in the custom business logic services + */ class BaseApp( - override val appPetService: PetService[Try] = PetService(), - override val appStoreService: StoreService[Try] = StoreService(), - override val appUserService: UserService[Try] = UserService(), - override val port: Int = sys.env.get("PORT").map(_.toInt).getOrElse(8080) -) extends cask.MainRoutes - with AppRoutes { + override val appPetService : PetService[Try] = PetService(), + + override val appStoreService : StoreService[Try] = StoreService(), + + override val appUserService : UserService[Try] = UserService(), + override val port : Int = sys.env.get("PORT").map(_.toInt).getOrElse(8080)) extends cask.MainRoutes with AppRoutes { + + /** routes for the UI + * Subclasses can override to turn this off + */ + def openApiRoute: Option[cask.Routes] = Option(OpenApiRoutes(port)) - /** routes for the UI Subclasses can override to turn this off - */ - def openApiRoute: Option[cask.Routes] = Option(OpenApiRoutes(port)) + override def allRoutes = appRoutes ++ openApiRoute - override def allRoutes = appRoutes ++ openApiRoute - override def host: String = "0.0.0.0" + override def host: String = "0.0.0.0" - def start() = locally { - initialize() - println(box(s""" 🚀 browse to localhost:$port 🚀 + def start() = locally { + initialize() + println(box(s""" 🚀 browse to localhost:$port 🚀 | host : $host | port : $port | verbose : $verbose | debugMode : $debugMode |""".stripMargin)) - // if java.awt.Desktop.isDesktopSupported then { - // java.awt.Desktop.getDesktop.browse(new java.net.URI(s"http://localhost:${port}")) - // } - } + // if java.awt.Desktop.isDesktopSupported then { + // java.awt.Desktop.getDesktop.browse(new java.net.URI(s"http://localhost:${port}")) + // } + } } diff --git a/samples/server/petstore/scala-cask/jvm/src/main/scala/sample/cask/ExampleApp.scala b/samples/server/petstore/scala-cask/jvm/src/main/scala/sample/cask/ExampleApp.scala index 3c13cb711f60..b49381daf7ec 100644 --- a/samples/server/petstore/scala-cask/jvm/src/main/scala/sample/cask/ExampleApp.scala +++ b/samples/server/petstore/scala-cask/jvm/src/main/scala/sample/cask/ExampleApp.scala @@ -1,17 +1,19 @@ //> using scala "3.3.1" //> using dep "com.lihaoyi::cask:0.9.2" //> using dep "com.lihaoyi::scalatags:0.8.2" -/** OpenAPI Petstore This is a sample server Petstore server. For this sample, you can use the api - * key `special-key` to test the authorization filters. - * - * OpenAPI spec version: 1.0.0 - * - * Contact: team@openapitools.org - * - * NOTE: This class is auto generated by OpenAPI Generator. - * - * https://openapi-generator.tech - */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator. + * + * https://openapi-generator.tech + */ + // this file was generated from app.mustache package cask.groupId.server @@ -27,10 +29,11 @@ object MoreRoutes extends cask.Routes { initialize() } -/** This is an example of how you might extends BaseApp for a runnable application. - * - * See the README.md for how to create your own app - */ +/** + * This is an example of how you might extends BaseApp for a runnable application. + * + * See the README.md for how to create your own app + */ object ExampleApp extends BaseApp() { // override to include our additional route override def allRoutes = super.allRoutes ++ Option(MoreRoutes) diff --git a/samples/server/petstore/scala-cask/jvm/src/main/scala/sample/cask/api/OpenApiRoutes.scala b/samples/server/petstore/scala-cask/jvm/src/main/scala/sample/cask/api/OpenApiRoutes.scala index 2e35d4b19077..403a519f2a3c 100644 --- a/samples/server/petstore/scala-cask/jvm/src/main/scala/sample/cask/api/OpenApiRoutes.scala +++ b/samples/server/petstore/scala-cask/jvm/src/main/scala/sample/cask/api/OpenApiRoutes.scala @@ -1,14 +1,16 @@ -/** OpenAPI Petstore This is a sample server Petstore server. For this sample, you can use the api - * key `special-key` to test the authorization filters. - * - * OpenAPI spec version: 1.0.0 - * - * Contact: team@openapitools.org - * - * NOTE: This class is auto generated by OpenAPI Generator. - * - * https://openapi-generator.tech - */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator. + * + * https://openapi-generator.tech + */ + // generated from openapiRoute.mustache package sample.cask.api @@ -17,13 +19,14 @@ import cask.model.Response import java.nio.file.{Files, Path, Paths} -/** This code will try and download the swagger UI static files on startup - * - * That behaviour can be altered by: - * - setting the environment variable SWAGGER_ON to false - * - setting the environment variable SWAGGER_UI_URL to either the URL of a swagger UI zip or - * setting it to the empty string - */ +/** + * This code will try and download the swagger UI static files on startup + * + * That behaviour can be altered by: + * - setting the environment variable SWAGGER_ON to false + * - setting the environment variable SWAGGER_UI_URL to either the URL of a swagger UI zip or setting it to the empty string + * + */ object OpenApiRoutes { def swaggerUIUrl: Option[String] = { @@ -87,7 +90,7 @@ class OpenApiRoutes(localPort: Int, swaggerUrl: Option[String]) extends cask.Rou } } - if (extracted.isFailure) { + if (extracted.isFailure) { println(s"Error extracting swagger: ${extracted}") } else { println(s"Extracting swagger: ${extracted}") @@ -111,8 +114,7 @@ class OpenApiRoutes(localPort: Int, swaggerUrl: Option[String]) extends cask.Rou // keeping this compatible for java 8, where this is from >= java 11: // Files.writeString(fullPath, textLines.mkString("\n")) - scala.util - .Using(new java.io.PrintWriter(fullPath.toFile))(_.write(textLines.mkString("\n"))) + scala.util.Using(new java.io.PrintWriter(fullPath.toFile))(_.write(textLines.mkString("\n"))) } else { Using(new FileOutputStream(filePath)) { outputStream => val buffer = new Array[Byte](1024) diff --git a/samples/server/petstore/scala-cask/jvm/src/main/scala/sample/cask/api/PetRoutes.scala b/samples/server/petstore/scala-cask/jvm/src/main/scala/sample/cask/api/PetRoutes.scala index b1348c98d4c7..da02bbb338d6 100644 --- a/samples/server/petstore/scala-cask/jvm/src/main/scala/sample/cask/api/PetRoutes.scala +++ b/samples/server/petstore/scala-cask/jvm/src/main/scala/sample/cask/api/PetRoutes.scala @@ -1,17 +1,19 @@ //> using scala "3.3.1" //> using lib "com.lihaoyi::cask:0.8.3" //> using lib "com.lihaoyi::scalatags:0.12.0" -/** OpenAPI Petstore This is a sample server Petstore server. For this sample, you can use the api - * key `special-key` to test the authorization filters. - * - * OpenAPI spec version: 1.0.0 - * - * Contact: team@openapitools.org - * - * NOTE: This class is auto generated by OpenAPI Generator. - * - * https://openapi-generator.tech - */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator. + * + * https://openapi-generator.tech + */ + // this is generated from apiRoutes.mustache package sample.cask.api @@ -26,211 +28,202 @@ import sample.cask.model.ApiResponse import java.io.File import sample.cask.model.Pet -class PetRoutes(service: PetService[Try]) extends cask.Routes { - - // route group for routeWorkAroundForPOSTPet - @cask.post("/pet", true) - def routeWorkAroundForPOSTPet(request: cask.Request) = { - request.remainingPathSegments match { - case Seq() => addPet(request) - case Seq(petId) => updatePetWithForm(petId.toLong, request) - case Seq(petId, "uploadImage") => uploadFile(petId.toLong, request) - case _ => cask.Response("Not Found", statusCode = 404) - } - } - // route group for routeWorkAroundForGETPet - @cask.get("/pet", true) - def routeWorkAroundForGETPet( - request: cask.Request, - status: Seq[String] = Nil, - tags: Seq[String] = Nil - ) = { - request.remainingPathSegments match { - case Seq("findByStatus") => findPetsByStatus(request, status) - case Seq("findByTags") => findPetsByTags(request, tags) - case Seq(petId) => getPetById(petId.toLong, request) - case _ => cask.Response("Not Found", statusCode = 404) - } - } - - /** Add a new pet to the store - */ - // conflicts with [/pet/{petId}, /pet/{petId}/uploadImage, /pet] after/pet, ignoring @cask.post("/pet") - def addPet(request: cask.Request) = { - // auth method petstore_auth : oauth2, keyParamName: - - def failFast = request.queryParams.keySet.contains("failFast") - - val result = for { - petJson <- Parsed.fromTry(request.bodyAsJson) - petData <- Parsed.eval(PetData.fromJson(petJson)) /* not array or map */ - pet <- Parsed.fromTry(petData.validated(failFast)) - resultTry <- Parsed.eval(service.addPet(pet)) - result <- Parsed.fromTry(resultTry) - } yield result - - (result: @unchecked) match { - case Left(error) => cask.Response(error, 500) - case Right(value: Pet) => - cask.Response(data = write(value), 200, headers = Seq("Content-Type" -> "application/json")) - case Right(other) => cask.Response(s"$other", 200) - } - } - - /** Deletes a pet - */ - @cask.delete("/pet/:petId") - def deletePet(petId: Long, request: cask.Request) = { - // auth method petstore_auth : oauth2, keyParamName: - - def failFast = request.queryParams.keySet.contains("failFast") - - val result = for { - petId <- Parsed(petId) - apiKey <- request.headerSingleValueOptional("apiKey") - resultTry <- Parsed.eval(service.deletePet(petId, apiKey)) - result <- Parsed.fromTry(resultTry) - } yield result - - (result: @unchecked) match { - case Left(error) => cask.Response(error, 500) - case Right(other) => cask.Response(s"$other", 200) - } - } - - /** Finds Pets by status - */ - // conflicts with [/pet/{petId}, /pet/findByStatus, /pet/findByTags] after/pet, ignoring @cask.get("/pet/findByStatus") - def findPetsByStatus(request: cask.Request, status: Seq[String]) = { - // auth method petstore_auth : oauth2, keyParamName: - - def failFast = request.queryParams.keySet.contains("failFast") - - val result = for { - resultTry <- Parsed.eval(service.findPetsByStatus(status)) - result <- Parsed.fromTry(resultTry) - } yield result - - (result: @unchecked) match { - case Left(error) => cask.Response(error, 500) - case Right(value: List[Pet]) => - cask.Response(data = write(value), 200, headers = Seq("Content-Type" -> "application/json")) - case Right(other) => cask.Response(s"$other", 200) - } - } - - /** Finds Pets by tags - */ - // conflicts with [/pet/{petId}, /pet/findByStatus, /pet/findByTags] after/pet, ignoring @cask.get("/pet/findByTags") - def findPetsByTags(request: cask.Request, tags: Seq[String]) = { - // auth method petstore_auth : oauth2, keyParamName: - - def failFast = request.queryParams.keySet.contains("failFast") - - val result = for { - resultTry <- Parsed.eval(service.findPetsByTags(tags)) - result <- Parsed.fromTry(resultTry) - } yield result - - (result: @unchecked) match { - case Left(error) => cask.Response(error, 500) - case Right(value: List[Pet]) => - cask.Response(data = write(value), 200, headers = Seq("Content-Type" -> "application/json")) - case Right(other) => cask.Response(s"$other", 200) - } - } - - /** Find pet by ID - */ - // conflicts with [/pet/{petId}, /pet/findByStatus, /pet/findByTags] after/pet, ignoring @cask.get("/pet/:petId") - def getPetById(petId: Long, request: cask.Request) = { - // auth method api_key : apiKey, keyParamName: api_key - - def failFast = request.queryParams.keySet.contains("failFast") - - val result = for { - petId <- Parsed(petId) - resultTry <- Parsed.eval(service.getPetById(petId)) - result <- Parsed.fromTry(resultTry) - } yield result - - (result: @unchecked) match { - case Left(error) => cask.Response(error, 500) - case Right(value: Pet) => - cask.Response(data = write(value), 200, headers = Seq("Content-Type" -> "application/json")) - case Right(other) => cask.Response(s"$other", 200) - } - } - - /** Update an existing pet - */ - @cask.put("/pet") - def updatePet(request: cask.Request) = { - // auth method petstore_auth : oauth2, keyParamName: - - def failFast = request.queryParams.keySet.contains("failFast") - - val result = for { - petJson <- Parsed.fromTry(request.bodyAsJson) - petData <- Parsed.eval(PetData.fromJson(petJson)) /* not array or map */ - pet <- Parsed.fromTry(petData.validated(failFast)) - resultTry <- Parsed.eval(service.updatePet(pet)) - result <- Parsed.fromTry(resultTry) - } yield result - - (result: @unchecked) match { - case Left(error) => cask.Response(error, 500) - case Right(value: Pet) => - cask.Response(data = write(value), 200, headers = Seq("Content-Type" -> "application/json")) - case Right(other) => cask.Response(s"$other", 200) - } - } - - /** Updates a pet in the store with form data - */ - // conflicts with [/pet/{petId}, /pet/{petId}/uploadImage, /pet] after/pet, ignoring @cask.post("/pet/:petId") - def updatePetWithForm(petId: Long, request: cask.Request) = { - // auth method petstore_auth : oauth2, keyParamName: - - def failFast = request.queryParams.keySet.contains("failFast") - - val result = for { - petId <- Parsed(petId) - name <- request.formSingleValueOptional("name") - status <- request.formSingleValueOptional("status") - resultTry <- Parsed.eval(service.updatePetWithForm(petId, name, status)) - result <- Parsed.fromTry(resultTry) - } yield result - - (result: @unchecked) match { - case Left(error) => cask.Response(error, 500) - case Right(other) => cask.Response(s"$other", 200) +class PetRoutes(service : PetService[Try]) extends cask.Routes { + + // route group for routeWorkAroundForPOSTPet + @cask.post("/pet", true) + def routeWorkAroundForPOSTPet(request: cask.Request) = { + request.remainingPathSegments match { + case Seq() => addPet(request) + case Seq(petId) => updatePetWithForm(petId.toLong,request) + case Seq(petId,"uploadImage") => uploadFile(petId.toLong,request) + case _ => cask.Response("Not Found", statusCode = 404) + } } - } - - /** uploads an image - */ - // conflicts with [/pet/{petId}, /pet/{petId}/uploadImage, /pet] after/pet, ignoring @cask.post("/pet/:petId/uploadImage") - def uploadFile(petId: Long, request: cask.Request) = { - // auth method petstore_auth : oauth2, keyParamName: - - def failFast = request.queryParams.keySet.contains("failFast") - - val result = for { - petId <- Parsed(petId) - additionalMetadata <- request.formSingleValueOptional("additionalMetadata") - file <- request.formValueAsFileOptional("file") - resultTry <- Parsed.eval(service.uploadFile(petId, additionalMetadata, file)) - result <- Parsed.fromTry(resultTry) - } yield result - - (result: @unchecked) match { - case Left(error) => cask.Response(error, 500) - case Right(value: ApiResponse) => - cask.Response(data = write(value), 200, headers = Seq("Content-Type" -> "application/json")) - case Right(other) => cask.Response(s"$other", 200) + // route group for routeWorkAroundForGETPet + @cask.get("/pet", true) + def routeWorkAroundForGETPet(request: cask.Request,status : Seq[String] = Nil,tags : Seq[String] = Nil) = { + request.remainingPathSegments match { + case Seq("findByStatus") => findPetsByStatus(request,status) + case Seq("findByTags") => findPetsByTags(request,tags) + case Seq(petId) => getPetById(petId.toLong,request) + case _ => cask.Response("Not Found", statusCode = 404) + } } - } - initialize() + /** Add a new pet to the store + * + */ + // conflicts with [/pet/{petId}, /pet/{petId}/uploadImage, /pet] after/pet, ignoring @cask.post("/pet") + def addPet(request: cask.Request) = { + // auth method petstore_auth : oauth2, keyParamName: + + def failFast = request.queryParams.keySet.contains("failFast") + + val result = for { + petJson <- Parsed.fromTry(request.bodyAsJson) + petData <- Parsed.eval(PetData.fromJson(petJson)) /* not array or map */ + pet <- Parsed.fromTry(petData.validated(failFast)) + resultTry <- Parsed.eval(service.addPet(pet)) + result <- Parsed.fromTry(resultTry) + } yield result + + (result : @unchecked) match { + case Left(error) => cask.Response(error, 500) + case Right(value : Pet) => cask.Response(data = write(value), 200, headers = Seq("Content-Type" -> "application/json")) + case Right(other) => cask.Response(s"$other", 200) + } + } + /** Deletes a pet + * + */ + @cask.delete("/pet/:petId") + def deletePet(petId : Long, request: cask.Request) = { + // auth method petstore_auth : oauth2, keyParamName: + + def failFast = request.queryParams.keySet.contains("failFast") + + val result = for { + petId <- Parsed(petId) + apiKey <- request.headerSingleValueOptional("apiKey") + resultTry <- Parsed.eval(service.deletePet(petId, apiKey)) + result <- Parsed.fromTry(resultTry) + } yield result + + (result : @unchecked) match { + case Left(error) => cask.Response(error, 500) + case Right(other) => cask.Response(s"$other", 200) + } + } + /** Finds Pets by status + * + */ + // conflicts with [/pet/{petId}, /pet/findByStatus, /pet/findByTags] after/pet, ignoring @cask.get("/pet/findByStatus") + def findPetsByStatus(request: cask.Request, status : Seq[String]) = { + // auth method petstore_auth : oauth2, keyParamName: + + def failFast = request.queryParams.keySet.contains("failFast") + + val result = for { + resultTry <- Parsed.eval(service.findPetsByStatus(status)) + result <- Parsed.fromTry(resultTry) + } yield result + + (result : @unchecked) match { + case Left(error) => cask.Response(error, 500) + case Right(value : List[Pet]) => cask.Response(data = write(value), 200, headers = Seq("Content-Type" -> "application/json")) + case Right(other) => cask.Response(s"$other", 200) + } + } + /** Finds Pets by tags + * + */ + // conflicts with [/pet/{petId}, /pet/findByStatus, /pet/findByTags] after/pet, ignoring @cask.get("/pet/findByTags") + def findPetsByTags(request: cask.Request, tags : Seq[String]) = { + // auth method petstore_auth : oauth2, keyParamName: + + def failFast = request.queryParams.keySet.contains("failFast") + + val result = for { + resultTry <- Parsed.eval(service.findPetsByTags(tags)) + result <- Parsed.fromTry(resultTry) + } yield result + + (result : @unchecked) match { + case Left(error) => cask.Response(error, 500) + case Right(value : List[Pet]) => cask.Response(data = write(value), 200, headers = Seq("Content-Type" -> "application/json")) + case Right(other) => cask.Response(s"$other", 200) + } + } + /** Find pet by ID + * + */ + // conflicts with [/pet/{petId}, /pet/findByStatus, /pet/findByTags] after/pet, ignoring @cask.get("/pet/:petId") + def getPetById(petId : Long, request: cask.Request) = { + // auth method api_key : apiKey, keyParamName: api_key + + def failFast = request.queryParams.keySet.contains("failFast") + + val result = for { + petId <- Parsed(petId) + resultTry <- Parsed.eval(service.getPetById(petId)) + result <- Parsed.fromTry(resultTry) + } yield result + + (result : @unchecked) match { + case Left(error) => cask.Response(error, 500) + case Right(value : Pet) => cask.Response(data = write(value), 200, headers = Seq("Content-Type" -> "application/json")) + case Right(other) => cask.Response(s"$other", 200) + } + } + /** Update an existing pet + * + */ + @cask.put("/pet") + def updatePet(request: cask.Request) = { + // auth method petstore_auth : oauth2, keyParamName: + + def failFast = request.queryParams.keySet.contains("failFast") + + val result = for { + petJson <- Parsed.fromTry(request.bodyAsJson) + petData <- Parsed.eval(PetData.fromJson(petJson)) /* not array or map */ + pet <- Parsed.fromTry(petData.validated(failFast)) + resultTry <- Parsed.eval(service.updatePet(pet)) + result <- Parsed.fromTry(resultTry) + } yield result + + (result : @unchecked) match { + case Left(error) => cask.Response(error, 500) + case Right(value : Pet) => cask.Response(data = write(value), 200, headers = Seq("Content-Type" -> "application/json")) + case Right(other) => cask.Response(s"$other", 200) + } + } + /** Updates a pet in the store with form data + * + */ + // conflicts with [/pet/{petId}, /pet/{petId}/uploadImage, /pet] after/pet, ignoring @cask.post("/pet/:petId") + def updatePetWithForm(petId : Long, request: cask.Request) = { + // auth method petstore_auth : oauth2, keyParamName: + + def failFast = request.queryParams.keySet.contains("failFast") + + val result = for { + petId <- Parsed(petId) + name <- request.formSingleValueOptional("name") + status <- request.formSingleValueOptional("status") + resultTry <- Parsed.eval(service.updatePetWithForm(petId, name, status)) + result <- Parsed.fromTry(resultTry) + } yield result + + (result : @unchecked) match { + case Left(error) => cask.Response(error, 500) + case Right(other) => cask.Response(s"$other", 200) + } + } + /** uploads an image + * + */ + // conflicts with [/pet/{petId}, /pet/{petId}/uploadImage, /pet] after/pet, ignoring @cask.post("/pet/:petId/uploadImage") + def uploadFile(petId : Long, request: cask.Request) = { + // auth method petstore_auth : oauth2, keyParamName: + + def failFast = request.queryParams.keySet.contains("failFast") + + val result = for { + petId <- Parsed(petId) + additionalMetadata <- request.formSingleValueOptional("additionalMetadata") + file <- request.formValueAsFileOptional("file") + resultTry <- Parsed.eval(service.uploadFile(petId, additionalMetadata, file)) + result <- Parsed.fromTry(resultTry) + } yield result + + (result : @unchecked) match { + case Left(error) => cask.Response(error, 500) + case Right(value : ApiResponse) => cask.Response(data = write(value), 200, headers = Seq("Content-Type" -> "application/json")) + case Right(other) => cask.Response(s"$other", 200) + } + } + + initialize() } diff --git a/samples/server/petstore/scala-cask/jvm/src/main/scala/sample/cask/api/StoreRoutes.scala b/samples/server/petstore/scala-cask/jvm/src/main/scala/sample/cask/api/StoreRoutes.scala index 4582355f7035..5c3414564e5f 100644 --- a/samples/server/petstore/scala-cask/jvm/src/main/scala/sample/cask/api/StoreRoutes.scala +++ b/samples/server/petstore/scala-cask/jvm/src/main/scala/sample/cask/api/StoreRoutes.scala @@ -1,17 +1,19 @@ //> using scala "3.3.1" //> using lib "com.lihaoyi::cask:0.8.3" //> using lib "com.lihaoyi::scalatags:0.12.0" -/** OpenAPI Petstore This is a sample server Petstore server. For this sample, you can use the api - * key `special-key` to test the authorization filters. - * - * OpenAPI spec version: 1.0.0 - * - * Contact: team@openapitools.org - * - * NOTE: This class is auto generated by OpenAPI Generator. - * - * https://openapi-generator.tech - */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator. + * + * https://openapi-generator.tech + */ + // this is generated from apiRoutes.mustache package sample.cask.api @@ -23,93 +25,91 @@ import upickle.default.* import scala.util.Try import sample.cask.model.Order -import ujson.Value - -class StoreRoutes(service: StoreService[Try]) extends cask.Routes { - - /** Delete purchase order by ID - */ - @cask.delete("/store/order/:orderId") - def deleteOrder(orderId: String, request: cask.Request) = { - - def failFast = request.queryParams.keySet.contains("failFast") - - val result = for { - orderId <- Parsed(orderId) - resultTry <- Parsed.eval(service.deleteOrder(orderId)) - result <- Parsed.fromTry(resultTry) - } yield result - - (result: @unchecked) match { - case Left(error) => cask.Response(error, 500) - case Right(other) => cask.Response(s"$other", 200) - } - } - - /** Returns pet inventories by status - */ - @cask.get("/store/inventory") - def getInventory(request: cask.Request) = { - // auth method api_key : apiKey, keyParamName: api_key - - def failFast = request.queryParams.keySet.contains("failFast") - - val result = for { - resultTry <- Parsed.eval(service.getInventory()) - result <- Parsed.fromTry(resultTry) - } yield result - - (result: @unchecked) match { - case Left(error) => cask.Response(error, 500) - case Right(value: Value) => - cask.Response(data = write(value), 200, headers = Seq("Content-Type" -> "application/json")) - case Right(other) => cask.Response(s"$other", 200) - } - } - - /** Find purchase order by ID - */ - @cask.get("/store/order/:orderId") - def getOrderById(orderId: Long, request: cask.Request) = { - - def failFast = request.queryParams.keySet.contains("failFast") - - val result = for { - orderId <- Parsed(orderId) - resultTry <- Parsed.eval(service.getOrderById(orderId)) - result <- Parsed.fromTry(resultTry) - } yield result - - (result: @unchecked) match { - case Left(error) => cask.Response(error, 500) - case Right(value: Order) => - cask.Response(data = write(value), 200, headers = Seq("Content-Type" -> "application/json")) - case Right(other) => cask.Response(s"$other", 200) - } - } - - /** Place an order for a pet - */ - @cask.post("/store/order") - def placeOrder(request: cask.Request) = { - - def failFast = request.queryParams.keySet.contains("failFast") - - val result = for { - orderJson <- Parsed.fromTry(request.bodyAsJson) - orderData <- Parsed.eval(OrderData.fromJson(orderJson)) /* not array or map */ - order <- Parsed.fromTry(orderData.validated(failFast)) - resultTry <- Parsed.eval(service.placeOrder(order)) - result <- Parsed.fromTry(resultTry) - } yield result - - (result: @unchecked) match { - case Left(error) => cask.Response(error, 500) - case Right(value: Order) => - cask.Response(data = write(value), 200, headers = Seq("Content-Type" -> "application/json")) - case Right(other) => cask.Response(s"$other", 200) - } - } - - initialize() + +class StoreRoutes(service : StoreService[Try]) extends cask.Routes { + + + /** Delete purchase order by ID + * + */ + @cask.delete("/store/order/:orderId") + def deleteOrder(orderId : String, request: cask.Request) = { + + def failFast = request.queryParams.keySet.contains("failFast") + + val result = for { + orderId <- Parsed(orderId) + resultTry <- Parsed.eval(service.deleteOrder(orderId)) + result <- Parsed.fromTry(resultTry) + } yield result + + (result : @unchecked) match { + case Left(error) => cask.Response(error, 500) + case Right(other) => cask.Response(s"$other", 200) + } + } + /** Returns pet inventories by status + * + */ + @cask.get("/store/inventory") + def getInventory(request: cask.Request) = { + // auth method api_key : apiKey, keyParamName: api_key + + def failFast = request.queryParams.keySet.contains("failFast") + + val result = for { + resultTry <- Parsed.eval(service.getInventory()) + result <- Parsed.fromTry(resultTry) + } yield result + + (result : @unchecked) match { + case Left(error) => cask.Response(error, 500) + case Right(value : Map[String, Int]) => cask.Response(data = write(value), 200, headers = Seq("Content-Type" -> "application/json")) + case Right(other) => cask.Response(s"$other", 200) + } + } + /** Find purchase order by ID + * + */ + @cask.get("/store/order/:orderId") + def getOrderById(orderId : Long, request: cask.Request) = { + + def failFast = request.queryParams.keySet.contains("failFast") + + val result = for { + orderId <- Parsed(orderId) + resultTry <- Parsed.eval(service.getOrderById(orderId)) + result <- Parsed.fromTry(resultTry) + } yield result + + (result : @unchecked) match { + case Left(error) => cask.Response(error, 500) + case Right(value : Order) => cask.Response(data = write(value), 200, headers = Seq("Content-Type" -> "application/json")) + case Right(other) => cask.Response(s"$other", 200) + } + } + /** Place an order for a pet + * + */ + @cask.post("/store/order") + def placeOrder(request: cask.Request) = { + + def failFast = request.queryParams.keySet.contains("failFast") + + val result = for { + orderJson <- Parsed.fromTry(request.bodyAsJson) + orderData <- Parsed.eval(OrderData.fromJson(orderJson)) /* not array or map */ + order <- Parsed.fromTry(orderData.validated(failFast)) + resultTry <- Parsed.eval(service.placeOrder(order)) + result <- Parsed.fromTry(resultTry) + } yield result + + (result : @unchecked) match { + case Left(error) => cask.Response(error, 500) + case Right(value : Order) => cask.Response(data = write(value), 200, headers = Seq("Content-Type" -> "application/json")) + case Right(other) => cask.Response(s"$other", 200) + } + } + + initialize() } diff --git a/samples/server/petstore/scala-cask/jvm/src/main/scala/sample/cask/api/UserRoutes.scala b/samples/server/petstore/scala-cask/jvm/src/main/scala/sample/cask/api/UserRoutes.scala index ddd42a7c987f..63c01ea5583e 100644 --- a/samples/server/petstore/scala-cask/jvm/src/main/scala/sample/cask/api/UserRoutes.scala +++ b/samples/server/petstore/scala-cask/jvm/src/main/scala/sample/cask/api/UserRoutes.scala @@ -1,17 +1,19 @@ //> using scala "3.3.1" //> using lib "com.lihaoyi::cask:0.8.3" //> using lib "com.lihaoyi::scalatags:0.12.0" -/** OpenAPI Petstore This is a sample server Petstore server. For this sample, you can use the api - * key `special-key` to test the authorization filters. - * - * OpenAPI spec version: 1.0.0 - * - * Contact: team@openapitools.org - * - * NOTE: This class is auto generated by OpenAPI Generator. - * - * https://openapi-generator.tech - */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator. + * + * https://openapi-generator.tech + */ + // this is generated from apiRoutes.mustache package sample.cask.api @@ -25,195 +27,182 @@ import scala.util.Try import java.time.OffsetDateTime import sample.cask.model.User -class UserRoutes(service: UserService[Try]) extends cask.Routes { - - // route group for routeWorkAroundForGETUser - @cask.get("/user", true) - def routeWorkAroundForGETUser( - request: cask.Request, - username: Option[String] = None, - password: Option[String] = None - ) = { - request.remainingPathSegments match { - case Seq("login") => loginUser(request, username.getOrElse(""), password.getOrElse("")) - case Seq("logout") => logoutUser(request) - case Seq(username) => getUserByName(username, request) - case _ => cask.Response("Not Found", statusCode = 404) - } - } - - /** Create user - */ - @cask.post("/user") - def createUser(request: cask.Request) = { - // auth method api_key : apiKey, keyParamName: api_key - - def failFast = request.queryParams.keySet.contains("failFast") - - val result = for { - userJson <- Parsed.fromTry(request.bodyAsJson) - userData <- Parsed.eval(UserData.fromJson(userJson)) /* not array or map */ - user <- Parsed.fromTry(userData.validated(failFast)) - resultTry <- Parsed.eval(service.createUser(user)) - result <- Parsed.fromTry(resultTry) - } yield result - - (result: @unchecked) match { - case Left(error) => cask.Response(error, 500) - case Right(other) => cask.Response(s"$other", 200) - } - } - - /** Creates list of users with given input array - */ - @cask.post("/user/createWithArray") - def createUsersWithArrayInput(request: cask.Request) = { - // auth method api_key : apiKey, keyParamName: api_key - - def failFast = request.queryParams.keySet.contains("failFast") - - val result = for { - user <- Parsed - .fromTry(UserData.manyFromJsonStringValidated(request.bodyAsString)) - .mapError(e => - s"Error parsing json as an array of User from >${request.bodyAsString}< : ${e}" - ) /* array */ - resultTry <- Parsed.eval(service.createUsersWithArrayInput(user)) - result <- Parsed.fromTry(resultTry) - } yield result - - (result: @unchecked) match { - case Left(error) => cask.Response(error, 500) - case Right(other) => cask.Response(s"$other", 200) - } - } - - /** Creates list of users with given input array - */ - @cask.post("/user/createWithList") - def createUsersWithListInput(request: cask.Request) = { - // auth method api_key : apiKey, keyParamName: api_key - - def failFast = request.queryParams.keySet.contains("failFast") - - val result = for { - user <- Parsed - .fromTry(UserData.manyFromJsonStringValidated(request.bodyAsString)) - .mapError(e => - s"Error parsing json as an array of User from >${request.bodyAsString}< : ${e}" - ) /* array */ - resultTry <- Parsed.eval(service.createUsersWithListInput(user)) - result <- Parsed.fromTry(resultTry) - } yield result - - (result: @unchecked) match { - case Left(error) => cask.Response(error, 500) - case Right(other) => cask.Response(s"$other", 200) - } - } - - /** Delete user - */ - @cask.delete("/user/:username") - def deleteUser(username: String, request: cask.Request) = { - // auth method api_key : apiKey, keyParamName: api_key - - def failFast = request.queryParams.keySet.contains("failFast") - - val result = for { - username <- Parsed(username) - resultTry <- Parsed.eval(service.deleteUser(username)) - result <- Parsed.fromTry(resultTry) - } yield result - - (result: @unchecked) match { - case Left(error) => cask.Response(error, 500) - case Right(other) => cask.Response(s"$other", 200) - } - } - - /** Get user by user name - */ - // conflicts with [/user/{username}, /user/login, /user/logout] after/user, ignoring @cask.get("/user/:username") - def getUserByName(username: String, request: cask.Request) = { - - def failFast = request.queryParams.keySet.contains("failFast") - - val result = for { - username <- Parsed(username) - resultTry <- Parsed.eval(service.getUserByName(username)) - result <- Parsed.fromTry(resultTry) - } yield result - - (result: @unchecked) match { - case Left(error) => cask.Response(error, 500) - case Right(value: User) => - cask.Response(data = write(value), 200, headers = Seq("Content-Type" -> "application/json")) - case Right(other) => cask.Response(s"$other", 200) - } - } - - /** Logs user into the system - */ - // conflicts with [/user/{username}, /user/login, /user/logout] after/user, ignoring @cask.get("/user/login") - def loginUser(request: cask.Request, username: String, password: String) = { - - def failFast = request.queryParams.keySet.contains("failFast") - - val result = for { - resultTry <- Parsed.eval(service.loginUser(username, password)) - result <- Parsed.fromTry(resultTry) - } yield result - - (result: @unchecked) match { - case Left(error) => cask.Response(error, 500) - case Right(value: String) => - cask.Response(data = write(value), 200, headers = Seq("Content-Type" -> "application/json")) - case Right(other) => cask.Response(s"$other", 200) - } - } - - /** Logs out current logged in user session - */ - // conflicts with [/user/{username}, /user/login, /user/logout] after/user, ignoring @cask.get("/user/logout") - def logoutUser(request: cask.Request) = { - // auth method api_key : apiKey, keyParamName: api_key - - def failFast = request.queryParams.keySet.contains("failFast") - - val result = for { - resultTry <- Parsed.eval(service.logoutUser()) - result <- Parsed.fromTry(resultTry) - } yield result - - (result: @unchecked) match { - case Left(error) => cask.Response(error, 500) - case Right(other) => cask.Response(s"$other", 200) - } - } - - /** Updated user - */ - @cask.put("/user/:username") - def updateUser(username: String, request: cask.Request) = { - // auth method api_key : apiKey, keyParamName: api_key - - def failFast = request.queryParams.keySet.contains("failFast") - - val result = for { - username <- Parsed(username) - userJson <- Parsed.fromTry(request.bodyAsJson) - userData <- Parsed.eval(UserData.fromJson(userJson)) /* not array or map */ - user <- Parsed.fromTry(userData.validated(failFast)) - resultTry <- Parsed.eval(service.updateUser(username, user)) - result <- Parsed.fromTry(resultTry) - } yield result - - (result: @unchecked) match { - case Left(error) => cask.Response(error, 500) - case Right(other) => cask.Response(s"$other", 200) +class UserRoutes(service : UserService[Try]) extends cask.Routes { + + // route group for routeWorkAroundForGETUser + @cask.get("/user", true) + def routeWorkAroundForGETUser(request: cask.Request,username : Option[String] = None,password : Option[String] = None) = { + request.remainingPathSegments match { + case Seq("login") => loginUser(request,username.getOrElse(""), password.getOrElse("")) + case Seq("logout") => logoutUser(request) + case Seq(username) => getUserByName(username,request) + case _ => cask.Response("Not Found", statusCode = 404) + } } - } - initialize() + /** Create user + * + */ + @cask.post("/user") + def createUser(request: cask.Request) = { + // auth method api_key : apiKey, keyParamName: api_key + + def failFast = request.queryParams.keySet.contains("failFast") + + val result = for { + userJson <- Parsed.fromTry(request.bodyAsJson) + userData <- Parsed.eval(UserData.fromJson(userJson)) /* not array or map */ + user <- Parsed.fromTry(userData.validated(failFast)) + resultTry <- Parsed.eval(service.createUser(user)) + result <- Parsed.fromTry(resultTry) + } yield result + + (result : @unchecked) match { + case Left(error) => cask.Response(error, 500) + case Right(other) => cask.Response(s"$other", 200) + } + } + /** Creates list of users with given input array + * + */ + @cask.post("/user/createWithArray") + def createUsersWithArrayInput(request: cask.Request) = { + // auth method api_key : apiKey, keyParamName: api_key + + def failFast = request.queryParams.keySet.contains("failFast") + + val result = for { + user <- Parsed.fromTry(UserData.manyFromJsonStringValidated(request.bodyAsString)).mapError(e => s"Error parsing json as an array of User from >${request.bodyAsString}< : ${e}") /* array */ + resultTry <- Parsed.eval(service.createUsersWithArrayInput(user)) + result <- Parsed.fromTry(resultTry) + } yield result + + (result : @unchecked) match { + case Left(error) => cask.Response(error, 500) + case Right(other) => cask.Response(s"$other", 200) + } + } + /** Creates list of users with given input array + * + */ + @cask.post("/user/createWithList") + def createUsersWithListInput(request: cask.Request) = { + // auth method api_key : apiKey, keyParamName: api_key + + def failFast = request.queryParams.keySet.contains("failFast") + + val result = for { + user <- Parsed.fromTry(UserData.manyFromJsonStringValidated(request.bodyAsString)).mapError(e => s"Error parsing json as an array of User from >${request.bodyAsString}< : ${e}") /* array */ + resultTry <- Parsed.eval(service.createUsersWithListInput(user)) + result <- Parsed.fromTry(resultTry) + } yield result + + (result : @unchecked) match { + case Left(error) => cask.Response(error, 500) + case Right(other) => cask.Response(s"$other", 200) + } + } + /** Delete user + * + */ + @cask.delete("/user/:username") + def deleteUser(username : String, request: cask.Request) = { + // auth method api_key : apiKey, keyParamName: api_key + + def failFast = request.queryParams.keySet.contains("failFast") + + val result = for { + username <- Parsed(username) + resultTry <- Parsed.eval(service.deleteUser(username)) + result <- Parsed.fromTry(resultTry) + } yield result + + (result : @unchecked) match { + case Left(error) => cask.Response(error, 500) + case Right(other) => cask.Response(s"$other", 200) + } + } + /** Get user by user name + * + */ + // conflicts with [/user/{username}, /user/login, /user/logout] after/user, ignoring @cask.get("/user/:username") + def getUserByName(username : String, request: cask.Request) = { + + def failFast = request.queryParams.keySet.contains("failFast") + + val result = for { + username <- Parsed(username) + resultTry <- Parsed.eval(service.getUserByName(username)) + result <- Parsed.fromTry(resultTry) + } yield result + + (result : @unchecked) match { + case Left(error) => cask.Response(error, 500) + case Right(value : User) => cask.Response(data = write(value), 200, headers = Seq("Content-Type" -> "application/json")) + case Right(other) => cask.Response(s"$other", 200) + } + } + /** Logs user into the system + * + */ + // conflicts with [/user/{username}, /user/login, /user/logout] after/user, ignoring @cask.get("/user/login") + def loginUser(request: cask.Request, username : String, password : String) = { + + def failFast = request.queryParams.keySet.contains("failFast") + + val result = for { + resultTry <- Parsed.eval(service.loginUser(username, password)) + result <- Parsed.fromTry(resultTry) + } yield result + + (result : @unchecked) match { + case Left(error) => cask.Response(error, 500) + case Right(value : String) => cask.Response(data = write(value), 200, headers = Seq("Content-Type" -> "application/json")) + case Right(other) => cask.Response(s"$other", 200) + } + } + /** Logs out current logged in user session + * + */ + // conflicts with [/user/{username}, /user/login, /user/logout] after/user, ignoring @cask.get("/user/logout") + def logoutUser(request: cask.Request) = { + // auth method api_key : apiKey, keyParamName: api_key + + def failFast = request.queryParams.keySet.contains("failFast") + + val result = for { + resultTry <- Parsed.eval(service.logoutUser()) + result <- Parsed.fromTry(resultTry) + } yield result + + (result : @unchecked) match { + case Left(error) => cask.Response(error, 500) + case Right(other) => cask.Response(s"$other", 200) + } + } + /** Updated user + * + */ + @cask.put("/user/:username") + def updateUser(username : String, request: cask.Request) = { + // auth method api_key : apiKey, keyParamName: api_key + + def failFast = request.queryParams.keySet.contains("failFast") + + val result = for { + username <- Parsed(username) + userJson <- Parsed.fromTry(request.bodyAsJson) + userData <- Parsed.eval(UserData.fromJson(userJson)) /* not array or map */ + user <- Parsed.fromTry(userData.validated(failFast)) + resultTry <- Parsed.eval(service.updateUser(username, user)) + result <- Parsed.fromTry(resultTry) + } yield result + + (result : @unchecked) match { + case Left(error) => cask.Response(error, 500) + case Right(other) => cask.Response(s"$other", 200) + } + } + + initialize() } diff --git a/samples/server/petstore/scala-cask/jvm/src/main/scala/sample/cask/api/package.scala b/samples/server/petstore/scala-cask/jvm/src/main/scala/sample/cask/api/package.scala index 58b9ffef03b1..28248ab8be29 100644 --- a/samples/server/petstore/scala-cask/jvm/src/main/scala/sample/cask/api/package.scala +++ b/samples/server/petstore/scala-cask/jvm/src/main/scala/sample/cask/api/package.scala @@ -1,17 +1,19 @@ -/** OpenAPI Petstore This is a sample server Petstore server. For this sample, you can use the api - * key `special-key` to test the authorization filters. - * - * OpenAPI spec version: 1.0.0 - * - * Contact: team@openapitools.org - * - * NOTE: This class is auto generated by OpenAPI Generator. - * - * https://openapi-generator.tech - */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator. + * + * https://openapi-generator.tech + */ package sample.cask.api + import cask.FormEntry import io.undertow.server.handlers.form.{FormData, FormParserFactory} @@ -23,14 +25,15 @@ import scala.reflect.ClassTag import scala.util.* import upickle.default.* + extension (f: java.io.File) { - def bytes: Array[Byte] = java.nio.file.Files.readAllBytes(f.toPath) - def toBase64: String = java.util.Base64.getEncoder.encodeToString(bytes) + def bytes: Array[Byte] = java.nio.file.Files.readAllBytes(f.toPath) + def toBase64: String = java.util.Base64.getEncoder.encodeToString(bytes) } // TODO - writing files as json isn't probably what we want to do given Writer[java.io.File] = new Writer[java.io.File] { - def write0[V](out: upickle.core.Visitor[?, V], v: java.io.File) = out.visitString(v.toBase64, -1) + def write0[V](out: upickle.core.Visitor[?, V], v: java.io.File) = out.visitString(v.toBase64, -1) } // needed for BigDecimal params @@ -44,87 +47,79 @@ object Parsed { def eval[A](value: => A): Parsed[A] = Try(value) match { case Failure(exp) => Left(s"Error: ${exp.getMessage}") - case Success(ok) => Right(ok) + case Success(ok) => Right(ok) } - def fromTry[A](value: Try[A]) = value match { - case Failure(err) => Left(err.getMessage) - case Success(ok) => Right(ok) + def fromTry[A](value : Try[A]) = value match { + case Failure(err) => Left(err.getMessage) + case Success(ok) => Right(ok) } def fail[A](msg: String): Parsed[A] = Left(msg) - def optionalValue( - map: Map[String, collection.Seq[String]], - key: String - ): Parsed[Option[String]] = { - map.get(key) match { - case Some(Seq(only: String)) => Parsed(Option(only)) - case Some(Seq()) => Parsed(None) - case Some(many) => Parsed.fail(s"${many.size} values set for '$key'") - case None => Parsed(None) + def optionalValue(map: Map[String, collection.Seq[String]], key: String): Parsed[Option[String]] = { + map.get(key) match { + case Some(Seq(only: String)) => Parsed(Option(only)) + case Some(Seq()) => Parsed(None) + case Some(many) => Parsed.fail(s"${many.size} values set for '$key'") + case None => Parsed(None) + } } - } - def singleValue(map: Map[String, collection.Seq[String]], key: String): Parsed[String] = { - map.get(key) match { - case Some(Seq(only: String)) => Parsed(only) - case Some(Seq()) => Parsed("") - case Some(many) => Parsed.fail(s"${many.size} values set for '$key'") - case None => Parsed.fail(s"required '$key' was not set") + def singleValue(map: Map[String, collection.Seq[String]], key : String): Parsed[String] = { + map.get(key) match { + case Some(Seq(only : String)) => Parsed(only) + case Some(Seq()) => Parsed("") + case Some(many) => Parsed.fail(s"${many.size} values set for '$key'") + case None => Parsed.fail(s"required '$key' was not set") + } } - } - - def manyValues( - map: Map[String, collection.Seq[String]], - key: String, - required: Boolean - ): Parsed[List[String]] = { - map.get(key) match { - case Some(many) => Parsed(many.toList) - case None if required => Parsed.fail(s"required '$key' was not set") - case None => Parsed(Nil) + + def manyValues(map: Map[String, collection.Seq[String]], key : String, required: Boolean): Parsed[List[String]] = { + map.get(key) match { + case Some(many) => Parsed(many.toList) + case None if required => Parsed.fail(s"required '$key' was not set") + case None => Parsed(Nil) + } } - } } -extension [A](parsed: Parsed[A]) { +extension[A] (parsed: Parsed[A]) { def toEither: Either[String, A] = parsed - def asLong(using ev: A =:= String): Parsed[Long] = as[Long](_.toLongOption) - def asBoolean(using ev: A =:= String): Parsed[Boolean] = as[Boolean](_.toBooleanOption) - def asInt(using ev: A =:= String): Parsed[Int] = as[Int](_.toIntOption) - def asByte(using ev: A =:= String): Parsed[Byte] = as[Byte](_.toByteOption) - def asUuid(using ev: A =:= String): Parsed[UUID] = as[UUID](x => Try(UUID.fromString(x)).toOption) - def asFloat(using ev: A =:= String): Parsed[Float] = as[Float](_.toFloatOption) - def asDouble(using ev: A =:= String): Parsed[Double] = as[Double](_.toDoubleOption) - def asDate(using ev: A =:= String): Parsed[LocalDate] = - as[LocalDate](x => Try(LocalDate.parse(x)).toOption) - - private def as[B: ClassTag](f: String => Option[B])(using ev: A =:= String): Parsed[B] = - parsed.flatMap { str => - f(ev(str)) match { - case None => - Parsed.fail(s"'$str' cannot be parsed as a ${implicitly[ClassTag[B]].runtimeClass}") - case Some(x) => Parsed(x) - } + def asLong(using ev : A =:= String): Parsed[Long] = as[Long](_.toLongOption) + def asBoolean(using ev : A =:= String): Parsed[Boolean] = as[Boolean](_.toBooleanOption) + def asInt(using ev : A =:= String): Parsed[Int] = as[Int](_.toIntOption) + def asByte(using ev : A =:= String): Parsed[Byte] = as[Byte](_.toByteOption) + def asUuid(using ev : A =:= String): Parsed[UUID] = as[UUID](x => Try(UUID.fromString(x)).toOption) + def asFloat(using ev : A =:= String): Parsed[Float] = as[Float](_.toFloatOption) + def asDouble(using ev : A =:= String): Parsed[Double] = as[Double](_.toDoubleOption) + def asDate(using ev: A =:= String): Parsed[LocalDate] = as[LocalDate](x => Try(LocalDate.parse(x)).toOption) + + private def as[B : ClassTag](f : String => Option[B])(using ev : A =:= String): Parsed[B] = parsed.flatMap { str => + f(ev(str)) match { + case None => Parsed.fail(s"'$str' cannot be parsed as a ${implicitly[ClassTag[B]].runtimeClass}") + case Some(x) => Parsed(x) } + } - def mapError(f: String => String): Parsed[A] = parsed match { + + def mapError(f : String => String) : Parsed[A] = parsed match { case Left(msg) => Left(f(msg)) - case right => right + case right => right } def map[B](f: A => B): Parsed[B] = parsed match { case Right(value) => Right(f(value)) - case Left(err) => Left(err) + case Left(err) => Left(err) } - def flatMap[B](f: A => Parsed[B]): Parsed[B] = parsed match { + def flatMap[B](f : A => Parsed[B]): Parsed[B] = parsed match { case Right(value) => f(value) - case Left(err) => Left(err) + case Left(err) => Left(err) } } + extension (request: cask.Request) { def formSingleValueRequired(paramName: String): Parsed[String] = { @@ -136,25 +131,21 @@ extension (request: cask.Request) { Parsed.optionalValue(Map(paramName -> data), paramName) } - def formValueAsFileOptional(paramName: String): Parsed[Option[File]] = { - val data = formDataForKey(paramName) - data.map(_.getFileItem.getFile.toFile).toSeq match { - case Seq() => Parsed(None) - case Seq(file) => Parsed(Option(file)) - case many => Parsed.fail(s"${many.size} file values set for '$paramName'") + def formValueAsFileOptional(paramName: String): Parsed[Option[File]] = { + val data = formDataForKey(paramName) + data.map(_.getFileItem.getFile.toFile).toSeq match { + case Seq() => Parsed(None) + case Seq(file) => Parsed(Option(file)) + case many => Parsed.fail(s"${many.size} file values set for '$paramName'") + } } - } def formValueAsFileRequired(paramName: String): Parsed[File] = { val data = formDataForKey(paramName) data.map(_.getFileItem.getFile.toFile).toSeq match { - case Seq() => - Parsed.fail( - s"No file form data was submitted for '$paramName'. The submitted form keys were: ${formDataKeys - .mkString(",")}" - ) + case Seq() => Parsed.fail(s"No file form data was submitted for '$paramName'. The submitted form keys were: ${formDataKeys.mkString(",")}") case Seq(file) => Parsed(file) - case many => Parsed.fail(s"${many.size} file values set for '$paramName'") + case many => Parsed.fail(s"${many.size} file values set for '$paramName'") } } @@ -163,40 +154,35 @@ extension (request: cask.Request) { Parsed.manyValues(Map(paramName -> data), paramName, required) } - def formData: FormData = - FormParserFactory.builder().build().createParser(request.exchange).parseBlocking() + def formData: FormData = FormParserFactory.builder().build().createParser(request.exchange).parseBlocking() def formDataKeys: Iterator[String] = formData.iterator().asScala - def formDataForKey(paramName: String): Iterable[FormData.FormValue] = - formData.get(paramName).asScala + def formDataForKey(paramName: String): Iterable[FormData.FormValue] = formData.get(paramName).asScala + + def headerSingleValueOptional(paramName: String): Parsed[Option[String]] = Parsed.optionalValue(request.headers, paramName) + def headerSingleValueRequired(paramName: String): Parsed[String] = Parsed.singleValue(request.headers, paramName) - def headerSingleValueOptional(paramName: String): Parsed[Option[String]] = - Parsed.optionalValue(request.headers, paramName) - def headerSingleValueRequired(paramName: String): Parsed[String] = - Parsed.singleValue(request.headers, paramName) - - def headerManyValues(paramName: String, required: Boolean): Parsed[List[String]] = - Parsed.manyValues(request.headers, paramName, required) + def headerManyValues(paramName: String, required: Boolean): Parsed[List[String]] = Parsed.manyValues(request.headers, paramName, required) def bodyAsString = new String(request.readAllBytes(), "UTF-8") - def bodyAsJson: Try[ujson.Value] = { - val jason = bodyAsString - try { - Success(read[ujson.Value](jason)) - } catch { - case scala.util.control.NonFatal(e) => sys.error(s"Error parsing json '$jason': $e") + def bodyAsJson : Try[ujson.Value] = { + val jason = bodyAsString + try { + Success(read[ujson.Value](jason)) + } catch { + case scala.util.control.NonFatal(e) => sys.error(s"Error parsing json '$jason': $e") + } } - } - - def pathValue(index: Int, paramName: String, required: Boolean): Parsed[String] = { - request.remainingPathSegments + + def pathValue(index: Int, paramName: String, required : Boolean): Parsed[String] = { + request + .remainingPathSegments .lift(index) match { case Some(value) => Right(value) - case None if required => - Left(s"'$paramName'' is a required path parameter at path position $index") - case None => Right("") + case None if required => Left(s"'$paramName'' is a required path parameter at path position $index") + case None => Right("") } } } diff --git a/samples/server/petstore/scala-cask/jvm/src/main/scala/sample/cask/package.scala b/samples/server/petstore/scala-cask/jvm/src/main/scala/sample/cask/package.scala index 0c58a5017739..f4c86e310e04 100644 --- a/samples/server/petstore/scala-cask/jvm/src/main/scala/sample/cask/package.scala +++ b/samples/server/petstore/scala-cask/jvm/src/main/scala/sample/cask/package.scala @@ -1,19 +1,20 @@ -/** OpenAPI Petstore This is a sample server Petstore server. For this sample, you can use the api - * key `special-key` to test the authorization filters. - * - * OpenAPI spec version: 1.0.0 - * - * Contact: team@openapitools.org - * - * NOTE: This class is auto generated by OpenAPI Generator. - * - * https://openapi-generator.tech - */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator. + * + * https://openapi-generator.tech + */ package cask.groupId.server def box(str: String): String = { - val lines = str.linesIterator.toList + val lines = str.linesIterator.toList val maxLen = (0 +: lines.map(_.length)).max val boxed = lines.map { line => s" | ${line.padTo(maxLen, ' ')} |" diff --git a/samples/server/petstore/scala-cask/shared/src/main/scala/sample/cask/api/PetService.scala b/samples/server/petstore/scala-cask/shared/src/main/scala/sample/cask/api/PetService.scala index 5afa262aaba2..4289c9e0fd0f 100644 --- a/samples/server/petstore/scala-cask/shared/src/main/scala/sample/cask/api/PetService.scala +++ b/samples/server/petstore/scala-cask/shared/src/main/scala/sample/cask/api/PetService.scala @@ -1,17 +1,19 @@ //> using scala "3.3.1" //> using lib "com.lihaoyi::cask:0.8.3" //> using lib "com.lihaoyi::scalatags:0.12.0" -/** OpenAPI Petstore This is a sample server Petstore server. For this sample, you can use the api - * key `special-key` to test the authorization filters. - * - * OpenAPI spec version: 1.0.0 - * - * Contact: team@openapitools.org - * - * NOTE: This class is auto generated by OpenAPI Generator. - * - * https://openapi-generator.tech - */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator. + * + * https://openapi-generator.tech + */ + // generated from apiService.mustache package sample.cask.api @@ -23,318 +25,264 @@ import scala.util.Failure import scala.util.Try import _root_.sample.cask.model.* -/** The PetService companion object. - * - * Use the PetService() companion object to create an instance which returns a 'not implemented' - * error for each operation. - */ +/** + * The PetService companion object. + * + * Use the PetService() companion object to create an instance which returns a 'not implemented' error + * for each operation. + * + */ object PetService { - /** The 'Handler' is an implementation of PetService convenient for delegating or overriding - * individual functions - */ + /** + * The 'Handler' is an implementation of PetService convenient for delegating or overriding individual functions + */ case class Handler[F[_]]( - addPetHandler: (pet: Pet) => F[Pet], - deletePetHandler: (petId: Long, apiKey: Option[String]) => F[Unit], - findPetsByStatusHandler: (status: Seq[String]) => F[List[Pet]], - findPetsByTagsHandler: (tags: Seq[String]) => F[List[Pet]], - getPetByIdHandler: (petId: Long) => F[Pet], - updatePetHandler: (pet: Pet) => F[Pet], - updatePetWithFormHandler: ( - petId: Long, - name: Option[String], - status: Option[String] - ) => F[Unit], - uploadFileHandler: ( - petId: Long, - additionalMetadata: Option[String], - file: Option[File] - ) => F[ApiResponse] + addPetHandler : (pet : Pet) => F[Pet], + deletePetHandler : (petId : Long, apiKey : Option[String]) => F[Unit], + findPetsByStatusHandler : (status : Seq[String]) => F[List[Pet]], + findPetsByTagsHandler : (tags : Seq[String]) => F[List[Pet]], + getPetByIdHandler : (petId : Long) => F[Pet], + updatePetHandler : (pet : Pet) => F[Pet], + updatePetWithFormHandler : (petId : Long, name : Option[String], status : Option[String]) => F[Unit], + uploadFileHandler : (petId : Long, additionalMetadata : Option[String], file : Option[File]) => F[ApiResponse] ) extends PetService[F] { - override def addPet(pet: Pet): F[Pet] = { - addPetHandler(pet) - } + override def addPet(pet : Pet) : F[Pet] = { + addPetHandler(pet) + } - override def deletePet(petId: Long, apiKey: Option[String]): F[Unit] = { - deletePetHandler(petId, apiKey) - } + override def deletePet(petId : Long, apiKey : Option[String]) : F[Unit] = { + deletePetHandler(petId, apiKey) + } - override def findPetsByStatus(status: Seq[String]): F[List[Pet]] = { - findPetsByStatusHandler(status) - } + override def findPetsByStatus(status : Seq[String]) : F[List[Pet]] = { + findPetsByStatusHandler(status) + } - override def findPetsByTags(tags: Seq[String]): F[List[Pet]] = { - findPetsByTagsHandler(tags) - } + override def findPetsByTags(tags : Seq[String]) : F[List[Pet]] = { + findPetsByTagsHandler(tags) + } - override def getPetById(petId: Long): F[Pet] = { - getPetByIdHandler(petId) - } + override def getPetById(petId : Long) : F[Pet] = { + getPetByIdHandler(petId) + } - override def updatePet(pet: Pet): F[Pet] = { - updatePetHandler(pet) - } + override def updatePet(pet : Pet) : F[Pet] = { + updatePetHandler(pet) + } - override def updatePetWithForm( - petId: Long, - name: Option[String], - status: Option[String] - ): F[Unit] = { - updatePetWithFormHandler(petId, name, status) - } + override def updatePetWithForm(petId : Long, name : Option[String], status : Option[String]) : F[Unit] = { + updatePetWithFormHandler(petId, name, status) + } - override def uploadFile( - petId: Long, - additionalMetadata: Option[String], - file: Option[File] - ): F[ApiResponse] = { - uploadFileHandler(petId, additionalMetadata, file) - } + override def uploadFile(petId : Long, additionalMetadata : Option[String], file : Option[File]) : F[ApiResponse] = { + uploadFileHandler(petId, additionalMetadata, file) + } } - def apply(): PetService[Try] = PetService.Handler[Try]( - (_) => notImplemented("addPet"), - // override def addPet(pet : Pet) : Pet = ??? - (_, _) => notImplemented("deletePet"), - // override def deletePet(petId : Long, apiKey : Option[String]) : Unit = ??? - (_) => notImplemented("findPetsByStatus"), - // override def findPetsByStatus(status : Seq[String]) : List[Pet] = ??? - (_) => notImplemented("findPetsByTags"), - // override def findPetsByTags(tags : Seq[String]) : List[Pet] = ??? - (_) => notImplemented("getPetById"), - // override def getPetById(petId : Long) : Pet = ??? - (_) => notImplemented("updatePet"), - // override def updatePet(pet : Pet) : Pet = ??? - (_, _, _) => notImplemented("updatePetWithForm"), - // override def updatePetWithForm(petId : Long, name : Option[String], status : Option[String]) : Unit = ??? - (_, _, _) => notImplemented("uploadFile") - // override def uploadFile(petId : Long, additionalMetadata : Option[String], file : Option[File]) : ApiResponse = ??? + def apply() : PetService[Try] = PetService.Handler[Try]( + (_) => notImplemented("addPet"), + // override def addPet(pet : Pet) : Pet = ??? + (_, _) => notImplemented("deletePet"), + // override def deletePet(petId : Long, apiKey : Option[String]) : Unit = ??? + (_) => notImplemented("findPetsByStatus"), + // override def findPetsByStatus(status : Seq[String]) : List[Pet] = ??? + (_) => notImplemented("findPetsByTags"), + // override def findPetsByTags(tags : Seq[String]) : List[Pet] = ??? + (_) => notImplemented("getPetById"), + // override def getPetById(petId : Long) : Pet = ??? + (_) => notImplemented("updatePet"), + // override def updatePet(pet : Pet) : Pet = ??? + (_, _, _) => notImplemented("updatePetWithForm"), + // override def updatePetWithForm(petId : Long, name : Option[String], status : Option[String]) : Unit = ??? + (_, _, _) => notImplemented("uploadFile") + // override def uploadFile(petId : Long, additionalMetadata : Option[String], file : Option[File]) : ApiResponse = ??? ) - private def notImplemented(name: String) = Failure(new Exception(s"TODO: $name not implemented")) + private def notImplemented(name : String) = Failure(new Exception(s"TODO: $name not implemented")) } -/** The Pet business-logic - * - * The 'asHandler' will return an implementation which allows for easily overriding individual - * operations. - * - * equally there are "on<Function>" helper methods for easily overriding individual functions - * - * @tparam F - * the effect type (Future, Try, IO, ID, etc) of the operations - */ +/** + * The Pet business-logic + * + * + * The 'asHandler' will return an implementation which allows for easily overriding individual operations. + * + * equally there are "on<Function>" helper methods for easily overriding individual functions + * + * @tparam F the effect type (Future, Try, IO, ID, etc) of the operations + */ trait PetService[F[_]] { - /** Add a new pet to the store - * - * @return - * Pet - */ - def addPet(pet: Pet): F[Pet] - - /** override addPet with the given handler - * @return - * a new implementation of PetService[F] with addPet overridden using the given handler - */ - final def onAddPet(handler: (pet: Pet) => F[Pet]): PetService[F] = { + * + * @return Pet + */ + def addPet(pet : Pet) : F[Pet] + + /** + * override addPet with the given handler + * @return a new implementation of PetService[F] with addPet overridden using the given handler + */ + final def onAddPet(handler : (pet : Pet) => F[Pet]) : PetService[F] = { asHandler.copy(addPetHandler = handler) } - /** Deletes a pet - * - * @return - */ - def deletePet(petId: Long, apiKey: Option[String]): F[Unit] - - /** override deletePet with the given handler - * @return - * a new implementation of PetService[F] with deletePet overridden using the given handler - */ - final def onDeletePet( - handler: (petId: Long, apiKey: Option[String]) => F[Unit] - ): PetService[F] = { + * + * @return + */ + def deletePet(petId : Long, apiKey : Option[String]) : F[Unit] + + /** + * override deletePet with the given handler + * @return a new implementation of PetService[F] with deletePet overridden using the given handler + */ + final def onDeletePet(handler : (petId : Long, apiKey : Option[String]) => F[Unit]) : PetService[F] = { asHandler.copy(deletePetHandler = handler) } - /** Finds Pets by status - * - * @return - * List[Pet] - */ - def findPetsByStatus(status: Seq[String]): F[List[Pet]] - - /** override findPetsByStatus with the given handler - * @return - * a new implementation of PetService[F] with findPetsByStatus overridden using the given - * handler - */ - final def onFindPetsByStatus(handler: (status: Seq[String]) => F[List[Pet]]): PetService[F] = { + * + * @return List[Pet] + */ + def findPetsByStatus(status : Seq[String]) : F[List[Pet]] + + /** + * override findPetsByStatus with the given handler + * @return a new implementation of PetService[F] with findPetsByStatus overridden using the given handler + */ + final def onFindPetsByStatus(handler : (status : Seq[String]) => F[List[Pet]]) : PetService[F] = { asHandler.copy(findPetsByStatusHandler = handler) } - /** Finds Pets by tags - * - * @return - * List[Pet] - */ - def findPetsByTags(tags: Seq[String]): F[List[Pet]] - - /** override findPetsByTags with the given handler - * @return - * a new implementation of PetService[F] with findPetsByTags overridden using the given handler - */ - final def onFindPetsByTags(handler: (tags: Seq[String]) => F[List[Pet]]): PetService[F] = { + * + * @return List[Pet] + */ + def findPetsByTags(tags : Seq[String]) : F[List[Pet]] + + /** + * override findPetsByTags with the given handler + * @return a new implementation of PetService[F] with findPetsByTags overridden using the given handler + */ + final def onFindPetsByTags(handler : (tags : Seq[String]) => F[List[Pet]]) : PetService[F] = { asHandler.copy(findPetsByTagsHandler = handler) } - /** Find pet by ID - * - * @return - * Pet - */ - def getPetById(petId: Long): F[Pet] - - /** override getPetById with the given handler - * @return - * a new implementation of PetService[F] with getPetById overridden using the given handler - */ - final def onGetPetById(handler: (petId: Long) => F[Pet]): PetService[F] = { + * + * @return Pet + */ + def getPetById(petId : Long) : F[Pet] + + /** + * override getPetById with the given handler + * @return a new implementation of PetService[F] with getPetById overridden using the given handler + */ + final def onGetPetById(handler : (petId : Long) => F[Pet]) : PetService[F] = { asHandler.copy(getPetByIdHandler = handler) } - /** Update an existing pet - * - * @return - * Pet - */ - def updatePet(pet: Pet): F[Pet] - - /** override updatePet with the given handler - * @return - * a new implementation of PetService[F] with updatePet overridden using the given handler - */ - final def onUpdatePet(handler: (pet: Pet) => F[Pet]): PetService[F] = { + * + * @return Pet + */ + def updatePet(pet : Pet) : F[Pet] + + /** + * override updatePet with the given handler + * @return a new implementation of PetService[F] with updatePet overridden using the given handler + */ + final def onUpdatePet(handler : (pet : Pet) => F[Pet]) : PetService[F] = { asHandler.copy(updatePetHandler = handler) } - /** Updates a pet in the store with form data - * - * @return - */ - def updatePetWithForm(petId: Long, name: Option[String], status: Option[String]): F[Unit] - - /** override updatePetWithForm with the given handler - * @return - * a new implementation of PetService[F] with updatePetWithForm overridden using the given - * handler - */ - final def onUpdatePetWithForm( - handler: (petId: Long, name: Option[String], status: Option[String]) => F[Unit] - ): PetService[F] = { + * + * @return + */ + def updatePetWithForm(petId : Long, name : Option[String], status : Option[String]) : F[Unit] + + /** + * override updatePetWithForm with the given handler + * @return a new implementation of PetService[F] with updatePetWithForm overridden using the given handler + */ + final def onUpdatePetWithForm(handler : (petId : Long, name : Option[String], status : Option[String]) => F[Unit]) : PetService[F] = { asHandler.copy(updatePetWithFormHandler = handler) } - /** uploads an image - * - * @return - * ApiResponse - */ - def uploadFile( - petId: Long, - additionalMetadata: Option[String], - file: Option[File] - ): F[ApiResponse] - - /** override uploadFile with the given handler - * @return - * a new implementation of PetService[F] with uploadFile overridden using the given handler - */ - final def onUploadFile( - handler: ( - petId: Long, - additionalMetadata: Option[String], - file: Option[File] - ) => F[ApiResponse] - ): PetService[F] = { + * + * @return ApiResponse + */ + def uploadFile(petId : Long, additionalMetadata : Option[String], file : Option[File]) : F[ApiResponse] + + /** + * override uploadFile with the given handler + * @return a new implementation of PetService[F] with uploadFile overridden using the given handler + */ + final def onUploadFile(handler : (petId : Long, additionalMetadata : Option[String], file : Option[File]) => F[ApiResponse]) : PetService[F] = { asHandler.copy(uploadFileHandler = handler) } - /** @return - * a Handler implementation of this service - */ - final def asHandler: PetService.Handler[F] = this match { - case h: PetService.Handler[F] => h - case _ => - PetService.Handler[F]( - (pet) => addPet(pet), - (petId, apiKey) => deletePet(petId, apiKey), - (status) => findPetsByStatus(status), - (tags) => findPetsByTags(tags), - (petId) => getPetById(petId), - (pet) => updatePet(pet), - (petId, name, status) => updatePetWithForm(petId, name, status), - (petId, additionalMetadata, file) => uploadFile(petId, additionalMetadata, file) - ) + /** + * @return a Handler implementation of this service + */ + final def asHandler : PetService.Handler[F] = this match { + case h : PetService.Handler[F] => h + case _ => + PetService.Handler[F]( + (pet) => addPet(pet), + (petId, apiKey) => deletePet(petId, apiKey), + (status) => findPetsByStatus(status), + (tags) => findPetsByTags(tags), + (petId) => getPetById(petId), + (pet) => updatePet(pet), + (petId, name, status) => updatePetWithForm(petId, name, status), + (petId, additionalMetadata, file) => uploadFile(petId, additionalMetadata, file) + ) } - /** This function will change the effect type of this service. - * - * It's not unlike a typical map operation from A => B, except we're not mapping a type from A to - * B, but rather from F[A] => G[A] using the 'changeEffect' function. - * - * For, this could turn an asynchronous service (one which returns Future[_] types) into a - * synchronous one (one which returns Try[_] types) by awaiting on the Future. - * - * It could change an IO type (like cats effect or ZIO) into an ID[A] which is just: - * ``` - * type ID[A] => A - * ``` - * - * @tparam G - * the new "polymorphic" effect type - * @param changeEffect - * the "natural transformation" which can change one effect type into another - * @return - * a new PetService service implementation with effect type [G] - */ - final def mapEffect[G[_]](changeEffect: [A] => F[A] => G[A]): PetService[G] = { + /** + * This function will change the effect type of this service. + * + * It's not unlike a typical map operation from A => B, except we're not mapping + * a type from A to B, but rather from F[A] => G[A] using the 'changeEffect' function. + * + * For, this could turn an asynchronous service (one which returns Future[_] types) into + * a synchronous one (one which returns Try[_] types) by awaiting on the Future. + * + * It could change an IO type (like cats effect or ZIO) into an ID[A] which is just: + * ``` + * type ID[A] => A + * ``` + * + * @tparam G the new "polymorphic" effect type + * @param changeEffect the "natural transformation" which can change one effect type into another + * @return a new PetService service implementation with effect type [G] + */ + final def mapEffect[G[_]](changeEffect : [A] => F[A] => G[A]) : PetService[G] = { val self = this new PetService[G] { - override def addPet(pet: Pet): G[Pet] = changeEffect { - self.addPet(pet) - } - override def deletePet(petId: Long, apiKey: Option[String]): G[Unit] = changeEffect { - self.deletePet(petId, apiKey) - } - override def findPetsByStatus(status: Seq[String]): G[List[Pet]] = changeEffect { - self.findPetsByStatus(status) - } - override def findPetsByTags(tags: Seq[String]): G[List[Pet]] = changeEffect { - self.findPetsByTags(tags) - } - override def getPetById(petId: Long): G[Pet] = changeEffect { - self.getPetById(petId) - } - override def updatePet(pet: Pet): G[Pet] = changeEffect { - self.updatePet(pet) - } - override def updatePetWithForm( - petId: Long, - name: Option[String], - status: Option[String] - ): G[Unit] = changeEffect { - self.updatePetWithForm(petId, name, status) - } - override def uploadFile( - petId: Long, - additionalMetadata: Option[String], - file: Option[File] - ): G[ApiResponse] = changeEffect { - self.uploadFile(petId, additionalMetadata, file) - } + override def addPet(pet : Pet) : G[Pet] = changeEffect { + self.addPet(pet) + } + override def deletePet(petId : Long, apiKey : Option[String]) : G[Unit] = changeEffect { + self.deletePet(petId, apiKey) + } + override def findPetsByStatus(status : Seq[String]) : G[List[Pet]] = changeEffect { + self.findPetsByStatus(status) + } + override def findPetsByTags(tags : Seq[String]) : G[List[Pet]] = changeEffect { + self.findPetsByTags(tags) + } + override def getPetById(petId : Long) : G[Pet] = changeEffect { + self.getPetById(petId) + } + override def updatePet(pet : Pet) : G[Pet] = changeEffect { + self.updatePet(pet) + } + override def updatePetWithForm(petId : Long, name : Option[String], status : Option[String]) : G[Unit] = changeEffect { + self.updatePetWithForm(petId, name, status) + } + override def uploadFile(petId : Long, additionalMetadata : Option[String], file : Option[File]) : G[ApiResponse] = changeEffect { + self.uploadFile(petId, additionalMetadata, file) + } } } } diff --git a/samples/server/petstore/scala-cask/shared/src/main/scala/sample/cask/api/StoreService.scala b/samples/server/petstore/scala-cask/shared/src/main/scala/sample/cask/api/StoreService.scala index 15fe72400276..30cf87209d6a 100644 --- a/samples/server/petstore/scala-cask/shared/src/main/scala/sample/cask/api/StoreService.scala +++ b/samples/server/petstore/scala-cask/shared/src/main/scala/sample/cask/api/StoreService.scala @@ -1,196 +1,190 @@ //> using scala "3.3.1" //> using lib "com.lihaoyi::cask:0.8.3" //> using lib "com.lihaoyi::scalatags:0.12.0" -/** OpenAPI Petstore This is a sample server Petstore server. For this sample, you can use the api - * key `special-key` to test the authorization filters. - * - * OpenAPI spec version: 1.0.0 - * - * Contact: team@openapitools.org - * - * NOTE: This class is auto generated by OpenAPI Generator. - * - * https://openapi-generator.tech - */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator. + * + * https://openapi-generator.tech + */ + // generated from apiService.mustache package sample.cask.api import _root_.sample.cask.model.Order -import _root_.ujson.Value import scala.util.Failure import scala.util.Try import _root_.sample.cask.model.* -/** The StoreService companion object. - * - * Use the StoreService() companion object to create an instance which returns a 'not implemented' - * error for each operation. - */ +/** + * The StoreService companion object. + * + * Use the StoreService() companion object to create an instance which returns a 'not implemented' error + * for each operation. + * + */ object StoreService { - /** The 'Handler' is an implementation of StoreService convenient for delegating or overriding - * individual functions - */ + /** + * The 'Handler' is an implementation of StoreService convenient for delegating or overriding individual functions + */ case class Handler[F[_]]( - deleteOrderHandler: (orderId: String) => F[Unit], - getInventoryHandler: () => F[Value], - getOrderByIdHandler: (orderId: Long) => F[Order], - placeOrderHandler: (order: Order) => F[Order] + deleteOrderHandler : (orderId : String) => F[Unit], + getInventoryHandler : () => F[Map[String, Int]], + getOrderByIdHandler : (orderId : Long) => F[Order], + placeOrderHandler : (order : Order) => F[Order] ) extends StoreService[F] { - override def deleteOrder(orderId: String): F[Unit] = { - deleteOrderHandler(orderId) - } + override def deleteOrder(orderId : String) : F[Unit] = { + deleteOrderHandler(orderId) + } - override def getInventory(): F[Value] = { - getInventoryHandler() - } + override def getInventory() : F[Map[String, Int]] = { + getInventoryHandler() + } - override def getOrderById(orderId: Long): F[Order] = { - getOrderByIdHandler(orderId) - } + override def getOrderById(orderId : Long) : F[Order] = { + getOrderByIdHandler(orderId) + } - override def placeOrder(order: Order): F[Order] = { - placeOrderHandler(order) - } + override def placeOrder(order : Order) : F[Order] = { + placeOrderHandler(order) + } } - def apply(): StoreService[Try] = StoreService.Handler[Try]( - (_) => notImplemented("deleteOrder"), - // override def deleteOrder(orderId : String) : Unit = ??? - () => notImplemented("getInventory"), - // override def getInventory() : Value = ??? - (_) => notImplemented("getOrderById"), - // override def getOrderById(orderId : Long) : Order = ??? - (_) => notImplemented("placeOrder") - // override def placeOrder(order : Order) : Order = ??? + def apply() : StoreService[Try] = StoreService.Handler[Try]( + (_) => notImplemented("deleteOrder"), + // override def deleteOrder(orderId : String) : Unit = ??? + () => notImplemented("getInventory"), + // override def getInventory() : Map[String, Int] = ??? + (_) => notImplemented("getOrderById"), + // override def getOrderById(orderId : Long) : Order = ??? + (_) => notImplemented("placeOrder") + // override def placeOrder(order : Order) : Order = ??? ) - private def notImplemented(name: String) = Failure(new Exception(s"TODO: $name not implemented")) + private def notImplemented(name : String) = Failure(new Exception(s"TODO: $name not implemented")) } -/** The Store business-logic - * - * The 'asHandler' will return an implementation which allows for easily overriding individual - * operations. - * - * equally there are "on<Function>" helper methods for easily overriding individual functions - * - * @tparam F - * the effect type (Future, Try, IO, ID, etc) of the operations - */ +/** + * The Store business-logic + * + * + * The 'asHandler' will return an implementation which allows for easily overriding individual operations. + * + * equally there are "on<Function>" helper methods for easily overriding individual functions + * + * @tparam F the effect type (Future, Try, IO, ID, etc) of the operations + */ trait StoreService[F[_]] { - /** Delete purchase order by ID - * - * @return - */ - def deleteOrder(orderId: String): F[Unit] - - /** override deleteOrder with the given handler - * @return - * a new implementation of StoreService[F] with deleteOrder overridden using the given handler - */ - final def onDeleteOrder(handler: (orderId: String) => F[Unit]): StoreService[F] = { + * + * @return + */ + def deleteOrder(orderId : String) : F[Unit] + + /** + * override deleteOrder with the given handler + * @return a new implementation of StoreService[F] with deleteOrder overridden using the given handler + */ + final def onDeleteOrder(handler : (orderId : String) => F[Unit]) : StoreService[F] = { asHandler.copy(deleteOrderHandler = handler) } - /** Returns pet inventories by status - * - * @return - * Value - */ - def getInventory(): F[Value] - - /** override getInventory with the given handler - * @return - * a new implementation of StoreService[F] with getInventory overridden using the given handler - */ - final def onGetInventory(handler: () => F[Value]): StoreService[F] = { + * + * @return Map[String, Int] + */ + def getInventory() : F[Map[String, Int]] + + /** + * override getInventory with the given handler + * @return a new implementation of StoreService[F] with getInventory overridden using the given handler + */ + final def onGetInventory(handler : () => F[Map[String, Int]]) : StoreService[F] = { asHandler.copy(getInventoryHandler = handler) } - /** Find purchase order by ID - * - * @return - * Order - */ - def getOrderById(orderId: Long): F[Order] - - /** override getOrderById with the given handler - * @return - * a new implementation of StoreService[F] with getOrderById overridden using the given handler - */ - final def onGetOrderById(handler: (orderId: Long) => F[Order]): StoreService[F] = { + * + * @return Order + */ + def getOrderById(orderId : Long) : F[Order] + + /** + * override getOrderById with the given handler + * @return a new implementation of StoreService[F] with getOrderById overridden using the given handler + */ + final def onGetOrderById(handler : (orderId : Long) => F[Order]) : StoreService[F] = { asHandler.copy(getOrderByIdHandler = handler) } - /** Place an order for a pet - * - * @return - * Order - */ - def placeOrder(order: Order): F[Order] - - /** override placeOrder with the given handler - * @return - * a new implementation of StoreService[F] with placeOrder overridden using the given handler - */ - final def onPlaceOrder(handler: (order: Order) => F[Order]): StoreService[F] = { + * + * @return Order + */ + def placeOrder(order : Order) : F[Order] + + /** + * override placeOrder with the given handler + * @return a new implementation of StoreService[F] with placeOrder overridden using the given handler + */ + final def onPlaceOrder(handler : (order : Order) => F[Order]) : StoreService[F] = { asHandler.copy(placeOrderHandler = handler) } - /** @return - * a Handler implementation of this service - */ - final def asHandler: StoreService.Handler[F] = this match { - case h: StoreService.Handler[F] => h - case _ => - StoreService.Handler[F]( - (orderId) => deleteOrder(orderId), - () => getInventory(), - (orderId) => getOrderById(orderId), - (order) => placeOrder(order) - ) + /** + * @return a Handler implementation of this service + */ + final def asHandler : StoreService.Handler[F] = this match { + case h : StoreService.Handler[F] => h + case _ => + StoreService.Handler[F]( + (orderId) => deleteOrder(orderId), + () => getInventory(), + (orderId) => getOrderById(orderId), + (order) => placeOrder(order) + ) } - /** This function will change the effect type of this service. - * - * It's not unlike a typical map operation from A => B, except we're not mapping a type from A to - * B, but rather from F[A] => G[A] using the 'changeEffect' function. - * - * For, this could turn an asynchronous service (one which returns Future[_] types) into a - * synchronous one (one which returns Try[_] types) by awaiting on the Future. - * - * It could change an IO type (like cats effect or ZIO) into an ID[A] which is just: - * ``` - * type ID[A] => A - * ``` - * - * @tparam G - * the new "polymorphic" effect type - * @param changeEffect - * the "natural transformation" which can change one effect type into another - * @return - * a new StoreService service implementation with effect type [G] - */ - final def mapEffect[G[_]](changeEffect: [A] => F[A] => G[A]): StoreService[G] = { + /** + * This function will change the effect type of this service. + * + * It's not unlike a typical map operation from A => B, except we're not mapping + * a type from A to B, but rather from F[A] => G[A] using the 'changeEffect' function. + * + * For, this could turn an asynchronous service (one which returns Future[_] types) into + * a synchronous one (one which returns Try[_] types) by awaiting on the Future. + * + * It could change an IO type (like cats effect or ZIO) into an ID[A] which is just: + * ``` + * type ID[A] => A + * ``` + * + * @tparam G the new "polymorphic" effect type + * @param changeEffect the "natural transformation" which can change one effect type into another + * @return a new StoreService service implementation with effect type [G] + */ + final def mapEffect[G[_]](changeEffect : [A] => F[A] => G[A]) : StoreService[G] = { val self = this new StoreService[G] { - override def deleteOrder(orderId: String): G[Unit] = changeEffect { - self.deleteOrder(orderId) - } - override def getInventory(): G[Value] = changeEffect { - self.getInventory() - } - override def getOrderById(orderId: Long): G[Order] = changeEffect { - self.getOrderById(orderId) - } - override def placeOrder(order: Order): G[Order] = changeEffect { - self.placeOrder(order) - } + override def deleteOrder(orderId : String) : G[Unit] = changeEffect { + self.deleteOrder(orderId) + } + override def getInventory() : G[Map[String, Int]] = changeEffect { + self.getInventory() + } + override def getOrderById(orderId : Long) : G[Order] = changeEffect { + self.getOrderById(orderId) + } + override def placeOrder(order : Order) : G[Order] = changeEffect { + self.placeOrder(order) + } } } } diff --git a/samples/server/petstore/scala-cask/shared/src/main/scala/sample/cask/api/UserService.scala b/samples/server/petstore/scala-cask/shared/src/main/scala/sample/cask/api/UserService.scala index 4d16218acf86..e88c0dc95d49 100644 --- a/samples/server/petstore/scala-cask/shared/src/main/scala/sample/cask/api/UserService.scala +++ b/samples/server/petstore/scala-cask/shared/src/main/scala/sample/cask/api/UserService.scala @@ -1,17 +1,19 @@ //> using scala "3.3.1" //> using lib "com.lihaoyi::cask:0.8.3" //> using lib "com.lihaoyi::scalatags:0.12.0" -/** OpenAPI Petstore This is a sample server Petstore server. For this sample, you can use the api - * key `special-key` to test the authorization filters. - * - * OpenAPI spec version: 1.0.0 - * - * Contact: team@openapitools.org - * - * NOTE: This class is auto generated by OpenAPI Generator. - * - * https://openapi-generator.tech - */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator. + * + * https://openapi-generator.tech + */ + // generated from apiService.mustache package sample.cask.api @@ -22,278 +24,264 @@ import scala.util.Failure import scala.util.Try import _root_.sample.cask.model.* -/** The UserService companion object. - * - * Use the UserService() companion object to create an instance which returns a 'not implemented' - * error for each operation. - */ +/** + * The UserService companion object. + * + * Use the UserService() companion object to create an instance which returns a 'not implemented' error + * for each operation. + * + */ object UserService { - /** The 'Handler' is an implementation of UserService convenient for delegating or overriding - * individual functions - */ + /** + * The 'Handler' is an implementation of UserService convenient for delegating or overriding individual functions + */ case class Handler[F[_]]( - createUserHandler: (user: User) => F[Unit], - createUsersWithArrayInputHandler: (user: Seq[User]) => F[Unit], - createUsersWithListInputHandler: (user: Seq[User]) => F[Unit], - deleteUserHandler: (username: String) => F[Unit], - getUserByNameHandler: (username: String) => F[User], - loginUserHandler: (username: String, password: String) => F[String], - logoutUserHandler: () => F[Unit], - updateUserHandler: (username: String, user: User) => F[Unit] + createUserHandler : (user : User) => F[Unit], + createUsersWithArrayInputHandler : (user : Seq[User]) => F[Unit], + createUsersWithListInputHandler : (user : Seq[User]) => F[Unit], + deleteUserHandler : (username : String) => F[Unit], + getUserByNameHandler : (username : String) => F[User], + loginUserHandler : (username : String, password : String) => F[String], + logoutUserHandler : () => F[Unit], + updateUserHandler : (username : String, user : User) => F[Unit] ) extends UserService[F] { - override def createUser(user: User): F[Unit] = { - createUserHandler(user) - } + override def createUser(user : User) : F[Unit] = { + createUserHandler(user) + } - override def createUsersWithArrayInput(user: Seq[User]): F[Unit] = { - createUsersWithArrayInputHandler(user) - } + override def createUsersWithArrayInput(user : Seq[User]) : F[Unit] = { + createUsersWithArrayInputHandler(user) + } - override def createUsersWithListInput(user: Seq[User]): F[Unit] = { - createUsersWithListInputHandler(user) - } + override def createUsersWithListInput(user : Seq[User]) : F[Unit] = { + createUsersWithListInputHandler(user) + } - override def deleteUser(username: String): F[Unit] = { - deleteUserHandler(username) - } + override def deleteUser(username : String) : F[Unit] = { + deleteUserHandler(username) + } - override def getUserByName(username: String): F[User] = { - getUserByNameHandler(username) - } + override def getUserByName(username : String) : F[User] = { + getUserByNameHandler(username) + } - override def loginUser(username: String, password: String): F[String] = { - loginUserHandler(username, password) - } + override def loginUser(username : String, password : String) : F[String] = { + loginUserHandler(username, password) + } - override def logoutUser(): F[Unit] = { - logoutUserHandler() - } + override def logoutUser() : F[Unit] = { + logoutUserHandler() + } - override def updateUser(username: String, user: User): F[Unit] = { - updateUserHandler(username, user) - } + override def updateUser(username : String, user : User) : F[Unit] = { + updateUserHandler(username, user) + } } - def apply(): UserService[Try] = UserService.Handler[Try]( - (_) => notImplemented("createUser"), - // override def createUser(user : User) : Unit = ??? - (_) => notImplemented("createUsersWithArrayInput"), - // override def createUsersWithArrayInput(user : Seq[User]) : Unit = ??? - (_) => notImplemented("createUsersWithListInput"), - // override def createUsersWithListInput(user : Seq[User]) : Unit = ??? - (_) => notImplemented("deleteUser"), - // override def deleteUser(username : String) : Unit = ??? - (_) => notImplemented("getUserByName"), - // override def getUserByName(username : String) : User = ??? - (_, _) => notImplemented("loginUser"), - // override def loginUser(username : String, password : String) : String = ??? - () => notImplemented("logoutUser"), - // override def logoutUser() : Unit = ??? - (_, _) => notImplemented("updateUser") - // override def updateUser(username : String, user : User) : Unit = ??? + def apply() : UserService[Try] = UserService.Handler[Try]( + (_) => notImplemented("createUser"), + // override def createUser(user : User) : Unit = ??? + (_) => notImplemented("createUsersWithArrayInput"), + // override def createUsersWithArrayInput(user : Seq[User]) : Unit = ??? + (_) => notImplemented("createUsersWithListInput"), + // override def createUsersWithListInput(user : Seq[User]) : Unit = ??? + (_) => notImplemented("deleteUser"), + // override def deleteUser(username : String) : Unit = ??? + (_) => notImplemented("getUserByName"), + // override def getUserByName(username : String) : User = ??? + (_, _) => notImplemented("loginUser"), + // override def loginUser(username : String, password : String) : String = ??? + () => notImplemented("logoutUser"), + // override def logoutUser() : Unit = ??? + (_, _) => notImplemented("updateUser") + // override def updateUser(username : String, user : User) : Unit = ??? ) - private def notImplemented(name: String) = Failure(new Exception(s"TODO: $name not implemented")) + private def notImplemented(name : String) = Failure(new Exception(s"TODO: $name not implemented")) } -/** The User business-logic - * - * The 'asHandler' will return an implementation which allows for easily overriding individual - * operations. - * - * equally there are "on<Function>" helper methods for easily overriding individual functions - * - * @tparam F - * the effect type (Future, Try, IO, ID, etc) of the operations - */ +/** + * The User business-logic + * + * + * The 'asHandler' will return an implementation which allows for easily overriding individual operations. + * + * equally there are "on<Function>" helper methods for easily overriding individual functions + * + * @tparam F the effect type (Future, Try, IO, ID, etc) of the operations + */ trait UserService[F[_]] { - /** Create user - * - * @return - */ - def createUser(user: User): F[Unit] - - /** override createUser with the given handler - * @return - * a new implementation of UserService[F] with createUser overridden using the given handler - */ - final def onCreateUser(handler: (user: User) => F[Unit]): UserService[F] = { + * + * @return + */ + def createUser(user : User) : F[Unit] + + /** + * override createUser with the given handler + * @return a new implementation of UserService[F] with createUser overridden using the given handler + */ + final def onCreateUser(handler : (user : User) => F[Unit]) : UserService[F] = { asHandler.copy(createUserHandler = handler) } - /** Creates list of users with given input array - * - * @return - */ - def createUsersWithArrayInput(user: Seq[User]): F[Unit] - - /** override createUsersWithArrayInput with the given handler - * @return - * a new implementation of UserService[F] with createUsersWithArrayInput overridden using the - * given handler - */ - final def onCreateUsersWithArrayInput(handler: (user: Seq[User]) => F[Unit]): UserService[F] = { + * + * @return + */ + def createUsersWithArrayInput(user : Seq[User]) : F[Unit] + + /** + * override createUsersWithArrayInput with the given handler + * @return a new implementation of UserService[F] with createUsersWithArrayInput overridden using the given handler + */ + final def onCreateUsersWithArrayInput(handler : (user : Seq[User]) => F[Unit]) : UserService[F] = { asHandler.copy(createUsersWithArrayInputHandler = handler) } - /** Creates list of users with given input array - * - * @return - */ - def createUsersWithListInput(user: Seq[User]): F[Unit] - - /** override createUsersWithListInput with the given handler - * @return - * a new implementation of UserService[F] with createUsersWithListInput overridden using the - * given handler - */ - final def onCreateUsersWithListInput(handler: (user: Seq[User]) => F[Unit]): UserService[F] = { + * + * @return + */ + def createUsersWithListInput(user : Seq[User]) : F[Unit] + + /** + * override createUsersWithListInput with the given handler + * @return a new implementation of UserService[F] with createUsersWithListInput overridden using the given handler + */ + final def onCreateUsersWithListInput(handler : (user : Seq[User]) => F[Unit]) : UserService[F] = { asHandler.copy(createUsersWithListInputHandler = handler) } - /** Delete user - * - * @return - */ - def deleteUser(username: String): F[Unit] - - /** override deleteUser with the given handler - * @return - * a new implementation of UserService[F] with deleteUser overridden using the given handler - */ - final def onDeleteUser(handler: (username: String) => F[Unit]): UserService[F] = { + * + * @return + */ + def deleteUser(username : String) : F[Unit] + + /** + * override deleteUser with the given handler + * @return a new implementation of UserService[F] with deleteUser overridden using the given handler + */ + final def onDeleteUser(handler : (username : String) => F[Unit]) : UserService[F] = { asHandler.copy(deleteUserHandler = handler) } - /** Get user by user name - * - * @return - * User - */ - def getUserByName(username: String): F[User] - - /** override getUserByName with the given handler - * @return - * a new implementation of UserService[F] with getUserByName overridden using the given handler - */ - final def onGetUserByName(handler: (username: String) => F[User]): UserService[F] = { + * + * @return User + */ + def getUserByName(username : String) : F[User] + + /** + * override getUserByName with the given handler + * @return a new implementation of UserService[F] with getUserByName overridden using the given handler + */ + final def onGetUserByName(handler : (username : String) => F[User]) : UserService[F] = { asHandler.copy(getUserByNameHandler = handler) } - /** Logs user into the system - * - * @return - * String - */ - def loginUser(username: String, password: String): F[String] - - /** override loginUser with the given handler - * @return - * a new implementation of UserService[F] with loginUser overridden using the given handler - */ - final def onLoginUser( - handler: (username: String, password: String) => F[String] - ): UserService[F] = { + * + * @return String + */ + def loginUser(username : String, password : String) : F[String] + + /** + * override loginUser with the given handler + * @return a new implementation of UserService[F] with loginUser overridden using the given handler + */ + final def onLoginUser(handler : (username : String, password : String) => F[String]) : UserService[F] = { asHandler.copy(loginUserHandler = handler) } - /** Logs out current logged in user session - * - * @return - */ - def logoutUser(): F[Unit] - - /** override logoutUser with the given handler - * @return - * a new implementation of UserService[F] with logoutUser overridden using the given handler - */ - final def onLogoutUser(handler: () => F[Unit]): UserService[F] = { + * + * @return + */ + def logoutUser() : F[Unit] + + /** + * override logoutUser with the given handler + * @return a new implementation of UserService[F] with logoutUser overridden using the given handler + */ + final def onLogoutUser(handler : () => F[Unit]) : UserService[F] = { asHandler.copy(logoutUserHandler = handler) } - /** Updated user - * - * @return - */ - def updateUser(username: String, user: User): F[Unit] - - /** override updateUser with the given handler - * @return - * a new implementation of UserService[F] with updateUser overridden using the given handler - */ - final def onUpdateUser(handler: (username: String, user: User) => F[Unit]): UserService[F] = { + * + * @return + */ + def updateUser(username : String, user : User) : F[Unit] + + /** + * override updateUser with the given handler + * @return a new implementation of UserService[F] with updateUser overridden using the given handler + */ + final def onUpdateUser(handler : (username : String, user : User) => F[Unit]) : UserService[F] = { asHandler.copy(updateUserHandler = handler) } - /** @return - * a Handler implementation of this service - */ - final def asHandler: UserService.Handler[F] = this match { - case h: UserService.Handler[F] => h - case _ => - UserService.Handler[F]( - (user) => createUser(user), - (user) => createUsersWithArrayInput(user), - (user) => createUsersWithListInput(user), - (username) => deleteUser(username), - (username) => getUserByName(username), - (username, password) => loginUser(username, password), - () => logoutUser(), - (username, user) => updateUser(username, user) - ) + /** + * @return a Handler implementation of this service + */ + final def asHandler : UserService.Handler[F] = this match { + case h : UserService.Handler[F] => h + case _ => + UserService.Handler[F]( + (user) => createUser(user), + (user) => createUsersWithArrayInput(user), + (user) => createUsersWithListInput(user), + (username) => deleteUser(username), + (username) => getUserByName(username), + (username, password) => loginUser(username, password), + () => logoutUser(), + (username, user) => updateUser(username, user) + ) } - /** This function will change the effect type of this service. - * - * It's not unlike a typical map operation from A => B, except we're not mapping a type from A to - * B, but rather from F[A] => G[A] using the 'changeEffect' function. - * - * For, this could turn an asynchronous service (one which returns Future[_] types) into a - * synchronous one (one which returns Try[_] types) by awaiting on the Future. - * - * It could change an IO type (like cats effect or ZIO) into an ID[A] which is just: - * ``` - * type ID[A] => A - * ``` - * - * @tparam G - * the new "polymorphic" effect type - * @param changeEffect - * the "natural transformation" which can change one effect type into another - * @return - * a new UserService service implementation with effect type [G] - */ - final def mapEffect[G[_]](changeEffect: [A] => F[A] => G[A]): UserService[G] = { + /** + * This function will change the effect type of this service. + * + * It's not unlike a typical map operation from A => B, except we're not mapping + * a type from A to B, but rather from F[A] => G[A] using the 'changeEffect' function. + * + * For, this could turn an asynchronous service (one which returns Future[_] types) into + * a synchronous one (one which returns Try[_] types) by awaiting on the Future. + * + * It could change an IO type (like cats effect or ZIO) into an ID[A] which is just: + * ``` + * type ID[A] => A + * ``` + * + * @tparam G the new "polymorphic" effect type + * @param changeEffect the "natural transformation" which can change one effect type into another + * @return a new UserService service implementation with effect type [G] + */ + final def mapEffect[G[_]](changeEffect : [A] => F[A] => G[A]) : UserService[G] = { val self = this new UserService[G] { - override def createUser(user: User): G[Unit] = changeEffect { - self.createUser(user) - } - override def createUsersWithArrayInput(user: Seq[User]): G[Unit] = changeEffect { - self.createUsersWithArrayInput(user) - } - override def createUsersWithListInput(user: Seq[User]): G[Unit] = changeEffect { - self.createUsersWithListInput(user) - } - override def deleteUser(username: String): G[Unit] = changeEffect { - self.deleteUser(username) - } - override def getUserByName(username: String): G[User] = changeEffect { - self.getUserByName(username) - } - override def loginUser(username: String, password: String): G[String] = changeEffect { - self.loginUser(username, password) - } - override def logoutUser(): G[Unit] = changeEffect { - self.logoutUser() - } - override def updateUser(username: String, user: User): G[Unit] = changeEffect { - self.updateUser(username, user) - } + override def createUser(user : User) : G[Unit] = changeEffect { + self.createUser(user) + } + override def createUsersWithArrayInput(user : Seq[User]) : G[Unit] = changeEffect { + self.createUsersWithArrayInput(user) + } + override def createUsersWithListInput(user : Seq[User]) : G[Unit] = changeEffect { + self.createUsersWithListInput(user) + } + override def deleteUser(username : String) : G[Unit] = changeEffect { + self.deleteUser(username) + } + override def getUserByName(username : String) : G[User] = changeEffect { + self.getUserByName(username) + } + override def loginUser(username : String, password : String) : G[String] = changeEffect { + self.loginUser(username, password) + } + override def logoutUser() : G[Unit] = changeEffect { + self.logoutUser() + } + override def updateUser(username : String, user : User) : G[Unit] = changeEffect { + self.updateUser(username, user) + } } } } diff --git a/samples/server/petstore/scala-cask/shared/src/main/scala/sample/cask/model/ApiResponse.scala b/samples/server/petstore/scala-cask/shared/src/main/scala/sample/cask/model/ApiResponse.scala index 54c6cd55d459..52aa5bcf9c06 100644 --- a/samples/server/petstore/scala-cask/shared/src/main/scala/sample/cask/model/ApiResponse.scala +++ b/samples/server/petstore/scala-cask/shared/src/main/scala/sample/cask/model/ApiResponse.scala @@ -1,14 +1,15 @@ -/** OpenAPI Petstore This is a sample server Petstore server. For this sample, you can use the api - * key `special-key` to test the authorization filters. - * - * OpenAPI spec version: 1.0.0 - * - * Contact: team@openapitools.org - * - * NOTE: This class is auto generated by OpenAPI Generator. - * - * https://openapi-generator.tech - */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator. + * + * https://openapi-generator.tech + */ // this model was generated using model.mustache package sample.cask.model @@ -19,33 +20,38 @@ import scala.util.control.NonFatal import upickle.default.{ReadWriter => RW, macroRW} import upickle.default.* + + case class ApiResponse( - code: Option[Int] = None, - `type`: Option[String] = None, - message: Option[String] = None + code: Option[Int] = None , + `type`: Option[String] = None , + message: Option[String] = None + + ) { - def asJsonString: String = asData.asJsonString - def asJson: ujson.Value = asData.asJson +def asJsonString: String = asData.asJsonString +def asJson: ujson.Value = asData.asJson - def asData: ApiResponseData = { - ApiResponseData( - code = code.getOrElse(0) /* 1 */, - `type` = `type`.getOrElse("") /* 1 */, - message = message.getOrElse("") /* 1 */ +def asData : ApiResponseData = { +ApiResponseData( + code = code.getOrElse(0) /* 1 */ , + `type` = `type`.getOrElse("") /* 1 */ , + message = message.getOrElse("") /* 1 */ - ) - } +) +} } object ApiResponse { - given RW[ApiResponse] = summon[RW[ujson.Value]] - .bimap[ApiResponse](_.asJson, json => read[ApiResponseData](json).asModel) +given RW[ApiResponse] = summon[RW[ujson.Value]].bimap[ApiResponse](_.asJson, json => read[ApiResponseData](json).asModel) - enum Fields(val fieldName: String) extends Field(fieldName) { - case code extends Fields("code") - case `type` extends Fields("`type`") +enum Fields(val fieldName : String) extends Field(fieldName) { + case code extends Fields("code") + case `type` extends Fields("`type`") case message extends Fields("message") - } +} + } + diff --git a/samples/server/petstore/scala-cask/shared/src/main/scala/sample/cask/model/ApiResponseData.scala b/samples/server/petstore/scala-cask/shared/src/main/scala/sample/cask/model/ApiResponseData.scala index 2968184ac9ee..595cec5f7200 100644 --- a/samples/server/petstore/scala-cask/shared/src/main/scala/sample/cask/model/ApiResponseData.scala +++ b/samples/server/petstore/scala-cask/shared/src/main/scala/sample/cask/model/ApiResponseData.scala @@ -1,14 +1,15 @@ -/** OpenAPI Petstore This is a sample server Petstore server. For this sample, you can use the api - * key `special-key` to test the authorization filters. - * - * OpenAPI spec version: 1.0.0 - * - * Contact: team@openapitools.org - * - * NOTE: This class is auto generated by OpenAPI Generator. - * - * https://openapi-generator.tech - */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator. + * + * https://openapi-generator.tech + */ // this model was generated using modelData.mustache package sample.cask.model @@ -19,116 +20,124 @@ import scala.util.* import upickle.default.{ReadWriter => RW, macroRW} import upickle.default.* -/** ApiResponseData a data transfer object, primarily for simple json serialisation. It has no - * validation - there may be nulls, values out of range, etc + + /** ApiResponseData a data transfer object, primarily for simple json serialisation. + * It has no validation - there may be nulls, values out of range, etc */ case class ApiResponseData( - code: Int = 0, - `type`: String = "", - message: String = "" + code: Int = 0 , + `type`: String = "" , + message: String = "" + + ) derives RW { def asJsonString: String = asJson.toString() - def asJson: ujson.Value = { + def asJson : ujson.Value = { val jason = writeJs(this) jason } - def validationErrors(path: Seq[Field], failFast: Boolean): Seq[ValidationError] = { + def validationErrors(path : Seq[Field], failFast : Boolean) : Seq[ValidationError] = { val errors = scala.collection.mutable.ListBuffer[ValidationError]() - // ================== code validation ================== - - // ================== `type` validation ================== - - // ================== message validation ================== + // ================== code validation ================== + + + + + + // ================== `type` validation ================== + + + + + + // ================== message validation ================== + + + + errors.toSeq } - /** @return - * the validated model within a Try (if successful) - */ - def validated(failFast: Boolean = false): scala.util.Try[ApiResponse] = { + /** + * @return the validated model within a Try (if successful) + */ + def validated(failFast : Boolean = false) : scala.util.Try[ApiResponse] = { validationErrors(Vector(), failFast) match { - case Seq() => Success(asModel) + case Seq() => Success(asModel) case first +: theRest => Failure(ValidationErrors(first, theRest)) } } /** use 'validated' to check validation */ - def asModel: ApiResponse = { + def asModel : ApiResponse = { ApiResponse( - code = Option(code) /* one */, - `type` = Option(`type`) /* one */, - message = Option(message) /* one */ - + code = Option(code) /* one */ , + `type` = Option(`type`) /* one */ , + message = Option(message) /* one */ + ) } } object ApiResponseData { - def fromJson(jason: ujson.Value): ApiResponseData = try { - val data = read[ApiResponseData](jason) - data - } catch { - case NonFatal(e) => sys.error(s"Error creating ApiResponseData from json '$jason': $e") + def fromJson(jason : ujson.Value) : ApiResponseData = try { + val data = read[ApiResponseData](jason) + data + } catch { + case NonFatal(e) => sys.error(s"Error creating ApiResponseData from json '$jason': $e") } - def fromJsonString(jason: String): ApiResponseData = { - val parsed = - try { - read[ujson.Value](jason) - } catch { - case NonFatal(e) => sys.error(s"Error parsing json '$jason': $e") - } - fromJson(parsed) + def fromJsonString(jason : String) : ApiResponseData = { + val parsed = try { + read[ujson.Value](jason) + } catch { + case NonFatal(e) => sys.error(s"Error parsing json '$jason': $e") + } + fromJson(parsed) } - def manyFromJsonString(jason: String): Seq[ApiResponseData] = try { - read[List[ApiResponseData]](jason) - } catch { - case NonFatal(e) => sys.error(s"Error parsing json '$jason' as list: $e") - } + def manyFromJsonString(jason : String) : Seq[ApiResponseData] = try { + read[List[ApiResponseData]](jason) + } catch { + case NonFatal(e) => sys.error(s"Error parsing json '$jason' as list: $e") + } - def manyFromJsonStringValidated( - jason: String, - failFast: Boolean = false - ): Try[Seq[ApiResponse]] = { - Try(manyFromJsonString(jason)).flatMap { list => - list.zipWithIndex.foldLeft(Try(Vector[ApiResponse]())) { - case (Success(list), (next, i)) => - next.validated(failFast) match { - case Success(ok) => Success(list :+ ok) - case Failure(err) => - Failure(new Exception(s"Validation error on element $i: ${err.getMessage}", err)) - } - case (fail, _) => fail + def manyFromJsonStringValidated(jason : String, failFast : Boolean = false) : Try[Seq[ApiResponse]] = { + Try(manyFromJsonString(jason)).flatMap { list => + list.zipWithIndex.foldLeft(Try(Vector[ApiResponse]())) { + case (Success(list), (next, i)) => + next.validated(failFast) match { + case Success(ok) => Success(list :+ ok) + case Failure(err) => Failure(new Exception(s"Validation error on element $i: ${err.getMessage}", err)) + } + case (fail, _) => fail + } } } - } - - def mapFromJsonString(jason: String): Map[String, ApiResponseData] = try { - read[Map[String, ApiResponseData]](jason) - } catch { - case NonFatal(e) => sys.error(s"Error parsing json '$jason' as map: $e") - } - def mapFromJsonStringValidated( - jason: String, - failFast: Boolean = false - ): Try[Map[String, ApiResponse]] = { - Try(mapFromJsonString(jason)).flatMap { map => - map.foldLeft(Try(Map[String, ApiResponse]())) { - case (Success(map), (key, next)) => - next.validated(failFast) match { - case Success(ok) => Success(map.updated(key, ok)) - case Failure(err) => - Failure(new Exception(s"Validation error on element $key: ${err.getMessage}", err)) - } - case (fail, _) => fail - } + def mapFromJsonString(jason : String) : Map[String, ApiResponseData] = try { + read[Map[String, ApiResponseData]](jason) + } catch { + case NonFatal(e) => sys.error(s"Error parsing json '$jason' as map: $e") } + + + def mapFromJsonStringValidated(jason : String, failFast : Boolean = false) : Try[Map[String, ApiResponse]] = { + Try(mapFromJsonString(jason)).flatMap { map => + map.foldLeft(Try(Map[String, ApiResponse]())) { + case (Success(map), (key, next)) => + next.validated(failFast) match { + case Success(ok) => Success(map.updated(key, ok)) + case Failure(err) => Failure(new Exception(s"Validation error on element $key: ${err.getMessage}", err)) + } + case (fail, _) => fail + } + } } } + diff --git a/samples/server/petstore/scala-cask/shared/src/main/scala/sample/cask/model/Category.scala b/samples/server/petstore/scala-cask/shared/src/main/scala/sample/cask/model/Category.scala index 1d0d722613db..4a145127bb3e 100644 --- a/samples/server/petstore/scala-cask/shared/src/main/scala/sample/cask/model/Category.scala +++ b/samples/server/petstore/scala-cask/shared/src/main/scala/sample/cask/model/Category.scala @@ -1,14 +1,15 @@ -/** OpenAPI Petstore This is a sample server Petstore server. For this sample, you can use the api - * key `special-key` to test the authorization filters. - * - * OpenAPI spec version: 1.0.0 - * - * Contact: team@openapitools.org - * - * NOTE: This class is auto generated by OpenAPI Generator. - * - * https://openapi-generator.tech - */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator. + * + * https://openapi-generator.tech + */ // this model was generated using model.mustache package sample.cask.model @@ -19,30 +20,35 @@ import scala.util.control.NonFatal import upickle.default.{ReadWriter => RW, macroRW} import upickle.default.* + + case class Category( - id: Option[Long] = None, - name: Option[String] = None + id: Option[Long] = None , + name: Option[String] = None + + ) { - def asJsonString: String = asData.asJsonString - def asJson: ujson.Value = asData.asJson +def asJsonString: String = asData.asJsonString +def asJson: ujson.Value = asData.asJson - def asData: CategoryData = { - CategoryData( - id = id.getOrElse(0) /* 1 */, - name = name.getOrElse("") /* 1 */ +def asData : CategoryData = { +CategoryData( + id = id.getOrElse(0) /* 1 */ , + name = name.getOrElse("") /* 1 */ - ) - } +) +} } object Category { - given RW[Category] = - summon[RW[ujson.Value]].bimap[Category](_.asJson, json => read[CategoryData](json).asModel) +given RW[Category] = summon[RW[ujson.Value]].bimap[Category](_.asJson, json => read[CategoryData](json).asModel) - enum Fields(val fieldName: String) extends Field(fieldName) { - case id extends Fields("id") +enum Fields(val fieldName : String) extends Field(fieldName) { + case id extends Fields("id") case name extends Fields("name") - } +} + } + diff --git a/samples/server/petstore/scala-cask/shared/src/main/scala/sample/cask/model/CategoryData.scala b/samples/server/petstore/scala-cask/shared/src/main/scala/sample/cask/model/CategoryData.scala index 19db07d0885a..870f035ba22d 100644 --- a/samples/server/petstore/scala-cask/shared/src/main/scala/sample/cask/model/CategoryData.scala +++ b/samples/server/petstore/scala-cask/shared/src/main/scala/sample/cask/model/CategoryData.scala @@ -1,14 +1,15 @@ -/** OpenAPI Petstore This is a sample server Petstore server. For this sample, you can use the api - * key `special-key` to test the authorization filters. - * - * OpenAPI spec version: 1.0.0 - * - * Contact: team@openapitools.org - * - * NOTE: This class is auto generated by OpenAPI Generator. - * - * https://openapi-generator.tech - */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator. + * + * https://openapi-generator.tech + */ // this model was generated using modelData.mustache package sample.cask.model @@ -19,118 +20,122 @@ import scala.util.* import upickle.default.{ReadWriter => RW, macroRW} import upickle.default.* -/** CategoryData a data transfer object, primarily for simple json serialisation. It has no - * validation - there may be nulls, values out of range, etc + + /** CategoryData a data transfer object, primarily for simple json serialisation. + * It has no validation - there may be nulls, values out of range, etc */ case class CategoryData( - id: Long = 0, - name: String = "" + id: Long = 0 , + name: String = "" + + ) derives RW { def asJsonString: String = asJson.toString() - def asJson: ujson.Value = { + def asJson : ujson.Value = { val jason = writeJs(this) jason } - def validationErrors(path: Seq[Field], failFast: Boolean): Seq[ValidationError] = { + def validationErrors(path : Seq[Field], failFast : Boolean) : Seq[ValidationError] = { val errors = scala.collection.mutable.ListBuffer[ValidationError]() - // ================== id validation ================== - - // ================== name validation ================== - // validate against pattern '^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$' - if (errors.isEmpty || !failFast) { - val regex = """^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$""" - if name == null || !regex.r.matches(name) then - errors += ValidationError( - path :+ Category.Fields.name, - s"value '$name' doesn't match pattern $regex" - ) - } + // ================== id validation ================== + + + + + + // ================== name validation ================== + // validate against pattern '^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$' + if (errors.isEmpty || !failFast) { + val regex = """^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$""" + if name == null || !regex.r.matches(name) then + errors += ValidationError(path :+ Category.Fields.name, s"value '$name' doesn't match pattern $regex") + } + + + + errors.toSeq } - /** @return - * the validated model within a Try (if successful) - */ - def validated(failFast: Boolean = false): scala.util.Try[Category] = { + /** + * @return the validated model within a Try (if successful) + */ + def validated(failFast : Boolean = false) : scala.util.Try[Category] = { validationErrors(Vector(), failFast) match { - case Seq() => Success(asModel) + case Seq() => Success(asModel) case first +: theRest => Failure(ValidationErrors(first, theRest)) } } /** use 'validated' to check validation */ - def asModel: Category = { + def asModel : Category = { Category( - id = Option(id) /* one */, - name = Option(name) /* one */ - + id = Option(id) /* one */ , + name = Option(name) /* one */ + ) } } object CategoryData { - def fromJson(jason: ujson.Value): CategoryData = try { - val data = read[CategoryData](jason) - data - } catch { - case NonFatal(e) => sys.error(s"Error creating CategoryData from json '$jason': $e") + def fromJson(jason : ujson.Value) : CategoryData = try { + val data = read[CategoryData](jason) + data + } catch { + case NonFatal(e) => sys.error(s"Error creating CategoryData from json '$jason': $e") } - def fromJsonString(jason: String): CategoryData = { - val parsed = - try { - read[ujson.Value](jason) - } catch { - case NonFatal(e) => sys.error(s"Error parsing json '$jason': $e") - } - fromJson(parsed) + def fromJsonString(jason : String) : CategoryData = { + val parsed = try { + read[ujson.Value](jason) + } catch { + case NonFatal(e) => sys.error(s"Error parsing json '$jason': $e") + } + fromJson(parsed) } - def manyFromJsonString(jason: String): Seq[CategoryData] = try { - read[List[CategoryData]](jason) - } catch { - case NonFatal(e) => sys.error(s"Error parsing json '$jason' as list: $e") - } + def manyFromJsonString(jason : String) : Seq[CategoryData] = try { + read[List[CategoryData]](jason) + } catch { + case NonFatal(e) => sys.error(s"Error parsing json '$jason' as list: $e") + } - def manyFromJsonStringValidated(jason: String, failFast: Boolean = false): Try[Seq[Category]] = { - Try(manyFromJsonString(jason)).flatMap { list => - list.zipWithIndex.foldLeft(Try(Vector[Category]())) { - case (Success(list), (next, i)) => - next.validated(failFast) match { - case Success(ok) => Success(list :+ ok) - case Failure(err) => - Failure(new Exception(s"Validation error on element $i: ${err.getMessage}", err)) - } - case (fail, _) => fail + def manyFromJsonStringValidated(jason : String, failFast : Boolean = false) : Try[Seq[Category]] = { + Try(manyFromJsonString(jason)).flatMap { list => + list.zipWithIndex.foldLeft(Try(Vector[Category]())) { + case (Success(list), (next, i)) => + next.validated(failFast) match { + case Success(ok) => Success(list :+ ok) + case Failure(err) => Failure(new Exception(s"Validation error on element $i: ${err.getMessage}", err)) + } + case (fail, _) => fail + } } } - } - - def mapFromJsonString(jason: String): Map[String, CategoryData] = try { - read[Map[String, CategoryData]](jason) - } catch { - case NonFatal(e) => sys.error(s"Error parsing json '$jason' as map: $e") - } - def mapFromJsonStringValidated( - jason: String, - failFast: Boolean = false - ): Try[Map[String, Category]] = { - Try(mapFromJsonString(jason)).flatMap { map => - map.foldLeft(Try(Map[String, Category]())) { - case (Success(map), (key, next)) => - next.validated(failFast) match { - case Success(ok) => Success(map.updated(key, ok)) - case Failure(err) => - Failure(new Exception(s"Validation error on element $key: ${err.getMessage}", err)) - } - case (fail, _) => fail - } + def mapFromJsonString(jason : String) : Map[String, CategoryData] = try { + read[Map[String, CategoryData]](jason) + } catch { + case NonFatal(e) => sys.error(s"Error parsing json '$jason' as map: $e") } + + + def mapFromJsonStringValidated(jason : String, failFast : Boolean = false) : Try[Map[String, Category]] = { + Try(mapFromJsonString(jason)).flatMap { map => + map.foldLeft(Try(Map[String, Category]())) { + case (Success(map), (key, next)) => + next.validated(failFast) match { + case Success(ok) => Success(map.updated(key, ok)) + case Failure(err) => Failure(new Exception(s"Validation error on element $key: ${err.getMessage}", err)) + } + case (fail, _) => fail + } + } } } + diff --git a/samples/server/petstore/scala-cask/shared/src/main/scala/sample/cask/model/Order.scala b/samples/server/petstore/scala-cask/shared/src/main/scala/sample/cask/model/Order.scala index de1a479e2d9a..52ee833b2a3a 100644 --- a/samples/server/petstore/scala-cask/shared/src/main/scala/sample/cask/model/Order.scala +++ b/samples/server/petstore/scala-cask/shared/src/main/scala/sample/cask/model/Order.scala @@ -1,14 +1,15 @@ -/** OpenAPI Petstore This is a sample server Petstore server. For this sample, you can use the api - * key `special-key` to test the authorization filters. - * - * OpenAPI spec version: 1.0.0 - * - * Contact: team@openapitools.org - * - * NOTE: This class is auto generated by OpenAPI Generator. - * - * https://openapi-generator.tech - */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator. + * + * https://openapi-generator.tech + */ // this model was generated using model.mustache package sample.cask.model @@ -20,51 +21,55 @@ import scala.util.control.NonFatal import upickle.default.{ReadWriter => RW, macroRW} import upickle.default.* + + case class Order( - id: Option[Long] = None, - petId: Option[Long] = None, - quantity: Option[Int] = None, - shipDate: Option[OffsetDateTime] = None, - /* Order Status */ - status: Option[Order.StatusEnum] = None, - complete: Option[Boolean] = None + id: Option[Long] = None , + petId: Option[Long] = None , + quantity: Option[Int] = None , + shipDate: Option[OffsetDateTime] = None , + /* Order Status */ + status: Option[Order.StatusEnum] = None , + complete: Option[Boolean] = None + + ) { - def asJsonString: String = asData.asJsonString - def asJson: ujson.Value = asData.asJson +def asJsonString: String = asData.asJsonString +def asJson: ujson.Value = asData.asJson - def asData: OrderData = { - OrderData( - id = id.getOrElse(0) /* 1 */, - petId = petId.getOrElse(0) /* 1 */, - quantity = quantity.getOrElse(0) /* 1 */, - shipDate = shipDate.getOrElse(null) /* 1 */, - status = status.getOrElse(null) /* 1 */, - complete = complete.getOrElse(false) /* 1 */ +def asData : OrderData = { +OrderData( + id = id.getOrElse(0) /* 1 */ , + petId = petId.getOrElse(0) /* 1 */ , + quantity = quantity.getOrElse(0) /* 1 */ , + shipDate = shipDate.getOrElse(null) /* 1 */ , + status = status.getOrElse(null) /* 1 */ , + complete = complete.getOrElse(false) /* 1 */ - ) - } +) +} } object Order { - given RW[Order] = - summon[RW[ujson.Value]].bimap[Order](_.asJson, json => read[OrderData](json).asModel) +given RW[Order] = summon[RW[ujson.Value]].bimap[Order](_.asJson, json => read[OrderData](json).asModel) - enum Fields(val fieldName: String) extends Field(fieldName) { - case id extends Fields("id") - case petId extends Fields("petId") +enum Fields(val fieldName : String) extends Field(fieldName) { + case id extends Fields("id") + case petId extends Fields("petId") case quantity extends Fields("quantity") case shipDate extends Fields("shipDate") - case status extends Fields("status") + case status extends Fields("status") case complete extends Fields("complete") - } +} - // baseName=status - // nameInCamelCase = status - enum StatusEnum derives ReadWriter { - case placed - case approved - case delivered - } + // baseName=status + // nameInCamelCase = status + enum StatusEnum derives ReadWriter { + case placed + case approved + case delivered + } } + diff --git a/samples/server/petstore/scala-cask/shared/src/main/scala/sample/cask/model/OrderData.scala b/samples/server/petstore/scala-cask/shared/src/main/scala/sample/cask/model/OrderData.scala index 19f702d132b0..ef46c9615b52 100644 --- a/samples/server/petstore/scala-cask/shared/src/main/scala/sample/cask/model/OrderData.scala +++ b/samples/server/petstore/scala-cask/shared/src/main/scala/sample/cask/model/OrderData.scala @@ -1,14 +1,15 @@ -/** OpenAPI Petstore This is a sample server Petstore server. For this sample, you can use the api - * key `special-key` to test the authorization filters. - * - * OpenAPI spec version: 1.0.0 - * - * Contact: team@openapitools.org - * - * NOTE: This class is auto generated by OpenAPI Generator. - * - * https://openapi-generator.tech - */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator. + * + * https://openapi-generator.tech + */ // this model was generated using modelData.mustache package sample.cask.model @@ -20,126 +21,149 @@ import scala.util.* import upickle.default.{ReadWriter => RW, macroRW} import upickle.default.* -/** OrderData a data transfer object, primarily for simple json serialisation. It has no validation - * \- there may be nulls, values out of range, etc + + /** OrderData a data transfer object, primarily for simple json serialisation. + * It has no validation - there may be nulls, values out of range, etc */ case class OrderData( - id: Long = 0, - petId: Long = 0, - quantity: Int = 0, - shipDate: OffsetDateTime = null, - /* Order Status */ - status: Order.StatusEnum = null, - complete: Boolean = false + id: Long = 0 , + petId: Long = 0 , + quantity: Int = 0 , + shipDate: OffsetDateTime = null , +/* Order Status */ + status: Order.StatusEnum = null , + complete: Boolean = false + + ) derives RW { def asJsonString: String = asJson.toString() - def asJson: ujson.Value = { + def asJson : ujson.Value = { val jason = writeJs(this) jason } - def validationErrors(path: Seq[Field], failFast: Boolean): Seq[ValidationError] = { + def validationErrors(path : Seq[Field], failFast : Boolean) : Seq[ValidationError] = { val errors = scala.collection.mutable.ListBuffer[ValidationError]() - // ================== id validation ================== - - // ================== petId validation ================== - - // ================== quantity validation ================== - - // ================== shipDate validation ================== - - // ================== status validation ================== - - // ================== complete validation ================== + // ================== id validation ================== + + + + + + // ================== petId validation ================== + + + + + + // ================== quantity validation ================== + + + + + + // ================== shipDate validation ================== + + + + + + // ================== status validation ================== + + + + + + // ================== complete validation ================== + + + + errors.toSeq } - /** @return - * the validated model within a Try (if successful) - */ - def validated(failFast: Boolean = false): scala.util.Try[Order] = { + /** + * @return the validated model within a Try (if successful) + */ + def validated(failFast : Boolean = false) : scala.util.Try[Order] = { validationErrors(Vector(), failFast) match { - case Seq() => Success(asModel) + case Seq() => Success(asModel) case first +: theRest => Failure(ValidationErrors(first, theRest)) } } /** use 'validated' to check validation */ - def asModel: Order = { + def asModel : Order = { Order( - id = Option(id) /* one */, - petId = Option(petId) /* one */, - quantity = Option(quantity) /* one */, - shipDate = Option(shipDate) /* one */, - status = Option(status) /* one */, - complete = Option(complete) /* one */ - + id = Option(id) /* one */ , + petId = Option(petId) /* one */ , + quantity = Option(quantity) /* one */ , + shipDate = Option(shipDate) /* one */ , + status = Option(status) /* one */ , + complete = Option(complete) /* one */ + ) } } object OrderData { - def fromJson(jason: ujson.Value): OrderData = try { - val data = read[OrderData](jason) - data - } catch { - case NonFatal(e) => sys.error(s"Error creating OrderData from json '$jason': $e") + def fromJson(jason : ujson.Value) : OrderData = try { + val data = read[OrderData](jason) + data + } catch { + case NonFatal(e) => sys.error(s"Error creating OrderData from json '$jason': $e") } - def fromJsonString(jason: String): OrderData = { - val parsed = - try { - read[ujson.Value](jason) - } catch { - case NonFatal(e) => sys.error(s"Error parsing json '$jason': $e") - } - fromJson(parsed) + def fromJsonString(jason : String) : OrderData = { + val parsed = try { + read[ujson.Value](jason) + } catch { + case NonFatal(e) => sys.error(s"Error parsing json '$jason': $e") + } + fromJson(parsed) } - def manyFromJsonString(jason: String): Seq[OrderData] = try { - read[List[OrderData]](jason) - } catch { - case NonFatal(e) => sys.error(s"Error parsing json '$jason' as list: $e") - } + def manyFromJsonString(jason : String) : Seq[OrderData] = try { + read[List[OrderData]](jason) + } catch { + case NonFatal(e) => sys.error(s"Error parsing json '$jason' as list: $e") + } - def manyFromJsonStringValidated(jason: String, failFast: Boolean = false): Try[Seq[Order]] = { - Try(manyFromJsonString(jason)).flatMap { list => - list.zipWithIndex.foldLeft(Try(Vector[Order]())) { - case (Success(list), (next, i)) => - next.validated(failFast) match { - case Success(ok) => Success(list :+ ok) - case Failure(err) => - Failure(new Exception(s"Validation error on element $i: ${err.getMessage}", err)) - } - case (fail, _) => fail + def manyFromJsonStringValidated(jason : String, failFast : Boolean = false) : Try[Seq[Order]] = { + Try(manyFromJsonString(jason)).flatMap { list => + list.zipWithIndex.foldLeft(Try(Vector[Order]())) { + case (Success(list), (next, i)) => + next.validated(failFast) match { + case Success(ok) => Success(list :+ ok) + case Failure(err) => Failure(new Exception(s"Validation error on element $i: ${err.getMessage}", err)) + } + case (fail, _) => fail + } } } - } - - def mapFromJsonString(jason: String): Map[String, OrderData] = try { - read[Map[String, OrderData]](jason) - } catch { - case NonFatal(e) => sys.error(s"Error parsing json '$jason' as map: $e") - } - def mapFromJsonStringValidated( - jason: String, - failFast: Boolean = false - ): Try[Map[String, Order]] = { - Try(mapFromJsonString(jason)).flatMap { map => - map.foldLeft(Try(Map[String, Order]())) { - case (Success(map), (key, next)) => - next.validated(failFast) match { - case Success(ok) => Success(map.updated(key, ok)) - case Failure(err) => - Failure(new Exception(s"Validation error on element $key: ${err.getMessage}", err)) - } - case (fail, _) => fail - } + def mapFromJsonString(jason : String) : Map[String, OrderData] = try { + read[Map[String, OrderData]](jason) + } catch { + case NonFatal(e) => sys.error(s"Error parsing json '$jason' as map: $e") } + + + def mapFromJsonStringValidated(jason : String, failFast : Boolean = false) : Try[Map[String, Order]] = { + Try(mapFromJsonString(jason)).flatMap { map => + map.foldLeft(Try(Map[String, Order]())) { + case (Success(map), (key, next)) => + next.validated(failFast) match { + case Success(ok) => Success(map.updated(key, ok)) + case Failure(err) => Failure(new Exception(s"Validation error on element $key: ${err.getMessage}", err)) + } + case (fail, _) => fail + } + } } } + diff --git a/samples/server/petstore/scala-cask/shared/src/main/scala/sample/cask/model/Pet.scala b/samples/server/petstore/scala-cask/shared/src/main/scala/sample/cask/model/Pet.scala index 3e2c6b2b7aa1..ac60ad7b18ab 100644 --- a/samples/server/petstore/scala-cask/shared/src/main/scala/sample/cask/model/Pet.scala +++ b/samples/server/petstore/scala-cask/shared/src/main/scala/sample/cask/model/Pet.scala @@ -1,14 +1,15 @@ -/** OpenAPI Petstore This is a sample server Petstore server. For this sample, you can use the api - * key `special-key` to test the authorization filters. - * - * OpenAPI spec version: 1.0.0 - * - * Contact: team@openapitools.org - * - * NOTE: This class is auto generated by OpenAPI Generator. - * - * https://openapi-generator.tech - */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator. + * + * https://openapi-generator.tech + */ // this model was generated using model.mustache package sample.cask.model @@ -19,50 +20,55 @@ import scala.util.control.NonFatal import upickle.default.{ReadWriter => RW, macroRW} import upickle.default.* + + case class Pet( - id: Option[Long] = None, - category: Option[Category] = None, + id: Option[Long] = None , + category: Option[Category] = None , name: String, photoUrls: Seq[String], - tags: Seq[Tag] = Nil, - /* pet status in the store */ - status: Option[Pet.StatusEnum] = None + tags: Seq[Tag] = Nil , + /* pet status in the store */ + status: Option[Pet.StatusEnum] = None + + ) { - def asJsonString: String = asData.asJsonString - def asJson: ujson.Value = asData.asJson +def asJsonString: String = asData.asJsonString +def asJson: ujson.Value = asData.asJson - def asData: PetData = { - PetData( - id = id.getOrElse(0) /* 1 */, - category = category.map(_.asData).getOrElse(null) /* 3.2 */, - name = name /* 2 */, - photoUrls = photoUrls /* 2 */, - tags = tags.map(_.asData) /* 4.2 */, - status = status.getOrElse(null) /* 1 */ +def asData : PetData = { +PetData( + id = id.getOrElse(0) /* 1 */ , + category = category.map(_.asData).getOrElse(null) /* 3.2 */ , + name = name /* 2 */ , + photoUrls = photoUrls /* 2 */ , + tags = tags.map(_.asData) /* 4.2 */ , + status = status.getOrElse(null) /* 1 */ - ) - } +) +} } object Pet { - given RW[Pet] = summon[RW[ujson.Value]].bimap[Pet](_.asJson, json => read[PetData](json).asModel) +given RW[Pet] = summon[RW[ujson.Value]].bimap[Pet](_.asJson, json => read[PetData](json).asModel) - enum Fields(val fieldName: String) extends Field(fieldName) { - case id extends Fields("id") - case category extends Fields("category") - case name extends Fields("name") +enum Fields(val fieldName : String) extends Field(fieldName) { + case id extends Fields("id") + case category extends Fields("category") + case name extends Fields("name") case photoUrls extends Fields("photoUrls") - case tags extends Fields("tags") - case status extends Fields("status") - } - - // baseName=status - // nameInCamelCase = status - enum StatusEnum derives ReadWriter { - case available - case pending - case sold - } + case tags extends Fields("tags") + case status extends Fields("status") +} + + // baseName=status + // nameInCamelCase = status + enum StatusEnum derives ReadWriter { + case available + case pending + case sold + } } + diff --git a/samples/server/petstore/scala-cask/shared/src/main/scala/sample/cask/model/PetData.scala b/samples/server/petstore/scala-cask/shared/src/main/scala/sample/cask/model/PetData.scala index d6257caf4aa0..a33ab2947f5c 100644 --- a/samples/server/petstore/scala-cask/shared/src/main/scala/sample/cask/model/PetData.scala +++ b/samples/server/petstore/scala-cask/shared/src/main/scala/sample/cask/model/PetData.scala @@ -1,14 +1,15 @@ -/** OpenAPI Petstore This is a sample server Petstore server. For this sample, you can use the api - * key `special-key` to test the authorization filters. - * - * OpenAPI spec version: 1.0.0 - * - * Contact: team@openapitools.org - * - * NOTE: This class is auto generated by OpenAPI Generator. - * - * https://openapi-generator.tech - */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator. + * + * https://openapi-generator.tech + */ // this model was generated using modelData.mustache package sample.cask.model @@ -19,145 +20,165 @@ import scala.util.* import upickle.default.{ReadWriter => RW, macroRW} import upickle.default.* -/** PetData a data transfer object, primarily for simple json serialisation. It has no validation - - * there may be nulls, values out of range, etc + + /** PetData a data transfer object, primarily for simple json serialisation. + * It has no validation - there may be nulls, values out of range, etc */ case class PetData( - id: Long = 0, - category: CategoryData = null, - name: String, - photoUrls: Seq[String], - tags: Seq[TagData] = Nil, - /* pet status in the store */ - status: Pet.StatusEnum = null + id: Long = 0 , + category: CategoryData = null , + name: String, + photoUrls: Seq[String], + tags: Seq[TagData] = Nil , +/* pet status in the store */ + status: Pet.StatusEnum = null + + ) derives RW { def asJsonString: String = asJson.toString() - def asJson: ujson.Value = { + def asJson : ujson.Value = { val jason = writeJs(this) jason } - def validationErrors(path: Seq[Field], failFast: Boolean): Seq[ValidationError] = { + def validationErrors(path : Seq[Field], failFast : Boolean) : Seq[ValidationError] = { val errors = scala.collection.mutable.ListBuffer[ValidationError]() - // ================== id validation ================== - - // ================== category validation ================== - - // validating category - if (errors.isEmpty || !failFast) { - if category != null then - errors ++= category.validationErrors(path :+ Pet.Fields.category, failFast) - } - - // ================== name validation ================== - - // ================== photoUrls validation ================== - - // ================== tags validation ================== + // ================== id validation ================== + + + + + + // ================== category validation ================== + + + + + // validating category + if (errors.isEmpty || !failFast) { + if category != null then errors ++= category.validationErrors(path :+ Pet.Fields.category, failFast) + } - if (errors.isEmpty || !failFast) { - if (tags != null) { - tags.zipWithIndex.foreach { - case (value, i) if errors.isEmpty || !failFast => - errors ++= value.validationErrors( - path :+ Pet.Fields.tags :+ Field(i.toString), - failFast - ) - case (value, i) => + // ================== name validation ================== + + + + + + // ================== photoUrls validation ================== + + + + + + // ================== tags validation ================== + + + + + if (errors.isEmpty || !failFast) { + if (tags != null) { + tags.zipWithIndex.foreach { + case (value, i) if errors.isEmpty || !failFast => + errors ++= value.validationErrors( + path :+ Pet.Fields.tags :+ Field(i.toString), + failFast) + case (value, i) => + } + } } - } - } + - // ================== status validation ================== + // ================== status validation ================== + + + + errors.toSeq } - /** @return - * the validated model within a Try (if successful) - */ - def validated(failFast: Boolean = false): scala.util.Try[Pet] = { + /** + * @return the validated model within a Try (if successful) + */ + def validated(failFast : Boolean = false) : scala.util.Try[Pet] = { validationErrors(Vector(), failFast) match { - case Seq() => Success(asModel) + case Seq() => Success(asModel) case first +: theRest => Failure(ValidationErrors(first, theRest)) } } /** use 'validated' to check validation */ - def asModel: Pet = { + def asModel : Pet = { Pet( - id = Option(id) /* one */, - category = Option(category).map(_.asModel) /* four */, - name = name /* two */, - photoUrls = photoUrls /* two */, - tags = tags.map(_.asModel) /* five */, - status = Option(status) /* one */ - + id = Option(id) /* one */ , + category = Option(category).map(_.asModel) /* four */, + name = name /* two */, + photoUrls = photoUrls /* two */, + tags = tags.map(_.asModel) /* five */, + status = Option(status) /* one */ + ) } } object PetData { - def fromJson(jason: ujson.Value): PetData = try { - val data = read[PetData](jason) - data - } catch { - case NonFatal(e) => sys.error(s"Error creating PetData from json '$jason': $e") + def fromJson(jason : ujson.Value) : PetData = try { + val data = read[PetData](jason) + data + } catch { + case NonFatal(e) => sys.error(s"Error creating PetData from json '$jason': $e") } - def fromJsonString(jason: String): PetData = { - val parsed = - try { - read[ujson.Value](jason) - } catch { - case NonFatal(e) => sys.error(s"Error parsing json '$jason': $e") - } - fromJson(parsed) + def fromJsonString(jason : String) : PetData = { + val parsed = try { + read[ujson.Value](jason) + } catch { + case NonFatal(e) => sys.error(s"Error parsing json '$jason': $e") + } + fromJson(parsed) } - def manyFromJsonString(jason: String): Seq[PetData] = try { - read[List[PetData]](jason) - } catch { - case NonFatal(e) => sys.error(s"Error parsing json '$jason' as list: $e") - } + def manyFromJsonString(jason : String) : Seq[PetData] = try { + read[List[PetData]](jason) + } catch { + case NonFatal(e) => sys.error(s"Error parsing json '$jason' as list: $e") + } - def manyFromJsonStringValidated(jason: String, failFast: Boolean = false): Try[Seq[Pet]] = { - Try(manyFromJsonString(jason)).flatMap { list => - list.zipWithIndex.foldLeft(Try(Vector[Pet]())) { - case (Success(list), (next, i)) => - next.validated(failFast) match { - case Success(ok) => Success(list :+ ok) - case Failure(err) => - Failure(new Exception(s"Validation error on element $i: ${err.getMessage}", err)) - } - case (fail, _) => fail + def manyFromJsonStringValidated(jason : String, failFast : Boolean = false) : Try[Seq[Pet]] = { + Try(manyFromJsonString(jason)).flatMap { list => + list.zipWithIndex.foldLeft(Try(Vector[Pet]())) { + case (Success(list), (next, i)) => + next.validated(failFast) match { + case Success(ok) => Success(list :+ ok) + case Failure(err) => Failure(new Exception(s"Validation error on element $i: ${err.getMessage}", err)) + } + case (fail, _) => fail + } } } - } - def mapFromJsonString(jason: String): Map[String, PetData] = try { - read[Map[String, PetData]](jason) - } catch { - case NonFatal(e) => sys.error(s"Error parsing json '$jason' as map: $e") - } - - def mapFromJsonStringValidated( - jason: String, - failFast: Boolean = false - ): Try[Map[String, Pet]] = { - Try(mapFromJsonString(jason)).flatMap { map => - map.foldLeft(Try(Map[String, Pet]())) { - case (Success(map), (key, next)) => - next.validated(failFast) match { - case Success(ok) => Success(map.updated(key, ok)) - case Failure(err) => - Failure(new Exception(s"Validation error on element $key: ${err.getMessage}", err)) - } - case (fail, _) => fail - } + def mapFromJsonString(jason : String) : Map[String, PetData] = try { + read[Map[String, PetData]](jason) + } catch { + case NonFatal(e) => sys.error(s"Error parsing json '$jason' as map: $e") } + + + def mapFromJsonStringValidated(jason : String, failFast : Boolean = false) : Try[Map[String, Pet]] = { + Try(mapFromJsonString(jason)).flatMap { map => + map.foldLeft(Try(Map[String, Pet]())) { + case (Success(map), (key, next)) => + next.validated(failFast) match { + case Success(ok) => Success(map.updated(key, ok)) + case Failure(err) => Failure(new Exception(s"Validation error on element $key: ${err.getMessage}", err)) + } + case (fail, _) => fail + } + } } } + diff --git a/samples/server/petstore/scala-cask/shared/src/main/scala/sample/cask/model/Tag.scala b/samples/server/petstore/scala-cask/shared/src/main/scala/sample/cask/model/Tag.scala index 5e296fc7d1d1..ff7c97a730dc 100644 --- a/samples/server/petstore/scala-cask/shared/src/main/scala/sample/cask/model/Tag.scala +++ b/samples/server/petstore/scala-cask/shared/src/main/scala/sample/cask/model/Tag.scala @@ -1,14 +1,15 @@ -/** OpenAPI Petstore This is a sample server Petstore server. For this sample, you can use the api - * key `special-key` to test the authorization filters. - * - * OpenAPI spec version: 1.0.0 - * - * Contact: team@openapitools.org - * - * NOTE: This class is auto generated by OpenAPI Generator. - * - * https://openapi-generator.tech - */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator. + * + * https://openapi-generator.tech + */ // this model was generated using model.mustache package sample.cask.model @@ -19,29 +20,35 @@ import scala.util.control.NonFatal import upickle.default.{ReadWriter => RW, macroRW} import upickle.default.* + + case class Tag( - id: Option[Long] = None, - name: Option[String] = None + id: Option[Long] = None , + name: Option[String] = None + + ) { - def asJsonString: String = asData.asJsonString - def asJson: ujson.Value = asData.asJson +def asJsonString: String = asData.asJsonString +def asJson: ujson.Value = asData.asJson - def asData: TagData = { - TagData( - id = id.getOrElse(0) /* 1 */, - name = name.getOrElse("") /* 1 */ +def asData : TagData = { +TagData( + id = id.getOrElse(0) /* 1 */ , + name = name.getOrElse("") /* 1 */ - ) - } +) +} } object Tag { - given RW[Tag] = summon[RW[ujson.Value]].bimap[Tag](_.asJson, json => read[TagData](json).asModel) +given RW[Tag] = summon[RW[ujson.Value]].bimap[Tag](_.asJson, json => read[TagData](json).asModel) - enum Fields(val fieldName: String) extends Field(fieldName) { - case id extends Fields("id") +enum Fields(val fieldName : String) extends Field(fieldName) { + case id extends Fields("id") case name extends Fields("name") - } +} + } + diff --git a/samples/server/petstore/scala-cask/shared/src/main/scala/sample/cask/model/TagData.scala b/samples/server/petstore/scala-cask/shared/src/main/scala/sample/cask/model/TagData.scala index 2ff2c5625f86..758d3a680f73 100644 --- a/samples/server/petstore/scala-cask/shared/src/main/scala/sample/cask/model/TagData.scala +++ b/samples/server/petstore/scala-cask/shared/src/main/scala/sample/cask/model/TagData.scala @@ -1,14 +1,15 @@ -/** OpenAPI Petstore This is a sample server Petstore server. For this sample, you can use the api - * key `special-key` to test the authorization filters. - * - * OpenAPI spec version: 1.0.0 - * - * Contact: team@openapitools.org - * - * NOTE: This class is auto generated by OpenAPI Generator. - * - * https://openapi-generator.tech - */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator. + * + * https://openapi-generator.tech + */ // this model was generated using modelData.mustache package sample.cask.model @@ -19,109 +20,116 @@ import scala.util.* import upickle.default.{ReadWriter => RW, macroRW} import upickle.default.* -/** TagData a data transfer object, primarily for simple json serialisation. It has no validation - - * there may be nulls, values out of range, etc + + /** TagData a data transfer object, primarily for simple json serialisation. + * It has no validation - there may be nulls, values out of range, etc */ case class TagData( - id: Long = 0, - name: String = "" + id: Long = 0 , + name: String = "" + + ) derives RW { def asJsonString: String = asJson.toString() - def asJson: ujson.Value = { + def asJson : ujson.Value = { val jason = writeJs(this) jason } - def validationErrors(path: Seq[Field], failFast: Boolean): Seq[ValidationError] = { + def validationErrors(path : Seq[Field], failFast : Boolean) : Seq[ValidationError] = { val errors = scala.collection.mutable.ListBuffer[ValidationError]() - // ================== id validation ================== - - // ================== name validation ================== + // ================== id validation ================== + + + + + + // ================== name validation ================== + + + + errors.toSeq } - /** @return - * the validated model within a Try (if successful) - */ - def validated(failFast: Boolean = false): scala.util.Try[Tag] = { + /** + * @return the validated model within a Try (if successful) + */ + def validated(failFast : Boolean = false) : scala.util.Try[Tag] = { validationErrors(Vector(), failFast) match { - case Seq() => Success(asModel) + case Seq() => Success(asModel) case first +: theRest => Failure(ValidationErrors(first, theRest)) } } /** use 'validated' to check validation */ - def asModel: Tag = { + def asModel : Tag = { Tag( - id = Option(id) /* one */, - name = Option(name) /* one */ - + id = Option(id) /* one */ , + name = Option(name) /* one */ + ) } } object TagData { - def fromJson(jason: ujson.Value): TagData = try { - val data = read[TagData](jason) - data - } catch { - case NonFatal(e) => sys.error(s"Error creating TagData from json '$jason': $e") + def fromJson(jason : ujson.Value) : TagData = try { + val data = read[TagData](jason) + data + } catch { + case NonFatal(e) => sys.error(s"Error creating TagData from json '$jason': $e") } - def fromJsonString(jason: String): TagData = { - val parsed = - try { - read[ujson.Value](jason) - } catch { - case NonFatal(e) => sys.error(s"Error parsing json '$jason': $e") - } - fromJson(parsed) + def fromJsonString(jason : String) : TagData = { + val parsed = try { + read[ujson.Value](jason) + } catch { + case NonFatal(e) => sys.error(s"Error parsing json '$jason': $e") + } + fromJson(parsed) } - def manyFromJsonString(jason: String): Seq[TagData] = try { - read[List[TagData]](jason) - } catch { - case NonFatal(e) => sys.error(s"Error parsing json '$jason' as list: $e") - } + def manyFromJsonString(jason : String) : Seq[TagData] = try { + read[List[TagData]](jason) + } catch { + case NonFatal(e) => sys.error(s"Error parsing json '$jason' as list: $e") + } - def manyFromJsonStringValidated(jason: String, failFast: Boolean = false): Try[Seq[Tag]] = { - Try(manyFromJsonString(jason)).flatMap { list => - list.zipWithIndex.foldLeft(Try(Vector[Tag]())) { - case (Success(list), (next, i)) => - next.validated(failFast) match { - case Success(ok) => Success(list :+ ok) - case Failure(err) => - Failure(new Exception(s"Validation error on element $i: ${err.getMessage}", err)) - } - case (fail, _) => fail + def manyFromJsonStringValidated(jason : String, failFast : Boolean = false) : Try[Seq[Tag]] = { + Try(manyFromJsonString(jason)).flatMap { list => + list.zipWithIndex.foldLeft(Try(Vector[Tag]())) { + case (Success(list), (next, i)) => + next.validated(failFast) match { + case Success(ok) => Success(list :+ ok) + case Failure(err) => Failure(new Exception(s"Validation error on element $i: ${err.getMessage}", err)) + } + case (fail, _) => fail + } } } - } - - def mapFromJsonString(jason: String): Map[String, TagData] = try { - read[Map[String, TagData]](jason) - } catch { - case NonFatal(e) => sys.error(s"Error parsing json '$jason' as map: $e") - } - def mapFromJsonStringValidated( - jason: String, - failFast: Boolean = false - ): Try[Map[String, Tag]] = { - Try(mapFromJsonString(jason)).flatMap { map => - map.foldLeft(Try(Map[String, Tag]())) { - case (Success(map), (key, next)) => - next.validated(failFast) match { - case Success(ok) => Success(map.updated(key, ok)) - case Failure(err) => - Failure(new Exception(s"Validation error on element $key: ${err.getMessage}", err)) - } - case (fail, _) => fail - } + def mapFromJsonString(jason : String) : Map[String, TagData] = try { + read[Map[String, TagData]](jason) + } catch { + case NonFatal(e) => sys.error(s"Error parsing json '$jason' as map: $e") } + + + def mapFromJsonStringValidated(jason : String, failFast : Boolean = false) : Try[Map[String, Tag]] = { + Try(mapFromJsonString(jason)).flatMap { map => + map.foldLeft(Try(Map[String, Tag]())) { + case (Success(map), (key, next)) => + next.validated(failFast) match { + case Success(ok) => Success(map.updated(key, ok)) + case Failure(err) => Failure(new Exception(s"Validation error on element $key: ${err.getMessage}", err)) + } + case (fail, _) => fail + } + } } } + diff --git a/samples/server/petstore/scala-cask/shared/src/main/scala/sample/cask/model/User.scala b/samples/server/petstore/scala-cask/shared/src/main/scala/sample/cask/model/User.scala index 200de159f81a..0f0e6e283013 100644 --- a/samples/server/petstore/scala-cask/shared/src/main/scala/sample/cask/model/User.scala +++ b/samples/server/petstore/scala-cask/shared/src/main/scala/sample/cask/model/User.scala @@ -1,14 +1,15 @@ -/** OpenAPI Petstore This is a sample server Petstore server. For this sample, you can use the api - * key `special-key` to test the authorization filters. - * - * OpenAPI spec version: 1.0.0 - * - * Contact: team@openapitools.org - * - * NOTE: This class is auto generated by OpenAPI Generator. - * - * https://openapi-generator.tech - */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator. + * + * https://openapi-generator.tech + */ // this model was generated using model.mustache package sample.cask.model @@ -19,49 +20,54 @@ import scala.util.control.NonFatal import upickle.default.{ReadWriter => RW, macroRW} import upickle.default.* + + case class User( - id: Option[Long] = None, - username: Option[String] = None, - firstName: Option[String] = None, - lastName: Option[String] = None, - email: Option[String] = None, - password: Option[String] = None, - phone: Option[String] = None, - /* User Status */ - userStatus: Option[Int] = None + id: Option[Long] = None , + username: Option[String] = None , + firstName: Option[String] = None , + lastName: Option[String] = None , + email: Option[String] = None , + password: Option[String] = None , + phone: Option[String] = None , + /* User Status */ + userStatus: Option[Int] = None + + ) { - def asJsonString: String = asData.asJsonString - def asJson: ujson.Value = asData.asJson - - def asData: UserData = { - UserData( - id = id.getOrElse(0) /* 1 */, - username = username.getOrElse("") /* 1 */, - firstName = firstName.getOrElse("") /* 1 */, - lastName = lastName.getOrElse("") /* 1 */, - email = email.getOrElse("") /* 1 */, - password = password.getOrElse("") /* 1 */, - phone = phone.getOrElse("") /* 1 */, - userStatus = userStatus.getOrElse(0) /* 1 */ - - ) - } +def asJsonString: String = asData.asJsonString +def asJson: ujson.Value = asData.asJson + +def asData : UserData = { +UserData( + id = id.getOrElse(0) /* 1 */ , + username = username.getOrElse("") /* 1 */ , + firstName = firstName.getOrElse("") /* 1 */ , + lastName = lastName.getOrElse("") /* 1 */ , + email = email.getOrElse("") /* 1 */ , + password = password.getOrElse("") /* 1 */ , + phone = phone.getOrElse("") /* 1 */ , + userStatus = userStatus.getOrElse(0) /* 1 */ + +) +} } object User { - given RW[User] = - summon[RW[ujson.Value]].bimap[User](_.asJson, json => read[UserData](json).asModel) - - enum Fields(val fieldName: String) extends Field(fieldName) { - case id extends Fields("id") - case username extends Fields("username") - case firstName extends Fields("firstName") - case lastName extends Fields("lastName") - case email extends Fields("email") - case password extends Fields("password") - case phone extends Fields("phone") +given RW[User] = summon[RW[ujson.Value]].bimap[User](_.asJson, json => read[UserData](json).asModel) + +enum Fields(val fieldName : String) extends Field(fieldName) { + case id extends Fields("id") + case username extends Fields("username") + case firstName extends Fields("firstName") + case lastName extends Fields("lastName") + case email extends Fields("email") + case password extends Fields("password") + case phone extends Fields("phone") case userStatus extends Fields("userStatus") - } +} + } + diff --git a/samples/server/petstore/scala-cask/shared/src/main/scala/sample/cask/model/UserData.scala b/samples/server/petstore/scala-cask/shared/src/main/scala/sample/cask/model/UserData.scala index de7003657c2b..368b35b30247 100644 --- a/samples/server/petstore/scala-cask/shared/src/main/scala/sample/cask/model/UserData.scala +++ b/samples/server/petstore/scala-cask/shared/src/main/scala/sample/cask/model/UserData.scala @@ -1,14 +1,15 @@ -/** OpenAPI Petstore This is a sample server Petstore server. For this sample, you can use the api - * key `special-key` to test the authorization filters. - * - * OpenAPI spec version: 1.0.0 - * - * Contact: team@openapitools.org - * - * NOTE: This class is auto generated by OpenAPI Generator. - * - * https://openapi-generator.tech - */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator. + * + * https://openapi-generator.tech + */ // this model was generated using modelData.mustache package sample.cask.model @@ -19,134 +20,165 @@ import scala.util.* import upickle.default.{ReadWriter => RW, macroRW} import upickle.default.* -/** UserData a data transfer object, primarily for simple json serialisation. It has no validation - - * there may be nulls, values out of range, etc + + /** UserData a data transfer object, primarily for simple json serialisation. + * It has no validation - there may be nulls, values out of range, etc */ case class UserData( - id: Long = 0, - username: String = "", - firstName: String = "", - lastName: String = "", - email: String = "", - password: String = "", - phone: String = "", - /* User Status */ - userStatus: Int = 0 + id: Long = 0 , + username: String = "" , + firstName: String = "" , + lastName: String = "" , + email: String = "" , + password: String = "" , + phone: String = "" , +/* User Status */ + userStatus: Int = 0 + + ) derives RW { def asJsonString: String = asJson.toString() - def asJson: ujson.Value = { + def asJson : ujson.Value = { val jason = writeJs(this) jason } - def validationErrors(path: Seq[Field], failFast: Boolean): Seq[ValidationError] = { + def validationErrors(path : Seq[Field], failFast : Boolean) : Seq[ValidationError] = { val errors = scala.collection.mutable.ListBuffer[ValidationError]() - // ================== id validation ================== - - // ================== username validation ================== - - // ================== firstName validation ================== - - // ================== lastName validation ================== - - // ================== email validation ================== - - // ================== password validation ================== - - // ================== phone validation ================== - - // ================== userStatus validation ================== + // ================== id validation ================== + + + + + + // ================== username validation ================== + + + + + + // ================== firstName validation ================== + + + + + + // ================== lastName validation ================== + + + + + + // ================== email validation ================== + + + + + + // ================== password validation ================== + + + + + + // ================== phone validation ================== + + + + + + // ================== userStatus validation ================== + + + + errors.toSeq } - /** @return - * the validated model within a Try (if successful) - */ - def validated(failFast: Boolean = false): scala.util.Try[User] = { + /** + * @return the validated model within a Try (if successful) + */ + def validated(failFast : Boolean = false) : scala.util.Try[User] = { validationErrors(Vector(), failFast) match { - case Seq() => Success(asModel) + case Seq() => Success(asModel) case first +: theRest => Failure(ValidationErrors(first, theRest)) } } /** use 'validated' to check validation */ - def asModel: User = { + def asModel : User = { User( - id = Option(id) /* one */, - username = Option(username) /* one */, - firstName = Option(firstName) /* one */, - lastName = Option(lastName) /* one */, - email = Option(email) /* one */, - password = Option(password) /* one */, - phone = Option(phone) /* one */, - userStatus = Option(userStatus) /* one */ - + id = Option(id) /* one */ , + username = Option(username) /* one */ , + firstName = Option(firstName) /* one */ , + lastName = Option(lastName) /* one */ , + email = Option(email) /* one */ , + password = Option(password) /* one */ , + phone = Option(phone) /* one */ , + userStatus = Option(userStatus) /* one */ + ) } } object UserData { - def fromJson(jason: ujson.Value): UserData = try { - val data = read[UserData](jason) - data - } catch { - case NonFatal(e) => sys.error(s"Error creating UserData from json '$jason': $e") + def fromJson(jason : ujson.Value) : UserData = try { + val data = read[UserData](jason) + data + } catch { + case NonFatal(e) => sys.error(s"Error creating UserData from json '$jason': $e") } - def fromJsonString(jason: String): UserData = { - val parsed = - try { - read[ujson.Value](jason) - } catch { - case NonFatal(e) => sys.error(s"Error parsing json '$jason': $e") - } - fromJson(parsed) + def fromJsonString(jason : String) : UserData = { + val parsed = try { + read[ujson.Value](jason) + } catch { + case NonFatal(e) => sys.error(s"Error parsing json '$jason': $e") + } + fromJson(parsed) } - def manyFromJsonString(jason: String): Seq[UserData] = try { - read[List[UserData]](jason) - } catch { - case NonFatal(e) => sys.error(s"Error parsing json '$jason' as list: $e") - } + def manyFromJsonString(jason : String) : Seq[UserData] = try { + read[List[UserData]](jason) + } catch { + case NonFatal(e) => sys.error(s"Error parsing json '$jason' as list: $e") + } - def manyFromJsonStringValidated(jason: String, failFast: Boolean = false): Try[Seq[User]] = { - Try(manyFromJsonString(jason)).flatMap { list => - list.zipWithIndex.foldLeft(Try(Vector[User]())) { - case (Success(list), (next, i)) => - next.validated(failFast) match { - case Success(ok) => Success(list :+ ok) - case Failure(err) => - Failure(new Exception(s"Validation error on element $i: ${err.getMessage}", err)) - } - case (fail, _) => fail + def manyFromJsonStringValidated(jason : String, failFast : Boolean = false) : Try[Seq[User]] = { + Try(manyFromJsonString(jason)).flatMap { list => + list.zipWithIndex.foldLeft(Try(Vector[User]())) { + case (Success(list), (next, i)) => + next.validated(failFast) match { + case Success(ok) => Success(list :+ ok) + case Failure(err) => Failure(new Exception(s"Validation error on element $i: ${err.getMessage}", err)) + } + case (fail, _) => fail + } } } - } - - def mapFromJsonString(jason: String): Map[String, UserData] = try { - read[Map[String, UserData]](jason) - } catch { - case NonFatal(e) => sys.error(s"Error parsing json '$jason' as map: $e") - } - def mapFromJsonStringValidated( - jason: String, - failFast: Boolean = false - ): Try[Map[String, User]] = { - Try(mapFromJsonString(jason)).flatMap { map => - map.foldLeft(Try(Map[String, User]())) { - case (Success(map), (key, next)) => - next.validated(failFast) match { - case Success(ok) => Success(map.updated(key, ok)) - case Failure(err) => - Failure(new Exception(s"Validation error on element $key: ${err.getMessage}", err)) - } - case (fail, _) => fail - } + def mapFromJsonString(jason : String) : Map[String, UserData] = try { + read[Map[String, UserData]](jason) + } catch { + case NonFatal(e) => sys.error(s"Error parsing json '$jason' as map: $e") } + + + def mapFromJsonStringValidated(jason : String, failFast : Boolean = false) : Try[Map[String, User]] = { + Try(mapFromJsonString(jason)).flatMap { map => + map.foldLeft(Try(Map[String, User]())) { + case (Success(map), (key, next)) => + next.validated(failFast) match { + case Success(ok) => Success(map.updated(key, ok)) + case Failure(err) => Failure(new Exception(s"Validation error on element $key: ${err.getMessage}", err)) + } + case (fail, _) => fail + } + } } } + diff --git a/samples/server/petstore/scala-cask/shared/src/main/scala/sample/cask/model/package.scala b/samples/server/petstore/scala-cask/shared/src/main/scala/sample/cask/model/package.scala index 4968f07f0134..45a650c9fb6b 100644 --- a/samples/server/petstore/scala-cask/shared/src/main/scala/sample/cask/model/package.scala +++ b/samples/server/petstore/scala-cask/shared/src/main/scala/sample/cask/model/package.scala @@ -1,14 +1,15 @@ -/** OpenAPI Petstore This is a sample server Petstore server. For this sample, you can use the api - * key `special-key` to test the authorization filters. - * - * OpenAPI spec version: 1.0.0 - * - * Contact: team@openapitools.org - * - * NOTE: This class is auto generated by OpenAPI Generator. - * - * https://openapi-generator.tech - */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator. + * + * https://openapi-generator.tech + */ package sample.cask.model @@ -17,9 +18,10 @@ import upickle.default._ import java.time.* import java.time.format.DateTimeFormatter -/** This base class lets us refer to fields in exceptions - */ -class Field(val name: String) +/** + * This base class lets us refer to fields in exceptions + */ +class Field(val name : String) final case class ValidationErrors( first: ValidationError, @@ -38,48 +40,43 @@ object ValidationErrors { } } -final case class ValidationError(path: Seq[Field], message: String) extends Exception(message) { + +final case class ValidationError(path : Seq[Field], message : String) extends Exception(message) { override def toString = s"ValidationError for ${path.mkString(".")}: $message" } given ReadWriter[ZonedDateTime] = readwriter[String].bimap[ZonedDateTime]( zonedDateTime => DateTimeFormatter.ISO_INSTANT.format(zonedDateTime), - str => ZonedDateTime.parse(str, DateTimeFormatter.ISO_INSTANT) -) + str => ZonedDateTime.parse(str, DateTimeFormatter.ISO_INSTANT)) given ReadWriter[LocalDateTime] = readwriter[String].bimap[LocalDateTime]( - zonedDateTime => DateTimeFormatter.ISO_INSTANT.format(zonedDateTime), - str => LocalDateTime.parse(str, DateTimeFormatter.ISO_INSTANT) -) + zonedDateTime => DateTimeFormatter.ISO_INSTANT.format(zonedDateTime), + str => LocalDateTime.parse(str, DateTimeFormatter.ISO_INSTANT)) given ReadWriter[LocalDate] = readwriter[String].bimap[LocalDate]( - zonedDateTime => DateTimeFormatter.ISO_INSTANT.format(zonedDateTime), - str => LocalDate.parse(str, DateTimeFormatter.ISO_INSTANT) -) + zonedDateTime => DateTimeFormatter.ISO_INSTANT.format(zonedDateTime), + str => LocalDate.parse(str, DateTimeFormatter.ISO_INSTANT)) given ReadWriter[OffsetDateTime] = readwriter[String].bimap[OffsetDateTime]( - zonedDateTime => DateTimeFormatter.ISO_INSTANT.format(zonedDateTime), - str => - scala.util - .Try(OffsetDateTime.parse(str, DateTimeFormatter.ISO_DATE_TIME)) - .getOrElse( - OffsetDateTime.parse(str, DateTimeFormatter.ISO_INSTANT) - ) + zonedDateTime => DateTimeFormatter.ISO_INSTANT.format(zonedDateTime), + str => scala.util.Try(OffsetDateTime.parse(str, DateTimeFormatter.ISO_DATE_TIME)).getOrElse( + OffsetDateTime.parse(str, DateTimeFormatter.ISO_INSTANT) + ) ) + extension (json: ujson.Value) { - def mergeWith(other: ujson.Value): ujson.Value = (json, other) match { - case (ujson.Obj(aMap), ujson.Obj(bMap)) => - val mergedMap: scala.collection.mutable.Map[String, ujson.Value] = aMap ++ bMap.map { - case (k, v) => - k -> (aMap.get(k) match { - case Some(aValue) => aValue.mergeWith(v) - case None => v - }) - } - ujson.Obj.from(mergedMap) - case (ujson.Arr(aArray), ujson.Arr(bArray)) => ujson.Arr(aArray ++ bArray) - case (aValue, ujson.Null) => aValue - case (_, bValue) => bValue - } -} + def mergeWith(other: ujson.Value): ujson.Value = (json, other) match { + case (ujson.Obj(aMap), ujson.Obj(bMap)) => + val mergedMap: scala.collection.mutable.Map[String, ujson.Value] = aMap ++ bMap.map { + case (k, v) => k -> (aMap.get(k) match { + case Some(aValue) => aValue.mergeWith(v) + case None => v + }) + } + ujson.Obj.from(mergedMap) + case (ujson.Arr(aArray), ujson.Arr(bArray)) => ujson.Arr(aArray ++ bArray) + case (aValue, ujson.Null) => aValue + case (_, bValue) => bValue + } +} \ No newline at end of file