Feathers-Hooks-Common 使用教程

Feathers-Hooks-Common 使用教程

feathers-hooks-commonUseful hooks for use with FeathersJS services.项目地址:https://gitcode.com/gh_mirrors/fe/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 中的 validatediscard 钩子进行数据验证和清理:

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 中的 iffdisallow 钩子进行权限控制:

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 配合使用的典型生态项目:

  1. feathers-mongoose: 用于与 MongoDB 集成。
  2. feathers-authentication: 用于用户认证。
  3. feathers-permissions: 用于权限管理。

这些项目与 feathers-hooks-common 结合使用,可以构建出功能强大且灵活的 API 服务。

feathers-hooks-commonUseful hooks for use with FeathersJS services.项目地址:https://gitcode.com/gh_mirrors/fe/feathers-hooks-common

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

吕真想Harland

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值