Discussion:
Render to "json:api" specification, not the usual json for REST
(too old to reply)
Nacho B
2018-08-14 14:37:13 UTC
Permalink
Hi!

I've been asked to build a backend using *"json:api" specification* (
http://jsonapi.org/). It will be accessed from an front end built with
Ember.

I thought it should be easy, but Its not the usual REST with JSON you cant
get with
return $self->pg->db->select('pressure_t')->hashes->to_array


The response should be like this.

{
"data": [
{
"id": "6d2d4245-41dc-4903-85a6-2c63b51ba15f",
"type": "pressure",
"attributes": {
"notes": "some notes from user",
"place": "home",
"time": "2018-07-26 18:40:00+02",
}
},
{
"id": "ccaf333e-682e-45de-98ef-5dd8e8ee7740",
"type": "pressure".
"attributes": {
"notes": "some notes from user",
"place": "home",
"time": "2018-07-26 17:34:00+02",
}
}
]
}



Here it is is my quick and dirty solution, just to keep things rolling:

In Model::Pressures

sub all {
my $self = shift;
return $self->pg->db->select('pressure_t')->hashes
}


In Controller::Pressures

sub index_json {
my $self = shift;

my @response;
my $results = $self->pressures->all;

foreach my $row (@$results) {
push @response, {
'id' => $row->{pressure_id},
'type' => 'pressure',
'attributes' => $row
};
}

$self->render(
json => {
data => [
@response
]
}
)
}



"json:api" can be more complex, with more properties in the first level,
but my current query is pretty simple:
- "Id", in the first level
- "type", also in the first level, but the value is fixed
- "attributes", with the rest of the retrieved columns

Maybe a map can be more elegant than creating an additional array to copy
everything. But in any case It seems to me that there are too many
transformations and wrappers of the same information, from the db to the
front end solution.


Any suggestion to make things easier and faster? it seems that "json:api"
is been used more and more.

Thank you in advance.

Nacho B.
--
You received this message because you are subscribed to the Google Groups "Mojolicious" group.
To unsubscribe from this group and stop receiving emails from it, send an email to mojolicious+***@googlegroups.com.
To post to this group, send email to ***@googlegroups.com.
Visit this group at https://groups.google.com/group/mojolicious.
For more options, visit https://groups.google.com/d/optout.
Loading...