| 1 | 1 | ▶ | use v5.40; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 2 | 1 | ▶ | use experimental 'signatures'; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 3 | 1 | ▶ | use Future::AsyncAwait; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 4 | 1 | ▶ | use PAGI::Nano; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 5 | |||
| 6 | # The strong-parameters grammar past the simple cases: a nested hash rule, a | ||
| 7 | # bare array, an array-of-hashes, and (for form bodies) namespace + flat-key | ||
| 8 | # reconstruction. $c->params picks the source by content-type — JSON keeps | ||
| 9 | # structure as-is; an urlencoded form rebuilds nested shapes from dotted/bracket | ||
| 10 | # keys. required's on-missing callback owns the 400. | ||
| 11 | # | ||
| 12 | # pagi-server app.pl | ||
| 13 | # | ||
| 14 | # # JSON order: nested address, bare-array coupons, array-of-hashes items | ||
| 15 | # curl -H 'content-type: application/json' -d '{ | ||
| 16 | # "customer":"Ada","address":{"street":"1 Calc Ln","city":"London"}, | ||
| 17 | # "coupons":["EARLY","VIP"], | ||
| 18 | # "items":[{"sku":"A1","qty":"2"},{"sku":"B2","qty":"1"}] | ||
| 19 | # }' http://127.0.0.1:5000/orders | ||
| 20 | # | ||
| 21 | # # Form profile: dotted keys rebuilt under a namespace | ||
| 22 | # curl -d 'user.name=Ada&user.email=ada@calc.dev&spam=x' http://127.0.0.1:5000/profile | ||
| 23 | |||
| 24 | 1 | ▶ | my $app = app { |
|
Subroutine
__ANON__: called CC=1 SCAR=0.0
| |||
| 25 | # JSON body: the rich rule grammar, with required guarding the must-haves. | ||
| 26 | 2 | ▶ | post '/orders' => async sub ($c) { |
|
Subroutine
__ANON__: called CC=1 SCAR=0.0
| |||
| 27 | my $order = await $c->params->required( | ||
| 28 | 'customer', # a required scalar | ||
| 29 | address => ['street', 'city'], # a nested hash (its keys whitelisted) | ||
| 30 | +{ items => ['sku', 'qty'] }, # an array of hashes | ||
| 31 | +{ coupons => [] }, # a bare array of scalars | ||
| 32 | 1 | ▶ | sub ($c, $missing) { |
|
Subroutine
__ANON__: called CC=1 SCAR=0.0
| |||
| 33 | 1 | $c->json({ error => 'missing', fields => $missing }, status => 400); | |
| 34 | }, | ||
| 35 | 2 | ); | |
| 36 | 1 | $c->json({ accepted => $order }, status => 201); | |
| 37 | 1 | }; | |
| 38 | |||
| 39 | # Form body: namespace scopes the rules to a key prefix, and the dotted flat | ||
| 40 | # keys (user.name, user.email) are reconstructed into a nested hash. Keys | ||
| 41 | # outside the whitelist (spam) are dropped. | ||
| 42 | 1 | ▶ | post '/profile' => async sub ($c) { |
|
Subroutine
__ANON__: called CC=1 SCAR=0.0
| |||
| 43 | 1 | my $profile = await $c->params->namespace(['user'])->permitted('name', 'email'); | |
| 44 | 1 | $c->json({ user => $profile }); | |
| 45 | 1 | }; | |
| 46 | 1 | }; | |
| 47 | |||
| 48 | 1 | $app; | |