Creating a Feathers Plugin

The easiest way to create a plugin is with the Yeoman generator.

First install the generator

  1. $ npm install -g generator-feathers-plugin

Then in a new directory run:

  1. $ yo feathers-plugin

This will scaffold out everything that is needed to start writing your plugin.

Output files from generator:

  1. create package.json
  2. create .babelrc
  3. create .editorconfig
  4. create .jshintrc
  5. create .travis.yml
  6. create src/index.js
  7. create test/index.test.js
  8. create README.md
  9. create LICENSE
  10. create .gitignore
  11. create .npmignore

Simple right? We technically could call it a day as we have created a Plugin. However, we probably want to do just a bit more. Generally speaking a Plugin is a Service. The fun part is that a Plugin can contain multiple Services which we will create below. This example is going to build out 2 services. The first will allow us to find members of the Feathers Core Team & the second will allow us to find the best state in the United States.

Verifying our Service

Before we start writing more code we need to see that things are working.

  1. $ cd example && node app.js
  2. Error: Cannot find module '../lib/index'

Dang! Running the example app resulted in an error and you said to yourself, “The generator must be broken and we should head over to the friendly Slack community to start our debugging journey”. Well, as nice as they may be we can get through this. Let’s take a look at the package.json that came with our generator. Most notably the scripts section.

  1. "scripts": {
  2. "prepublish": "npm run compile",
  3. "publish": "git push origin && git push origin --tags",
  4. "release:patch": "npm version patch && npm publish",
  5. "release:minor": "npm version minor && npm publish",
  6. "release:major": "npm version major && npm publish",
  7. "compile": "rimraf lib/ && babel -d lib/ src/",
  8. "watch": "babel --watch -d lib/ src/",
  9. "jshint": "jshint src/. test/. --config",
  10. "mocha": "mocha --recursive test/ --compilers js:babel-core/register",
  11. "test": "npm run compile && npm run jshint && npm run mocha",
  12. "start": "npm run compile && node example/app"
  13. }

Back in business. That error message was telling us that we need to build our project. In this case it means babel needs to do it’s thing.
For development you can run watch

  1. $ npm run watch
  2. > creatingPlugin@0.0.0 watch /Users/ajones/git/training/creatingPlugin
  3. > babel --watch -d lib/ src/
  4. src/index.js -> lib/index.js

After that you can run the example app and everything should be good to go.

  1. $ node app.js
  2. Feathers app started on 127.0.0.1:3030

Expanding our Plugin

Now that we did our verification we can safely change things. For this example we want 2 services to be exposed from our Plugin. Let’s create a services directory within the src folder.

  1. // From the src directory
  2. $ mkdir services
  3. $ ls
  4. index.js services

Now let’s create our two services. We will just copy the index.js file.

  1. $ cp index.js services/core-team.js
  2. $ cp index.js services/best-state.js
  3. $ cd services && ls
  4. best-state.js core-team.js
  5. $ cat best-state.js
  6. if (!global._babelPolyfill) { require('babel-polyfill'); }
  7. import errors from 'feathers-errors';
  8. import makeDebug from 'debug';
  9. const debug = makeDebug('creatingPlugin');
  10. class Service {
  11. constructor(options = {}) {
  12. this.options = options;
  13. }
  14. find(params) {
  15. return new Promise((resolve, reject) => {
  16. // Put some async code here.
  17. if (!params.query) {
  18. return reject(new errors.BadRequest());
  19. }
  20. resolve([]);
  21. });
  22. }
  23. }
  24. export default function init(options) {
  25. debug('Initializing creatingPlugin plugin');
  26. return new Service(options);
  27. }
  28. init.Service = Service;

At this point we have index.js, best-state.js and core-team.js with identical content. The next step will be to change index.js so that it is our main file.

Our new index.js

  1. if (!global._babelPolyfill) { require('babel-polyfill'); }
  2. import coreTeam from './services/core-team';
  3. import bestState from './services/best-state';
  4. export default { coreTeam, bestState };

