|
31 | 31 | [:error (sc/human-readable-explain (sc/explain schema data))] |
32 | 32 | [:ok result]))) |
33 | 33 |
|
34 | | -(defn- json-body |
35 | | - "Reads and decodes a JSON request body from the raw input stream. |
36 | | - Returns an empty map when the body is empty or malformed." |
37 | | - [_req] |
38 | | - (let [raw (php/file_get_contents "php://input")] |
39 | | - (if (and (string? raw) (not (php/empty raw))) |
40 | | - (try (json/decode raw) (catch \Throwable _ {})) |
41 | | - {}))) |
| 34 | +(defn- greet-response |
| 35 | + "Validates `params` against the greet schema and answers with a greeting or |
| 36 | + a 400. Shared by the path-param and JSON-body greet routes." |
| 37 | + [params] |
| 38 | + (let [[status payload] (conform-or-error schema/greet-params params)] |
| 39 | + (if (= status :ok) |
| 40 | + (json-response 200 {:greeting (g/greet (:name payload))}) |
| 41 | + (bad-request payload)))) |
42 | 42 |
|
43 | 43 | (defn index-handler [_req] |
44 | 44 | (html-response 200 index-html)) |
45 | 45 |
|
46 | 46 | (defn ping-handler [req] |
47 | | - ;; Pattern-match on the HTTP method instead of nested conds. |
| 47 | + ;; Pattern-match on the HTTP method instead of nested conds. The JSON body is |
| 48 | + ;; decoded by phel.http into :parsed-body, so there is no manual php://input read. |
48 | 49 | (match [(:method req)] |
49 | | - ["POST"] (json-response 200 {:message "pong" :echo (json-body req) :ts (php/time)}) |
| 50 | + ["POST"] (json-response 200 {:message "pong" :echo (or (:parsed-body req) {}) :ts (php/time)}) |
50 | 51 | ["GET"] (json-response 200 {:message "pong" :ts (php/time)}) |
51 | 52 | :else (json-response 405 {:error "method not allowed"}))) |
52 | 53 |
|
53 | 54 | (defn greet-handler |
54 | 55 | "GET /greet/{name} — validates the path param against a schema before use." |
55 | 56 | [req] |
56 | | - (let [name (get-in req [:attributes :match :path-params :name] "world") |
57 | | - [status result] (conform-or-error schema/greet-params {:name name})] |
58 | | - (if (= status :ok) |
59 | | - (json-response 200 {:greeting (g/greet (:name result))}) |
60 | | - (bad-request result)))) |
| 57 | + (greet-response {:name (get-in req [:attributes :match :path-params :name] "world")})) |
61 | 58 |
|
62 | 59 | (defn greet-post-handler |
63 | | - "POST /greet — reads a JSON body `{\"name\": \"...\"}`, validates, responds." |
| 60 | + "POST /greet — reads a JSON body `{\"name\": \"...\"}`, validates, responds. |
| 61 | + phel.http already decoded the body into `:parsed-body`." |
64 | 62 | [req] |
65 | | - (let [[status result] (conform-or-error schema/greet-params (json-body req))] |
66 | | - (if (= status :ok) |
67 | | - (json-response 200 {:greeting (g/greet (:name result))}) |
68 | | - (bad-request result)))) |
| 63 | + (greet-response (or (:parsed-body req) {}))) |
69 | 64 |
|
70 | 65 | (defn not-found-handler [_req] |
71 | 66 | (html-response 404 "<h1>404</h1><p>Page not found.</p>")) |
0 commit comments