DRY solution to add self link to all results for a hypermedia api within express/sailsjs

Use Case

When implementing an application/collection+json response with SailsJS, it is necessary to add the rel and href attributes to every item or model. I've tried two solutions, but haven't been able to come up with a fool-proof solution that keeps the code DRY. The best possible solution I think would be to include this within the config/models.js file or a service, but in both solutions I do not know the model name that I am working with to construct the href.

Question

How does one reflect the model name within config/models.js or a service while keeping the code DRY?

Solution 1

The current solution is to use the api/responses/ok.js file and call a service that loops through all data items and adds the self reference. The variable url parses the request for the model name by assuming that the first word after the sails.config.blueprints.prefix is the model name.

data = _.map(data, function(item) {
  item.rel = "self";
  item.href = url + '/' + item.id;
  return item
});

Problems

When URL Slugs are used, this process completely breaks as the first word after the prefix in a URL Slug may not be the model name.

Solution 2

The second solution is to add the rel and href attributes within each model using the toJSON function.

...
toJSON: function() {
  var obj = this.toObject();
  obj.rel = "self";
  obj.href = "HARDCODE MODEL NAME" + '/' + obj.id
}
...

Problems

This solution isn't DRY.

Desired Solution

Using config/models.js one can modify the toJSON for every model in the system. The model name would then replace the ???.

module.exports.model = {
  toJSON: function() {
    var obj = this.toObject();
    obj.rel = "self";
    obj.href = [sails.config.blueprints.prefix, ???, obj.id ].join('/');
  }
}

References