Skip to content

Instantly share code, notes, and snippets.

@recursivecodes
Created April 17, 2019 20:40
Show Gist options
  • Select an option

  • Save recursivecodes/db1101f9f76ba6eb860e220a2f8536a7 to your computer and use it in GitHub Desktop.

Select an option

Save recursivecodes/db1101f9f76ba6eb860e220a2f8536a7 to your computer and use it in GitHub Desktop.
package codes.recursive
import codes.recursive.model.Person
import codes.recursive.service.PersonService
import groovy.transform.CompileStatic
import io.micronaut.http.HttpResponse
import io.micronaut.http.HttpStatus
import io.micronaut.http.annotation.Body
import io.micronaut.http.annotation.Controller
import io.micronaut.http.annotation.Get
import io.micronaut.http.annotation.Post
import io.micronaut.validation.Validated
import org.grails.datastore.mapping.validation.ValidationException
import org.springframework.validation.FieldError
import javax.annotation.Nullable
import javax.inject.Inject
import javax.validation.Valid
@CompileStatic
@Validated
@Controller("/test")
class TestController {
@Inject PersonService personService
@Get("/")
HttpResponse index() {
return HttpResponse.status(HttpStatus.OK).body([awesome: true, javaVersion: System.getProperty("java.version")])
}
@Get("/persons{/offset}{/max}")
List<Person> getPersons(@Nullable Optional<Integer> offset, @Nullable Optional<Integer> max) {
if( offset && max ) {
return personService.findAll([offset: offset.get(), max: max.get()])
}
else {
return personService.findAll()
}
}
@Get("/person/{id}")
Person getPerson(int id) {
return personService.find(id)
}
@Post("/savePerson")
HttpResponse<Map> savePerson(@Valid @Body Person person) {
try {
personService.save(person)
return HttpResponse.ok( [ person: person ] as Map
)
}
catch(ValidationException e) {
return HttpResponse.unprocessableEntity().body(
[
person: person,
errors: e.errors.allErrors.collect {
FieldError err = it as FieldError
[
field: err.field,
rejectedValue: err.rejectedValue,
message: err.defaultMessage
]
}
]
) as HttpResponse<Map>
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment