Loopbackjs 什么';设置/定制远程响应的最佳方式是什么?
有时,我们需要在将响应JSON数据发送到客户端之前对其进行修改。例如:Loopbackjs 什么';设置/定制远程响应的最佳方式是什么?,loopbackjs,Loopbackjs,有时,我们需要在将响应JSON数据发送到客户端之前对其进行修改。例如: //model definition { "name": "File", "base": "PersistedModel", "properties": { "filename": { "type": "string", "required": true }, "filepath": { "type": "string" } } "pro
//model definition
{
"name": "File",
"base": "PersistedModel",
"properties": {
"filename": {
"type": "string",
"required": true
},
"filepath": {
"type": "string"
}
}
"protected": ["filepath"]
}
我想在get/files/:id
请求上获得一个url
属性,因此我在prototype上定义了一个url GETTER
//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;
});
}
我的问题是,当我发出如下请求时,如何向远程响应公开url
属性
GET /files/123456
期望得到如下响应:
{
id: '123456',
filename: 'myfile.ext',
url: 'http://example.com/uploads/files/123456/myfile.ext'
}
非常感谢 您可以使用来拦截CRUD操作,而不依赖于调用它们的特定方法
下面的代码将在加载文件对象时向文件对象添加url
属性
File.observe('loaded', function(ctx, next) {
var baseUrl = 'http://example.com/uploads/files/';
ctx.data.url = baseUrl + data.id + data.filename;
next();
});
当直接在JS中或通过HTTP API间接调用下面的任何方法时,都会调用此函数
- 查找()
- 芬顿()
- findById()
- 存在()
- 计数()
- 创建()
- upsert()(与UPDATEORCEATE()相同)
- findOrCreate()
- prototype.save()
- prototype.updateAttributes()
- 通路
- 保存前
- 保存后
- 删除前
- 删除后
- 装载
- 坚持
url
属性
File.observe('loaded', function(ctx, next) {
var baseUrl = 'http://example.com/uploads/files/';
ctx.data.url = baseUrl + data.id + data.filename;
next();
});
当直接在JS中或通过HTTP API间接调用下面的任何方法时,都会调用此函数
- 查找()
- 芬顿()
- findById()
- 存在()
- 计数()
- 创建()
- upsert()(与UPDATEORCEATE()相同)
- findOrCreate()
- prototype.save()
- prototype.updateAttributes()
- 通路
- 保存前
- 保存后
- 删除前
- 删除后
- 装载
- 坚持
url
属性
File.observe('loaded', function(ctx, next) {
var baseUrl = 'http://example.com/uploads/files/';
ctx.data.url = baseUrl + data.id + data.filename;
next();
});
当直接在JS中或通过HTTP API间接调用下面的任何方法时,都会调用此函数
- 查找()
- 芬顿()
- findById()
- 存在()
- 计数()
- 创建()
- upsert()(与UPDATEORCEATE()相同)
- findOrCreate()
- prototype.save()
- prototype.updateAttributes()
- 通路
- 保存前
- 保存后
- 删除前
- 删除后
- 装载
- 坚持
url
属性
File.observe('loaded', function(ctx, next) {
var baseUrl = 'http://example.com/uploads/files/';
ctx.data.url = baseUrl + data.id + data.filename;
next();
});
当直接在JS中或通过HTTP API间接调用下面的任何方法时,都会调用此函数
- 查找()
- 芬顿()
- findById()
- 存在()
- 计数()
- 创建()
- upsert()(与UPDATEORCEATE()相同)
- findOrCreate()
- prototype.save()
- prototype.updateAttributes()
- 通路
- 保存前
- 保存后
- 删除前
- 删除后
- 装载
- 坚持