Databases

In the services chapter we created a custom in-memory messages service that can create, update and delete messages. You can probably imagine how we could implement the same thing using a database instead of storing the messages in memory so there isn’t really a database that Feathers doesn’t support.

Writing all that code yourself is pretty repetitive and cumbersome though which is why Feathers has a collection of pre-built services for different databases. They offer most the basic functionality and can always be fully customized to your requirements using hooks. Feathers database adapters support a common usage API, pagination and querying syntax for many popular databases and NodeJS ORMs:

Database Adapter
In memory feathers-memory, feathers-nedb
Localstorage, AsyncStorage feathers-localstorage
Filesystem feathers-nedb
MongoDB feathers-mongodb, feathers-mongoose
MySQL, PostgreSQL, MariaDB, SQLite, MSSQL feathers-knex, feathers-sequelize
Elasticsearch feathers-elasticsearch
RethinkDB feathers-rethinkdb

Pro tip: Each one of the linked adapters has a complete REST API example in their readme.

In this chapter we will look at the basic usage of the in-memory database adapter.

Important: You should be familiar with the database technology and ORM (Sequelize, KnexJS or Mongoose) before using a Feathers database adapter.

An in-memory database

feathers-memory is a Feathers database adapter that - similar to our messages service - stores its data in memory. We will use it for the examples because it also works in the browser. Let’s install it with:

  1. npm install feathers-memory --save

We can use the adapter by requiring it and initializing it with the options we want. Here we enable pagination showing 10 entries by default and a maximum of 25 (so that clients can’t just request all data at once and crash our server):

  1. const feathers = require('@feathersjs/feathers');
  2. const memory = require('feathers-memory');
  3. const app = feathers();
  4. app.use('messages', memory({
  5. paginate: {
  6. default: 10,
  7. max: 25
  8. }
  9. }));

That’s it. We have a complete CRUD service for our messages with querying functionality.

In the browser

We can also include feathers-memory in the browser, most easily by loading its browser build which will add it as feathers.memory. In public/index.html:

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Feathers Basics</title>
  6. </head>
  7. <body>
  8. <h1>Welcome to Feathers</h1>
  9. <p>Open up the console in your browser.</p>
  10. <script type="text/javascript" src="//unpkg.com/@feathersjs/client@^3.0.0/dist/feathers.js"></script>
  11. <script type="text/javascript" src="//unpkg.com/feathers-memory@^2.0.0/dist/feathers-memory.js"></script>
  12. <script src="client.js"></script>
  13. </body>
  14. </html>

And public/client.js:

  1. const app = feathers();
  2. app.use('messages', feathers.memory({
  3. paginate: {
  4. default: 10,
  5. max: 25
  6. }
  7. }));

Querying

As mentioned, all database adapters support a common way of querying the data in a find method call using params.query. You can find a complete list in the querying syntax API.

With pagination enabled, the find method will return an object with the following properties:

  • data - The current list of data
  • limit - The page size
  • skip - The number of entries that were skipped
  • total - The total number of entries for this query

The following example automatically creates a couple of messages and makes some queries. You can add it at the end of both app.js and public/client.js to see it in Node and the browser:

  1. async function createAndFind() {
  2. // Stores a reference to the messages service so we don't have to call it all the time
  3. const messages = app.service('messages');
  4. for(let counter = 0; counter < 100; counter++) {
  5. await messages.create({
  6. counter,
  7. message: `Message number ${counter}`
  8. });
  9. }
  10. // We show 10 entries by default. By skipping 10 we go to page 2
  11. const page2 = await messages.find({
  12. query: { $skip: 10 }
  13. });
  14. console.log('Page number 2', page2);
  15. // Show 20 items per page
  16. const largePage = await messages.find({
  17. query: { $limit: 20 }
  18. });
  19. console.log('20 items', largePage);
  20. // Find the first 10 items with counter greater 50 and less than 70
  21. const counterList = await messages.find({
  22. query: {
  23. counter: { $gt: 50, $lt: 70 }
  24. }
  25. });
  26. console.log('Counter greater 50 and less than 70', counterList);
  27. // Find all entries with text "Message number 20"
  28. const message20 = await messages.find({
  29. query: {
  30. message: 'Message number 20'
  31. }
  32. });
  33. console.log('Entries with text "Message number 20"', message20);
  34. }
  35. createAndFind();

As a REST API

In the REST API chapter we created a REST API from our custom messages service. Using a database adapter instead will make our app.js a lot shorter:

  1. const feathers = require('@feathersjs/feathers');
  2. const express = require('@feathersjs/express');
  3. const memory = require('feathers-memory');
  4. const app = express(feathers());
  5. // Turn on JSON body parsing for REST services
  6. app.use(express.json())
  7. // Turn on URL-encoded body parsing for REST services
  8. app.use(express.urlencoded({ extended: true }));
  9. // Set up REST transport using Express
  10. app.configure(express.rest());
  11. // Set up an error handler that gives us nicer errors
  12. app.use(express.errorHandler());
  13. // Initialize the messages service
  14. app.use('messages', memory({
  15. paginate: {
  16. default: 10,
  17. max: 25
  18. }
  19. }));
  20. // Start the server on port 3030
  21. const server = app.listen(3030);
  22. // Use the service to create a new message on the server
  23. app.service('messages').create({
  24. text: 'Hello from the server'
  25. });
  26. server.on('listening', () => console.log('Feathers REST API started at localhost:3030'));

After starting the server with node app.js we can pass a query e.g. by going to localhost:3030/messages?$limit=2.

Note: The querying syntax API documentation has more examples how URLs should look like.

What’s next?

Feathers database adapters are a quick way to get an API and up and running. The great thing is that hooks still give us all the flexibility we need to customize how they work. We already saw how we can easily create a database backed REST API, in the next chapter we will make our API real-time.