Created
July 21, 2021 16:51
-
-
Save jonathanstowe/7d2ec8d499ddb058e62669cac0792cbb to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use Cro::HTTP::BodySerializers; | |
use JSON::Class; | |
class Foo::HTTP::BodySerializerJSONClass does Cro::HTTP::BodySerializer { | |
method is-applicable(Cro::HTTP::Message $message, $body --> Bool) { | |
with $message.content-type { | |
(.type eq 'application' && .subtype eq 'json' || .suffix eq 'json') && ($body ~~ JSON::Class ); | |
} | |
else { | |
False | |
} | |
} | |
method serialize(Cro::HTTP::Message $message, $body --> Supply) { | |
my $json = $body.to-json( :!pretty).encode('utf-8'); | |
self!set-content-length($message, $json.bytes); | |
supply { emit $json } | |
} | |
} | |
# Then given a model like | |
use Red; | |
use JSON::Class; | |
model Foo does JSON::Class { | |
has Int $.id is id; | |
has Str $.whatever is column; | |
has Date $.date is column is marshalled-by('Str'); | |
} | |
# Then in some Cro::Route | |
get -> 'foos-for-date', Date() $date { | |
content 'application/json', ( Foo.^all.grep( *.date eq $date ) but JSON::Class ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment