Reputation: 156
Sometimes, we need to modify the response JSON data before it be sent to client. for example:
//model definition
{
"name": "File",
"base": "PersistedModel",
"properties": {
"filename": {
"type": "string",
"required": true
},
"filepath": {
"type": "string"
}
}
"protected": ["filepath"]
}
I want to get a url
property on GET /files/:id
request, and so I defined a url GETTER on prototype.
//file.js
module.exports = function(File){
var baseUrl = 'http://example.com/uploads/files/';
File.prototype.__defineGetter__('url', function(){
return baseUrl + this.id.toString() + this.filename;
});
}
My question is How to expose the url
property to remote response when I make a request as following?
GET /files/123456
expect a response like:
{
id: '123456',
filename: 'myfile.ext',
url: 'http://example.com/uploads/files/123456/myfile.ext'
}
Thanks a lot!
Upvotes: 0
Views: 298
Reputation: 2610
You can use Operation Hooks to intercept CRUD actions independently of the specific method that invoke them.
The code below will add the url
property to the File object when loading a File object.
File.observe('loaded', function(ctx, next) {
var baseUrl = 'http://example.com/uploads/files/';
ctx.data.url = baseUrl + data.id + data.filename;
next();
});
This will get called when any of the methods below are invoked, either directly in your JS or indirectly via the HTTP API.
Other Operation Hooks include:
Upvotes: 1
Reputation: 2781
Use a remote method/hook and customize your response accordingly. See https://github.com/strongloop/loopback-example-app-logic/blob/master/common/models/car.js.
Upvotes: 2