Feathers-Hooks-Common 使用教程
项目介绍
feathers-hooks-common
是一个为 Feathers.js 框架提供通用钩子(hooks)的库。Feathers.js 是一个轻量级的 REST 和实时 API 的框架,而 feathers-hooks-common
扩展了其功能,提供了许多常用的钩子,帮助开发者更高效地处理业务逻辑。
项目快速启动
安装
首先,确保你已经安装了 Feathers.js。然后,通过 npm 安装 feathers-hooks-common
:
npm install feathers-hooks-common --save
基本使用
以下是一个简单的示例,展示如何在 Feathers 服务中使用 feathers-hooks-common
提供的钩子:
const feathers = require('@feathersjs/feathers');
const memory = require('feathers-memory');
const { discard, populate } = require('feathers-hooks-common');
const app = feathers();
// 设置一个内存存储的服务
app.use('messages', memory());
// 获取服务并添加钩子
const messageService = app.service('messages');
messageService.hooks({
before: {
create: [
// 丢弃请求中的 `password` 字段
discard('password')
]
},
after: {
find: [
// 填充关联数据
populate({
schema: {
include: [{
service: 'users',
nameAs: 'user',
parentField: 'userId',
childField: '_id'
}]
}
})
]
}
});
// 启动应用
app.listen(3000, () => {
console.log('Feathers app started on localhost:3000');
});
应用案例和最佳实践
案例1:数据验证和清理
使用 feathers-hooks-common
中的 validate
和 discard
钩子进行数据验证和清理:
const { validate, discard } = require('feathers-hooks-common');
const validateSchema = {
title: 'string',
content: 'string',
createdAt: 'date'
};
app.service('posts').hooks({
before: {
create: [
validate(validateSchema),
discard('createdAt') // 丢弃不需要的字段
]
}
});
案例2:权限控制
使用 feathers-hooks-common
中的 iff
和 disallow
钩子进行权限控制:
const { iff, disallow } = require('feathers-hooks-common');
app.service('users').hooks({
before: {
update: [
iff(
context => !context.params.user || context.params.user.role !== 'admin',
disallow('external')
)
]
}
});
典型生态项目
feathers-hooks-common
是 Feathers.js 生态系统中的一个重要组成部分。以下是一些与 feathers-hooks-common
配合使用的典型生态项目:
- feathers-mongoose: 用于与 MongoDB 集成。
- feathers-authentication: 用于用户认证。
- feathers-permissions: 用于权限管理。
这些项目与 feathers-hooks-common
结合使用,可以构建出功能强大且灵活的 API 服务。