我正在学习FeathersJS,到目前为止,我希望流星是什么样子。继续好好表现!
现在,我正在通过聊天应用教程进行工作,但遇到了一些混乱。我不太明白本教程的本节中发生了什么,特别是本节中的populate钩子
'use strict';
const { authenticate } = require('feathers-authentication').hooks;
const { populate } = require('feathers-hooks-common');
const processMessage = require('../../hooks/process-message');
module.exports = {
before: {
all: [ authenticate('jwt') ],
find: [],
get: [],
create: [ processMessage() ],
update: [ processMessage() ],
patch: [ processMessage() ],
remove: []
},
after: {
all: [
// What's the purpose of this ?
populate({
schema: {
include: [{
service: 'users',
nameAs: 'user',
parentField: 'userId',
childField: '_id'
}]
}
})
],
find: [],
get: [],
create: [],
update: [],
patch: [],
remove: []
},
error: {
all: [],
find: [],
get: [],
create: [],
update: [],
patch: [],
remove: []
}
};这是process-message.js
'use strict';
// Use this hook to manipulate incoming or outgoing data.
// For more information on hooks see: http://docs.feathersjs.com/api/hooks.html
module.exports = function() {
return function(hook) {
// The authenticated user
const user = hook.params.user;
// The actual message text
const text = hook.data.text
// Messages can't be longer than 400 characters
.substring(0, 400)
// Do some basic HTML escaping
.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
// Override the original data
hook.data = {
text,
// Set the user id
userId: user._id,
// Add the current time via `getTime`
createdAt: new Date().getTime()
};
// Hooks can either return nothing or a promise
// that resolves with the `hook` object for asynchronous operations
return Promise.resolve(hook);
};
};我了解到,在对消息服务执行create、update或patch之前,数据被发送到processMessage(),processMessage()对数据进行消毒并向其添加用户ID。
问题
processMessage()之后,是否立即将数据写入数据库?after钩子,对吗?populate挂钩的目的是什么?谢谢:)
发布于 2017-05-02 09:11:48
更好地理解羽毛上的钩子和其他酷的东西。做一些基本日志是很好的。不管怎么说,这就是流动。
客户端->在所有钩子->之前(创建、更新、.) ->数据库->错误钩子(注意:只有在前面步骤有错误时才有错误) ->在(创建、更新、.) ->过滤器客户端之后的-> ->
至于填充钩子,它在数据库中执行populate的相同用途。羽毛是为你做的,而不是你做的填充查询。
基于您的示例,您希望您的模式中有类似的内容;
{
...,
userId : [{ type: <theType>, ref: 'users' }]
}您希望添加另一个字段,名为user,然后使用来自users服务的数据填充它,并将其_id与userId匹配。
发布于 2017-11-10 14:50:03
填充钩是由羽毛钩-普通模块提供的钩子之一.它的功能是在加入数据库中的各种表后提供数据。因为每个表都由一个单独的服务表示,所以您可以想到调用填充钩子的服务和另一个服务之间的连接。因此,在下面的代码中,模式对象被传递给填充钩子:
populate({
schema: {
include: [{
service: 'users',
nameAs: 'user',
parentField: 'userId',
childField: '_id'
}]
}
})它基本上是告诉钩子包含来自“用户”服务的数据。它还告诉它将附加数据命名为“用户”。它是说连接的parentField (即带有钩子的服务中的字段(在您的例子中是消息服务)是'userId‘。它的意思是连接的childField (即‘用户’服务中的字段是'_id‘。
当接收到数据时,它将拥有messages表中的所有字段和来自users表的带有key和key、值对的附加对象。
https://stackoverflow.com/questions/43725099
复制相似问题