|
19 | 19 | package org.jooby.internal.assets; |
20 | 20 |
|
21 | 21 | import java.util.List; |
22 | | -import java.util.stream.Collectors; |
23 | 22 |
|
24 | 23 | import org.jooby.Request; |
25 | 24 | import org.jooby.Response; |
26 | 25 | import org.jooby.Route; |
27 | 26 | import org.jooby.assets.AssetCompiler; |
28 | 27 |
|
| 28 | +import javaslang.Function1; |
| 29 | + |
29 | 30 | public class AssetVars implements Route.Handler { |
30 | 31 |
|
31 | 32 | private AssetCompiler compiler; |
32 | 33 |
|
33 | 34 | private String cpath; |
34 | 35 |
|
35 | | - public AssetVars(final AssetCompiler compiler, final String cpath) { |
| 36 | + private Function1<String, List<String>> styles; |
| 37 | + private Function1<String, List<String>> scripts; |
| 38 | + |
| 39 | + public AssetVars(final AssetCompiler compiler, final String cpath, final boolean cache) { |
36 | 40 | this.compiler = compiler; |
37 | 41 | this.cpath = cpath.equals("/") ? "" : cpath; |
| 42 | + styles = compiler::styles; |
| 43 | + scripts = compiler::scripts; |
| 44 | + if (cache) { |
| 45 | + styles = styles.memoized(); |
| 46 | + scripts = scripts.memoized(); |
| 47 | + } |
38 | 48 | } |
39 | 49 |
|
40 | 50 | @Override |
41 | 51 | public void handle(final Request req, final Response rsp) throws Exception { |
42 | 52 | compiler.fileset().forEach(asset -> { |
43 | 53 | /** Styles */ |
44 | | - List<String> styles = compiler.styles(asset); |
45 | | - req.set(asset + "_css", styles); |
46 | | - req.set(asset + "_styles", styles.stream() |
47 | | - .map(p -> "<link href=\"" + cpath + p + "\" rel=\"stylesheet\">\n") |
48 | | - .collect(Collectors.joining())); |
| 54 | + List<String> css = this.styles.apply(asset); |
| 55 | + String styles = css.stream().reduce(new StringBuilder(), |
| 56 | + (buff, it) -> buff.append("<link href=\"") |
| 57 | + .append(cpath) |
| 58 | + .append(it) |
| 59 | + .append("\" rel=\"stylesheet\">\n"), |
| 60 | + StringBuilder::append) |
| 61 | + .toString(); |
| 62 | + req.set(asset + "_css", css); |
| 63 | + req.set(asset + "_styles", styles); |
49 | 64 |
|
50 | 65 | /** Scripts */ |
51 | | - List<String> scripts = compiler.scripts(asset); |
52 | | - req.set(asset + "_js", scripts); |
53 | | - req.set(asset + "_scripts", scripts.stream() |
54 | | - .map(p -> "<script src=\"" + cpath + p + "\"></script>\n") |
55 | | - .collect(Collectors.joining())); |
| 66 | + List<String> js = this.scripts.apply(asset); |
| 67 | + String scripts = js.stream().reduce(new StringBuilder(), |
| 68 | + (buff, it) -> buff.append("<script src=\"") |
| 69 | + .append(cpath) |
| 70 | + .append(it) |
| 71 | + .append("\"></script>\n"), |
| 72 | + StringBuilder::append) |
| 73 | + .toString(); |
| 74 | + req.set(asset + "_js", js); |
| 75 | + req.set(asset + "_scripts", scripts); |
56 | 76 | }); |
57 | 77 | } |
58 | 78 |
|
|
0 commit comments