数据库

服务 中, 我们创建了一个可以创建, 更新和删除消息的自定义内存中消息服务.您可以想象我们如何使用数据库实现相同的功能, 而不是将消息存储在内存中, 因此实际上没有Feathers不支持的数据库.

自己编写所有代码是非常重复和繁琐的,尽管这就是为什么Feathers为不同的数据库提供了一系列预构建服务.它们提供了大多数基本功能,并且可以使用 钩子 完全根据您的要求进行定制. Feathers数据库适配器支持一个常见的 通用API,分页 和 查询,用于许多流行的数据库和NodeJS ORM:

数据库

适配器

在内存中

feathers-memory, feathers-nedb

本地存储, 异步存储

feathers-localstorage

文件系统

feathers-nedb

MongoDB

feathers-mongodb, feathers-mongoose

MySQL, PostgreSQL, MariaDB, SQLite, MSSQL

feathers-knex, feathers-sequelize, feathers-objection

Elasticsearch

feathers-elasticsearch

RethinkDB

feathers-rethinkdb

小技巧

每个链接的适配器在其自述文件中都有一个完整的REST API示例.

在本章中, 我们将了解内存数据库适配器的基本用法.

重要

你应该熟悉数据库技术和ORM(Sequelize, KnexJSMongoose)在使用Feathers数据库适配器之前.

内存数据库

feathers-memory 是一个Feathers数据库适配器 - 类似于我们的消息服务 - 将其数据存储在内存中.我们将它用于示例, 因为它也可以在浏览器中使用.让我们安装它:

npm install feathers-memory --save

我们可以通过要求它并使用我们想要的选项初始化它来使用适配器.在这里, 我们启用分页, 默认显示10个条目, 最多25个(这样客户端不能只是一次请求所有数据并使我们的服务器崩溃):

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

const app = feathers();

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

而已.我们为具有查询功能的消息提供了完整的CRUD服务.

在浏览器中

我们还可以在浏览器中包含 feathers-memory, 最容易加载它的浏览器构建, 将其添加为 feathers.memory. 在 public/index.html 中:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Feathers Basics</title>
</head>
<body>
  <h1>Welcome to Feathers</h1>
  <p>Open up the console in your browser.</p>
  <script type="text/javascript" src="//unpkg.com/@feathersjs/client@^3.0.0/dist/feathers.js"></script>
  <script type="text/javascript" src="//unpkg.com/feathers-memory@^2.0.0/dist/feathers-memory.js"></script>
  <script src="client.js"></script>
</body>
</html>

public/client.js:

const app = feathers();

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

查询

如上所述, 所有数据库适配器都支持使用 params.queryfind 方法调用中查询数据的常用方法.您可以在以下位置找到完整列表 查询.

启用分页后, find 方法将返回具有以下属性的对象:

  • data - 当前的数据列表

  • limit - 页面大小

  • skip - 跳过的条目数

  • total - 此查询的条目总数

以下示例自动创建100条消息并进行一些查询.你可以在 app.jspublic/client.js 的末尾添加它, 以便在Node和浏览器中看到它:

async function createAndFind() {
  // Stores a reference to the messages service so we don't have to call it all the time
  const messages = app.service('messages');

  for(let counter = 0; counter < 100; counter++) {
    await messages.create({
      counter,
      message: `Message number ${counter}`
    });
  }

  // We show 10 entries by default. By skipping 10 we go to page 2
  const page2 = await messages.find({
    query: { $skip: 10 }
  });

  console.log('Page number 2', page2);

  // Show 20 items per page
  const largePage = await messages.find({
    query: { $limit: 20 }
  });

  console.log('20 items', largePage);

  // Find the first 10 items with counter greater 50 and less than 70
  const counterList = await messages.find({
    query: {
      counter: { $gt: 50, $lt: 70 }
    }
  });

  console.log('Counter greater 50 and less than 70', counterList);

  // Find all entries with text "Message number 20"
  const message20 = await messages.find({
    query: {
      message: 'Message number 20'
    }
  });

  console.log('Entries with text "Message number 20"', message20);
}

createAndFind();

作为REST API

REST APIs 中, 我们从自定义消息服务中创建了一个REST API.使用数据库适配器将使我们的 app.js 缩短很多:

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

const app = express(feathers());

// Turn on JSON body parsing for REST services
app.use(express.json())
// Turn on URL-encoded body parsing for REST services
app.use(express.urlencoded({ extended: true }));
// Set up REST transport using Express
app.configure(express.rest());

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

// Set up an error handler that gives us nicer errors
app.use(express.errorHandler());

// Start the server on port 3030
const server = app.listen(3030);

// Use the service to create a new message on the server
app.service('messages').create({
  text: 'Hello from the server'
});

server.on('listening', () => console.log('Feathers REST API started at localhost:3030'));

使用 node app.js 启动服务器后,我们可以传递查询,例如通过转到 localhost:3030/messages?$limit=2.

注解

查询 有更多示例URL的样子.

下一步是什么?

Feathers数据库适配器是启动和运行API的快捷方式.最棒的是 钩子 仍然为我们提供了定制工作方式所需的所有灵活性.我们已经看到了如何在以下文档中轻松创建数据库支持的REST API 实时API 我们将使我们的API实时化.