|
| 1 | +// Feature: web controller payload (de)serialization. |
| 2 | +// |
| 3 | +// A controller replies with `res.send(dto)` and reads a typed body with |
| 4 | +// `req.parse(T)`. Both route the payload through the DI-resolved `WebTransport` |
| 5 | +// over the compiler's auto-derived JSON codecs (`dto as Json` / `json as T`). |
| 6 | +// This test exercises that exact path without standing up a server: bind the |
| 7 | +// default `JsonTransport`, then serialize a DTO to the wire and parse it back. |
| 8 | +import "std/web.xi" |
| 9 | + |
| 10 | +// The kind of payload a controller sends back (res.send) ... |
| 11 | +event Created = { id: Integer, name: String, active: Bool } |
| 12 | +// ... and the kind it accepts in a request body (req.parse). |
| 13 | +type NewUser = { name: String, age: Integer } |
| 14 | + |
| 15 | +module WebPayload { bind WebTransport -> JsonTransport as singleton } |
| 16 | + |
| 17 | +test "serialize a controller response payload (res.send path)" { |
| 18 | + let tx = WebPayload.resolve(WebTransport) |
| 19 | + let dto = Created { id: 7, name: "John Doe", active: true } |
| 20 | + // res.send(dto) === transport.serialize(dto as Json) |
| 21 | + let wire = tx.serialize(dto as Json) |
| 22 | + assertEq(wire, "{\"id\":7,\"name\":\"John Doe\",\"active\":true}") |
| 23 | +} |
| 24 | + |
| 25 | +test "deserialize a request body payload (req.parse path)" { |
| 26 | + let tx = WebPayload.resolve(WebTransport) |
| 27 | + let body = "{\"name\":\"John Doe\",\"age\":44}" |
| 28 | + // req.parse(NewUser) === transport.deserialize(body) as NewUser |
| 29 | + let u = (tx.deserialize(body)) as NewUser |
| 30 | + assertEq(u.name, "John Doe") |
| 31 | + assertEq(u.age, 44) |
| 32 | +} |
| 33 | + |
| 34 | +test "round-trip a payload through the transport" { |
| 35 | + let tx = WebPayload.resolve(WebTransport) |
| 36 | + let sent = Created { id: 3, name: "Ada", active: false } |
| 37 | + let back = (tx.deserialize(tx.serialize(sent as Json))) as Created |
| 38 | + assertEq(back.id, 3) |
| 39 | + assertEq(back.name, "Ada") |
| 40 | + assertEq(back.active, false) |
| 41 | +} |
0 commit comments