Created
August 31, 2017 20:31
-
-
Save ugexe/644d53553818c245e080679c925f9817 to your computer and use it in GitHub Desktop.
Basic get/delete/put/post json store example using Perl 6 and Cro
This file contains 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
#!/usr/bin/env perl6 | |
use v6; | |
use Cro::HTTP::Server; | |
use Cro::HTTP::Router; | |
use Cro::HTTP::BodyParser; | |
# Create a new resource | |
# curl --verbose -H "Content-Type: application/json" -X POST -d '{ "foo" : "123" }' http://localhost:3000/resource | |
# Get list of all resources | |
# curl --verbose -X GET http://localhost:3000/resource | |
# Update an existing resource | |
# curl --verbose -H "Content-Type: application/json" -X PUT -d '{ "bar" : "456" }' http://localhost:3000/resource/0 | |
# Delete an existing resource | |
# curl --verbose -X DELETE http://localhost:3000/resource/0 | |
sub MAIN(:$host = 'localhost', :$port = 3000) { | |
my $json-storage-service = Cro::HTTP::Server.new( | |
host => $host, | |
port => $port, | |
body-parsers => [Cro::HTTP::BodyParser::JSON], | |
application => route { | |
my Hash @storage; | |
my atomicint $storage-counter = 0; | |
my subset ValidResourceId of Int where { @storage[$_].defined } | |
get -> 'resource', ValidResourceId $id { | |
content 'application/json', @storage[$id]; | |
} | |
get -> 'resource' { | |
content 'application/json', @storage.grep(*.defined).list; | |
} | |
put -> 'resource', ValidResourceId $id { | |
request-body -> %json where !*.?EXISTS-KEY('_id') { | |
@storage[$id] = %json; | |
response.status = 204; | |
} | |
} | |
post -> 'resource' { | |
request-body -> %json where !*.?EXISTS-KEY('_id') { | |
my $resource-id = $storage-counter⚛++; | |
@storage[$resource-id] = %( %json.Slip, _id => $resource-id ); | |
created "/resource/$resource-id", 'application/json', %json; | |
} | |
} | |
delete -> 'resource', ValidResourceId $id { | |
@storage[$id] = Nil; | |
response.status = 204; | |
} | |
}, | |
) andthen *.start; | |
react { | |
whenever signal(SIGINT) { | |
$json-storage-service.stop; | |
exit; | |
} | |
} | |
} | |
BEGIN die "Run `zef install Cro --/test` first\n" if (try require ::("Cro::HTTP::Server")) ~~ Nil; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment