使用视图引擎

由于Feathers只是Express的扩展,因此使用Feathers服务中的数据在服务器上呈现模板化视图非常简单.您可以通过几种不同的方式构建应用程序,因此本指南将向您展示3种典型的方式,您可以组织您的Feathers应用程序.

单个“单片”应用程序

您可能已经知道,当您注册Feathers服务时,Feathers会自动为该服务创建RESTful端点.嗯,真的那些只是Express路线,所以你也可以定义自己的路线.

小技巧

您自己定义的REST端点不能与钩子一起使用,也不会发出套接字事件.如果您发现需要该功能,最好将端点转换为最小的Feathers服务.

假设您要使用Jade模板引擎呈现从最新到最旧的消息列表.

// You've set up your main Feathers app already

// Register your view engine
app.set('view engine', 'jade');

// Register your message service
app.use('/api/messages', memory());

// Inside your main Feathers app
app.get('/messages', function(req, res, next){
  // You namespace your feathers service routes so that
  // don't get route conflicts and have nice URLs.
  app.service('api/messages')
    .find({ query: {$sort: { updatedAt: -1 } } })
    .then(result => res.render('message-list', result.data))
    .catch(next);
});

简单吧?我们现在已经呈现了一个消息列表.所有挂钩都会像通常一样被触发,因此您可以使用挂钩预先过滤数据,并使模板渲染路线保持超紧.

小技巧

如果你在内部调用一个Feathers服务(即不通过套接字或REST)你将没有 context.params.provider 属性.这允许您只在外部调用服务而不是从您自己的代码调用服务时执行钩子.

Feathers 作为子应用程序

有时,分解您的Feathers应用程序的更好方法是将您的服务放入API并将您的API作为子应用程序安装.这就像你使用Express一样.如果您这样做,从您的服务获取数据只是一个小小的改变.

// You've set up your main Feathers app already

// Register your view engine
app.set('view engine', 'jade');

// Require your configured API sub-app
const api = require('./api');

// Register your API sub app
app.use('/api', api);

app.get('/messages', function(req, res, next){
  api.service('messages')
    .find({ query: {$sort: { updatedAt: -1 } } })
    .then(result => res.render('message-list', result.data))
    .catch(next);
});

不是很多不同.您的API子应用程序与前一个示例中的单个应用程序几乎相同,而您的主要Feathers应用程序只是一个非常小的包装器,它只能渲染模板.

Feathers 作为一个单独的应用程序

如果您的应用程序开始变得更加繁忙,您可能决定将API移动到完全独立的独立Feathers应用程序,甚至可能在不同的服务器上.为了让两个应用程序相互通信,他们需要一些方法来进行远程请求.好吧,Feathers恰好有一个 Feathers 客户端 可以在服务器上使用.这是它的工作原理.

// You've set up your feathers app already

// Register your view engine
app.set('view engine', 'jade');

// Include the Feathers client modules
const client = require('@feathersjs/client');
const socketio = require('@feathersjs/socketio-client');
const io = require('socket.io-client');

// Set up a socket connection to our remote API
const socket = io('http://api.feathersjs.com');
const api = client().configure(socketio(socket));

app.get('/messages', function(req, res, next){
  api.service('messages')
    .find({ query: {$sort: { updatedAt: -1 } } })
    .then(result => res.render('message-list', result.data))
    .catch(next);
});

小技巧

在上面的例子中,我们设置了套接字.或者你可以使用Feathers客户端 REST客户端.

有了它,我们已经展示了3种不同的方法,您可以使用带有Feathers的模板引擎来呈现服务数据.