- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPostController.scala
73 lines (59 loc) · 1.8 KB
/
PostController.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
packagev1.post
importjavax.inject.Inject
importplay.api.Logger
importplay.api.data.Form
importplay.api.libs.json.Json
importplay.api.mvc._
importscala.concurrent.{ExecutionContext, Future}
caseclassPostFormInput(title: String, body: String)
objectPostFormInput {
defunapply(postFormInput: PostFormInput):Option[(String, String)] = {
Some((postFormInput.title, postFormInput.body))
}
}
/**
* Takes HTTP requests and produces JSON.
*/
classPostController@Inject()(cc: PostControllerComponents)(
implicitec: ExecutionContext)
extendsPostBaseController(cc) {
privatevallogger=Logger(getClass)
privatevalform:Form[PostFormInput] = {
importplay.api.data.Forms._
Form(
mapping(
"title"-> nonEmptyText,
"body"-> text
)(PostFormInput.apply)(PostFormInput.unapply)
)
}
defindex:Action[AnyContent] =PostAction.async { implicit request =>
logger.trace("index: ")
postResourceHandler.find.map { posts =>
Ok(Json.toJson(posts))
}
}
defprocess:Action[AnyContent] =PostAction.async { implicit request =>
logger.trace("process: ")
processJsonPost()
}
defshow(id: String):Action[AnyContent] =PostAction.async {
implicit request =>
logger.trace(s"show: id = $id")
postResourceHandler.lookup(id).map { post =>
Ok(Json.toJson(post))
}
}
privatedefprocessJsonPost[A]()(
implicitrequest: PostRequest[A]):Future[Result] = {
deffailure(badForm: Form[PostFormInput]) = {
Future.successful(BadRequest(badForm.errorsAsJson))
}
defsuccess(input: PostFormInput) = {
postResourceHandler.create(input).map { post =>
Created(Json.toJson(post)).withHeaders(LOCATION-> post.link)
}
}
form.bindFromRequest().fold(failure, success)
}
}