美文网首页
Feathers 服务 Services

Feathers 服务 Services

作者: 时见疏星 | 来源:发表于2019-10-07 22:55 被阅读0次

    服务是每个Feathers应用程序的核心。我们将更多地介绍服务并更新聊天应用程序中的现有用户服务以包含头像图像。

    服务

    通常,服务是实现某些方法的类的对象或实例。服务提供统一的,独立于协议的界面,用于如何与任何类型的数据进行交互,例如:

    • 从数据库中读取和/或写入
    • 与文件系统交互
    • 调用另一个API
    • 打电话给其他服务
      • 发送电子邮件
      • 处理付款
      • 返回当前天气的位置等

    独立于协议意味着对于Feathers服务而言,通过REST API,websockets,在我们的应用程序内部或任何其他方式调用它并不重要。

    服务方法

    服务方法是服务可以实现的CRUD方法。羽毛服务方​​法有:

    • find - 查找所有数据(可能与查询匹配)
    • get - 通过其唯一标识符获取单个数据条目
    • create - 创建新数据
    • update - 通过完全替换现有数据条目来更新它
    • patch - 通过合并新数据更新一个或多个数据条目
    • remove - 删除一个或多个现有数据条目

    下面是作为类和普通对象的Feathers服务接口的示例:

    class MyService {
      async find(params) {}
      async get(id, params) {}
      async create(data, params) {}
      async update(id, data, params) {}
      async patch(id, data, params) {}
      async remove(id, params) {}
    }
    
    app.use('/my-service', new MyService());
    

    服务方法的参数是:

    • id - 数据的唯一标识符
    • data - 用户发送的数据(用于创建,更新和修补)
    • params(可选) - 其他参数,例如经过身份验证的用户或查询

    注意:服务不必实现所有这些方法,但必须至少有一个。

    注册服务

    正如我们所看到的,通过使用名称和服务实例调用app.use(name,service),可以在Feathers应用程序上注册服务:

    const app = feathers();
    
    // Register the message service on the Feathers application
    app.use('messages', new MessageService());
    

    要获取服务对象并使用服务方法(和事件),我们可以使用app.service(name)

    const messageService = app.service('messages');
    const messages = await messageService.find();
    

    Service Event

    注册服务将自动成为NodeJS EventEmitter,当修改数据(create, update, patch and remove)的服务方法返回时,它会使用新数据发送事件。可以通过app.service('messages').on('eventName', data => {})收听事件。以下是服务方法及其相应事件的列表

    这是Feathers 做 real-time 和如何自动的更新消息通过 app.service('messages').on('created').

    相关文章

      网友评论

          本文标题:Feathers 服务 Services

          本文链接:https://www.haomeiwen.com/subject/jxmvyctx.html