Skip to content

Commit e8047e2

Browse files
authored
Create README.md
1 parent 07a7c8b commit e8047e2

File tree

1 file changed

+107
-0
lines changed

1 file changed

+107
-0
lines changed

README.md

Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
# javalin-generator
2+
Java annotation processor for generating web route to Controller adapters
3+
4+
## Define a Controller
5+
```java
6+
package org.example.hello
7+
8+
import io.dinject.controller.Controller
9+
import io.dinject.controller.Get
10+
import io.dinject.controller.Path
11+
12+
@Path("/widgets")
13+
@Controller
14+
class WidgetController(private val hello: HelloComponent) {
15+
16+
@Get("/:id")
17+
fun getById(id : Int): Widget {
18+
return Widget(id, "you got it${hello.hello()}")
19+
}
20+
21+
@Get
22+
fun getAll(): MutableList<Widget> {
23+
24+
val list = mutableListOf<Widget>()
25+
list.add(Widget(1, "Rob"))
26+
list.add(Widget(2, "Fi"))
27+
28+
return list
29+
}
30+
31+
data class Widget(var id: Int, var name: String)
32+
}
33+
34+
```
35+
36+
## Generated source
37+
38+
The annotation processor will generate a `$route` for the controller like below.
39+
40+
Note that this class implements the WebRoutes interface, which means we can
41+
get all the WebRoutes and register them with Javalin using.
42+
43+
```java
44+
fun main(args: Array<String>) {
45+
46+
// get all the webRoutes
47+
val webRoutes = SystemContext.getBeans(WebRoutes::class.java)
48+
49+
val javalin = Javalin.create()
50+
51+
javalin.routes {
52+
// register all the routes with Javalin
53+
webRoutes.forEach { it.registerRoutes() }
54+
55+
// other routes etc as desired
56+
ApiBuilder.get("/foo") { ctx ->
57+
ctx.html("bar")
58+
ctx.status(200)
59+
}
60+
...
61+
}
62+
63+
javalin.start(7000)
64+
}
65+
66+
```
67+
68+
### The generated WidgetController$route.java is:
69+
70+
71+
```java
72+
package org.example.hello;
73+
74+
import static io.dinject.controller.PathTypeConversion.*;
75+
import io.dinject.controller.WebRoutes;
76+
import io.javalin.apibuilder.ApiBuilder;
77+
import javax.annotation.Generated;
78+
import javax.inject.Singleton;
79+
import org.example.hello.WidgetController;
80+
81+
@Generated("io.dinject.web.javlin")
82+
@Singleton
83+
public class WidgetController$route implements WebRoutes {
84+
85+
private final WidgetController controller;
86+
87+
public WidgetController$route(WidgetController controller) {
88+
this.controller = controller;
89+
}
90+
91+
@Override
92+
public void registerRoutes() {
93+
94+
ApiBuilder.get("/widgets/:id", ctx -> {
95+
int id = asInt(ctx.pathParam("id"));
96+
ctx.json(controller.getById(id));
97+
ctx.status(200);
98+
});
99+
100+
ApiBuilder.get("/widgets", ctx -> {
101+
ctx.json(controller.getAll());
102+
ctx.status(200);
103+
});
104+
105+
}
106+
}
107+
```

0 commit comments

Comments
 (0)