Skip to content

Instantly share code, notes, and snippets.

@gontard
Last active March 19, 2021 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gontard/f7cd38d444ee918bec229dc66d627877 to your computer and use it in GitHub Desktop.
Save gontard/f7cd38d444ee918bec229dc66d627877 to your computer and use it in GitHub Desktop.
ScalaPB code generation of case class and validator
syntax = "proto2";
package teads.api;
import "validate/validate.proto";
message CreateAccountRequest {
required string first_name = 1 [(validate.rules).string.max_len = 255];
required string last_name = 2 [(validate.rules).string.max_len = 255];
required string email = 3 [(validate.rules).string.email = true];
optional string website = 4 [(validate.rules).string.uri = true];
repeated string roles = 5 [(validate.rules).repeated = {min_items: 1, unique: true}];
}
package teads.api
final case class CreateAccountRequest(
firstName: String,
lastName: String,
email: String,
website: Option[String] = None,
roles: Seq[String] = Seq.empty
) extends scalapb.GeneratedMessage {
...
}
package teads.api
import scalapb.validate.{Result, Validator}
import scalapb.validate.RepeatedValidation._
import io.envoyproxy.pgv.StringValidation._
object CreateAccountRequestValidator extends Validator[CreateAccountRequest] {
def validate(input: CreateAccountRequest): Result =
Result.run(maxLength("CreateAccountRequest.first_name", input.firstName, 255)) &&
Result.run(maxLength("CreateAccountRequest.last_name", input.lastName, 255)) &&
Result.run(email("CreateAccountRequest.email", input.email)) &&
Result.optional(input.website) { _value =>
Result.run(uri("CreateAccountRequest.website", _value))
} &&
minItems("CreateAccountRequest.roles", input.roles.size, 1) &&
unique("CreateAccountRequest.roles", input.roles.iterator.toSeq)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment