Feathers生成器(CLI)

到目前为止,我们在一个文件中手动编写代码,以便更好地了解Feathers本身的工作原理. Feathers CLI允许我们使用推荐的结构初始化新的Feathers应用程序.它也有帮助

  • 配置验证

  • 生成数据库支持的服务

  • 设置数据库连接

  • 生成钩子(带测试)

  • 添加Express中间件

在本章中,我们将介绍如何安装CLI以及生成器用于构建服务器应用程序的常用模式. CLI的进一步使用将在 创建聊天应用程序 中讨论.

安装CLI

CLI应该通过npm全局安装:

npm install @feathersjs/cli -g

一旦成功,我们现在应该在命令行上提供 feathers 命令,我们可以查看:

feathers --version

哪个应该显示 3.8.2 或更高版本.

配置功能

生成的应用程序中使用的最常见模式是 configure functions,这些函数采用Feathers 应用 然后使用它,例如:注册服务.然后将这些函数传递给 .configure(callback).

让我们来看看 数据库:

const feathers = require('@feathersjs/feathers');
const memory = require('feathers-memory');

const app = feathers();

app.use('messages', memory({
  paginate: {
    default: 10,
    max: 25
  }
}));

可以使用像这样的配置功能拆分:

const feathers = require('@feathersjs/feathers');
const memory = require('feathers-memory');

const configureMessages = function(app) {
  app.use('messages', memory({
    paginate: {
      default: 10,
      max: 25
    }
  }));
};

const app = feathers();

app.configure(configureMessages);

现在我们可以将该函数移动到一个单独的文件,如 messages.service.js,并将其设置为该文件的 默认模块导出:

const memory = require('feathers-memory');

module.exports = function(app) {
  app.use('messages', memory({
    paginate: {
      default: 10,
      max: 25
    }
  }));
};

然后将其导入 app.js 并使用它:

const feathers = require('@feathersjs/feathers');
const configureMessages = require('./messages.service.js');

const app = feathers();

app.configure(configureMessages);

这是生成器如何将事物拆分为单独文件的最常见模式,并且任何使用 app 对象的文档示例都可以在configure函数中使用.您可以创建自己的文件,在 app.js 中导出configure函数和 requireapp.configure 它们

注解

请记住,调用configure函数的顺序可能很重要,例如如果它正在使用服务,则必须首先注册该服务.

钩子功能

我们已经在 钩子 中看到了如何创建一个包装器函数,它允许使用 setTimestamp 示例自定义钩子的选项:

const setTimestamp = name => {
  return async context => {
    context.data[name] = new Date();

    return context;
  }
}

app.service('messages').hooks({
  before: {
    create: setTimestamp('createdAt'),
    update: setTimestamp('updatedAt')
  }
});

这也是钩子生成器使用的模式,但在它自己的文件中,如 hooks/set-timestamp.js,它们看起来像这样:

module.exports = ({ name }) => {
  return async context => {
    context.data[name] = new Date();

    return context;
  }
}

现在我们可以使用这样的钩子:

const setTimestamp = require('./hooks/set-timestamp.js');

app.service('messages').hooks({
  before: {
    create: setTimestamp({ name: 'createdAt' }),
    update: setTimestamp({ name: 'updatedAt' })
  }
});

注解

我们在这里使用了一个选项对象,它允许我们更容易地添加新的选项而不是函数参数.

下一步是什么?

在本章中,我们安装了Feathers CLI(和生成器),并查看了用于构造生成的应用程序的模式.现在我们可以使用生成器 创建聊天应用程序 完成身份验证和JavaScript前端!