Now we need to actually write the services. We will only be implementing the find action as you can reference the service docs to learn more. Starting with core-team.js we want to find out the names of the members listed in the feathers.js org on github.

  1. //core-team.js
  2. if (!global._babelPolyfill) { require('babel-polyfill'); }
  3. import errors from 'feathers-errors';
  4. import makeDebug from 'debug';
  5. const debug = makeDebug('creatingPlugin');
  6. class Service {
  7. constructor(options = {}) {
  8. this.options = options;
  9. }
  10. //We are only changing the find...
  11. find(params) {
  12. return Promise.resolve(['Mikey', 'Cory Smith', 'David Luecke', 'Emmanuel Bourmalo', 'Eric Kryski',
  13. 'Glavin Wiechert', 'Jack Guy', 'Anton Kulakov', 'Marshall Thompson'])
  14. }
  15. }
  16. export default function init(options) {
  17. debug('Initializing creatingPlugin plugin');
  18. return new Service(options);
  19. }
  20. init.Service = Service;

That will now return an array of names when service.find is called. Moving on to the best-state service we can follow the same pattern

  1. if (!global._babelPolyfill) { require('babel-polyfill'); }
  2. import errors from 'feathers-errors';
  3. import makeDebug from 'debug';
  4. const debug = makeDebug('creatingPlugin');
  5. class Service {
  6. constructor(options = {}) {
  7. this.options = options;
  8. }
  9. find(params) {
  10. return Promise.resolve(['Alaska']);
  11. }
  12. }
  13. export default function init(options) {
  14. debug('Initializing creatingPlugin plugin');
  15. return new Service(options);
  16. }
  17. init.Service = Service;

Notice in the above service it return a single item array with the best state listed.

Usage

The easiest way to use our plugin will be within the same app.js file that we were using earlier. Let’s write out some basic usage in that file.

  1. //app.js
  2. const feathers = require('feathers');
  3. const rest = require('feathers-rest');
  4. const hooks = require('feathers-hooks');
  5. const bodyParser = require('body-parser');
  6. const errorHandler = require('feathers-errors/handler');
  7. const plugin = require('../lib/index');
  8. // Initialize the application
  9. const app = feathers()
  10. .configure(rest())
  11. .configure(hooks())
  12. // Needed for parsing bodies (login)
  13. .use(bodyParser.json())
  14. .use(bodyParser.urlencoded({ extended: true }))
  15. // Initialize your feathers plugin
  16. .use('/plugin/coreTeam', plugin.coreTeam())
  17. .use('/plugin/bestState', plugin.bestState())
  18. .use(errorHandler());
  19. var bestStateService = app.service('/plugin/bestState')
  20. var coreTeamService = app.service('/plugin/coreTeam')
  21. bestStateService.find().then( (result) => {
  22. console.log(result)
  23. }).catch( error => {
  24. console.log('Error finding the best state ', error)
  25. })
  26. coreTeamService.find().then( (result) => {
  27. console.log(result)
  28. }).catch( error => {
  29. console.log('Error finding the core team ', error)
  30. })
  31. app.listen(3030);
  32. console.log('Feathers app started on 127.0.0.1:3030');
  1. $ node app.js
  2. Feathers app started on 127.0.0.1:3030
  3. [ 'Alaska' ]
  4. [ 'Mikey',
  5. 'Cory Smith',
  6. 'David Luecke',
  7. 'Emmanuel Bourmalo',
  8. 'Eric Kryski',
  9. 'Glavin Wiechert',
  10. 'Jack Guy',
  11. 'Anton Kulakov',
  12. 'Marshall Thompson' ]

Testing

Our generator stubbed out some basic tests. We will remove everything and replace it with the following.

  1. import { expect } from 'chai';
  2. import plugin from '../src';
  3. const bestStateService = plugin.bestState()
  4. describe('bestState', () => {
  5. it('is Alaska', () => {
  6. bestStateService.find().then(result => {
  7. console.log(result)
  8. expect(result).to.eql(['Alaska']);
  9. done();
  10. });
  11. });
  12. });
  1. $ npm run test

Because this is just a quick sample jshint might fail. You can either fix the syntax or change the test command.

  1. $ npm run compile && npm run mocha

This should give you the basic idea of creating a Plugin for Feathers.