halacious
halacious copied to clipboard
Unable to add an empty array of embedded entities with different hrefs
Hi,
Issue https://github.com/bleupen/halacious/issues/58 allows empty arrays of embedded entities, but I can't see how to use it where I need to map objects that have self-refs defined by their own properties (eg. '/people/{id}') in an array that might be empty.
I think I'm looking for rep.embed
to support an array-arg based variant (like rep.link
) such as embed(rel, embeddables)
where toEmbed is an object with self and entity properties. Then, I can call
rep.embed('friends', rawFriendsArray.map(function(friend) {
var selfHref = '/people/'+friend.id;
delete friend.id;
return {self: selfHref, entity: friend};
}));
...and rawFriendsArray happens to be empty it'll just embed an empty array.
Happy to submit a PR for this if I'm not missing a better way to do it already!
i like that idea. You can do this easily already in route configuration, but its more difficult programmatically:
{
handler: function(req, reply) {
reply({ name: 'John Doe', friends: ['Jane', 'Moe', 'Play']}
},
plugins: {
hal: {
friends: {
path: 'friends',
href: '/people/{item.id}'
}
}
}
}
Cheers - hopefully will get a few minutes to put something together...
Implementing was trickier than I expected - maybe needs a bit of callback acrobatics to embed the entity and still provide access to the representation to configure links, not enough time!
But I found a workaround... embed an array with the right rel first.
rep.embed('friends', 'whatever-its-empty', []);
rep.entity.friends.forEach(function(friend) {
var friendRep = rep.embed('friends', '/friends/'+friend.id, friend);
friendRep.link('unfriend', './unfriend');
friendRep.ignore('id');
});
Feels a bit hacky but it means that the rep will have an _embedded.friends that is an array regardless of how many friends there are at runtime.
Happy to close this off.