Rest API Node Js&Express,创build链接(href)给自己

目前我正在使用Node JS&Express中的REST API。 我必须为API中的每个资源创build一个链接,就像以上的例子。

{ "id": "20281", "title": "test", "body": "test", "date": "2017-11-14 09:01:35", "_links": { "self": { "href": "https://docent.cmi.hro.nl/bootb/demo/notes/20281" }, "collection": { "href": "https://docent.cmi.hro.nl/bootb/demo/notes/" } } }, 

我知道我可以在我的控制器中处理这个,因为req对象是可用的。 但是最好在我的模型中创build一个虚拟字段,以便dynamic地创build链接,而不是将其保存在数据库中。

什么是最好的方法来做到这一点?

DB: MongoDB ODM: Mongoose

有很多方法可以做到这一点,而且你还没有描述你的数据库或者ORM之类的东西,但是暗示你有一些与你的术语有关的东西。

要做的最简单的事情就是假设这不是存储的问题,而是全局应用于api的东西,这样所有的路由都被应用了。 这可能是中间件的forms:

 router.use((req, res, next) => { if (res.data) { // if you do it this way, none of your routes will actually do a res.send, but instead will put their data into res.data and rely on another middleware to render or send it res.data._links = { self: calculateSelf(req, res.data), collection: calculateCollection(req, res.data) }; } }); 

因此,这两个链接计算器可以使用一些标准模式或正则expression式来弄清楚链接应该看起来像一般。

或者,如果您使用的是Mongoose,则可以重写toJSON来填充任何您希望发送的模型中的链接,但这意味着您的模型应该知道根应用程序URL是什么,而不是推荐。

虚拟现场实施:

 YourSchema.virtual('links').get(() => { return { self: 'http://example.com/api/v1.0/schema/' + this._id, collection: 'http://example.com/api/v1.0/schema/' }; }); 

为了达到这个目的,你必须将{ virtuals: true }传递给toObject()或者toJSON()或者将其设置为一个全局mongooseconfiguration来显示虚拟。 正如我以前所说,我真的不会build议,因为它需要模式有权访问和知识的基础URL,它可以改变环境之间。 如果(正如你的模式所暗示的)模型代表一个网页,那么URL模板可能是与模型实际相关的东西,但是在大多数情况下,情况并非如此,所以我build议使用中间件方法。

如果你正在使用mongoose,你可以使用虚拟属性来创build一个非持久化字段,下面是一个例子:

 var MySchema = new Schema({ id: Number, title: String, body: String, date: Date }); MySchema.virtual('links').get(function () { return { self: { href: 'https://docent.cmi.hro.nl/bootb/demo/notes/' + this.id }, collection: { href: 'https://docent.cmi.hro.nl/bootb/demo/notes' } } }); var My = mongoose.model('My', MySchema); 

或者你可以用find后find中间件( post hooks ),例如:

 var MySchema = new Schema({ id: Number, title: String, body: String, date: Date }); MySchema.post('find', function(doc) { doc.links = { self: { 'href': 'https://docent.cmi.hro.nl/bootb/demo/notes/' + doc.id }, collection: { 'href': 'https://docent.cmi.hro.nl/bootb/demo/notes/' } } }); var My = mongoose.model('My', MySchema);