title: Plugin Development

Plugins is the most important feature in Egg framework. It keeps Egg simple, stable and efficient, and also it can make the best reuse of business logic, to build an entire ecosystem. Someone should be confused:

  • Since Koa already has the mechanism of middleware, what’s the point of the Egg’s plugins
  • What is the differences between middleware, plugin and application, what is the relationship
  • How can I use the plugin
  • How do I build a plugin

As we’ve already explained some these points in Chapter using plugins before. Now we are going through how to build a plugin.

Plugin Development

Quick Start with Scaffold

You can choose plugin scaffold in egg-init for quick start.

  1. $ egg-init --type=plugin egg-hello
  2. $ cd egg-hello
  3. $ npm i
  4. $ npm test

Directory of Plugin

Plugin is actually a ‘mini application’, directory of plugin is as below

  1. . egg-hello
  2. ├── package.json
  3. ├── app.js (optional)
  4. ├── agent.js (optional)
  5. ├── app
  6. ├── extend (optional)
  7. | ├── helper.js (optional)
  8. | ├── request.js (optional)
  9. | ├── response.js (optional)
  10. | ├── context.js (optional)
  11. | ├── application.js (optional)
  12. | └── agent.js (optional)
  13. ├── service (optional)
  14. └── middleware (optional)
  15. └── mw.js
  16. ├── config
  17. | ├── config.default.js
  18. ├── config.prod.js
  19. | ├── config.test.js (optional)
  20. | ├── config.local.js (optional)
  21. | └── config.unittest.js (optional)
  22. └── test
  23. └── middleware
  24. └── mw.test.js

It is almost the same as the application directory, what’s the difference?

  1. Plugin have no independant router or controller. This is because:

    • Usually routers are strongly bound to application, it is not fit here.
    • An application might have plenty of dependant plugins, routers of plugin are very possible conflict with others. It would be a disaster.
    • If you really need a general router, you should implement it as middleware of the plugin.
  2. The specific information of plugin should be declared in the package.json of eggPlugin

    • {String} name - plugin name(required), it must be unique, it will be used in the config of the dependencies of plugin.
    • {Array} dependencies - strong dependant plugins list of current plugin(if one of these plugins here is not found, application’s startup will be failed)
    • {Array} optionalDependencies - optional dependencies list of this plugin.(if these plugins are not activated, only warnings would be occurred, and will not affect the startup of the application).
    • {Array} env - this option is available only when specify the environment. The list of env please refer to env. This is optional, most time you can leave it.

      1. {
      2. "name": "egg-rpc",
      3. "eggPlugin": {
      4. "name": "rpc",
      5. "dependencies": [ "registry" ],
      6. "optionalDependencies": [ "vip" ],
      7. "env": [ "local", "test", "unittest", "prod" ]
      8. }
      9. }
  3. No plugin.js

    • eggPlugin.dependencies is for declaring dependencies only, not for importing, nor activating.
    • If you want to manage multiple plugins, you should do it inupper framework

Dependencies Management of Plugins

The dependencies are managed by plugin himself, this is different from middleware. Before loading plugins, application will read eggPlugin > dependencies and eggPlugin > optionalDependencies from package.json, and then sort out the loading orders according to their relationships, for example, the loading order of the following plugins is c => b => a

  1. // plugin a
  2. {
  3. "name": "egg-plugin-a",
  4. "eggPlugin": {
  5. "name": "a",
  6. "dependencies": [ "b" ]
  7. }
  8. }
  9. // plugin b
  10. {
  11. "name": "egg-plugin-b",
  12. "eggPlugin": {
  13. "name": "b",
  14. "optionalDependencies": [ "c" ]
  15. }
  16. }
  17. // plugin c
  18. {
  19. "name": "egg-plugin-c",
  20. "eggPlugin": {
  21. "name": "c"
  22. }
  23. }

Attention: The values in dependencies and optionalDependencies are the eggPlugin.name of plugins, not package.name.

The dependencies and optionalDependencies is studied from npm, most time we are using dependencies, it is recommended. There are about two situations to apply the optionalDependencies:

  • Only be dependant in specific environment: for example, a authentication plugin, only depends on the mock plugin in development environment.
  • Weakly depending, for example: A depends on B, but without B, A can take other choice

Pay attention: if you are using optionalDependencies, framework won’t verify the activation of these dependencies, they are only for sorting loading orders. In such situation, the plugin will go through other ways such as interface detection to decide processing logic.

What can plugin do

We’ve discussed what plugin is. Now what can it do?

Built-in Objects API Extension

Extend the built-in objects of the framework, just like the application

  • app/extend/request.js - extends Koa#Request object
  • app/extend/response.js - extends Koa#Response object
  • app/extend/context.js - extends Koa#Context object
  • app/extend/helper.js - extends Helper object
  • app/extend/application.js - extends Application object
  • app/extend/agent.js - extends Agent object

Insert Custom Middlewares

  1. First, define and implement middleware under directory app/middleware

    1. 'use strict';
    2. const staticCache = require('koa-static-cache');
    3. const assert = require('assert');
    4. const mkdirp = require('mkdirp');
    5. module.exports = (options, app) => {
    6. assert.strictEqual(typeof options.dir, 'string', 'Must set `app.config.static.dir` when static plugin enable');
    7. // ensure directory exists
    8. mkdirp.sync(options.dir);
    9. app.loggers.coreLogger.info('[egg-static] starting static serve %s -> %s', options.prefix, options.dir);
    10. return staticCache(options);
    11. };
  2. Insert middleware to the appropriate position in app.js(e.g. insert static middleware before bodyParser )

    1. const assert = require('assert');
    2. module.exports = app => {
    3. // insert static middleware before bodyParser
    4. const index = app.config.coreMiddleware.indexOf('bodyParser');
    5. assert(index >= 0, 'bodyParser highly needed');
    6. app.config.coreMiddleware.splice(index, 0, 'static');
    7. };

Initialization on Application Starting

  • If you want to read some local config before startup

    1. // ${plugin_root}/app.js
    2. const fs = require('fs');
    3. const path = require('path');
    4. module.exports = app => {
    5. app.customData = fs.readFileSync(path.join(app.config.baseDir, 'data.bin'));
    6. app.coreLogger.info('read data ok');
    7. };
  • If you want to do some async starting business, you can do it with app.beforeStart API

    1. // ${plugin_root}/app.js
    2. const MyClient = require('my-client');
    3. module.exports = app => {
    4. app.myClient = new MyClient();
    5. app.myClient.on('error', err => {
    6. app.coreLogger.error(err);
    7. });
    8. app.beforeStart(async () => {
    9. await app.myClient.ready();
    10. app.coreLogger.info('my client is ready');
    11. });
    12. };
  • You can add starting business of agent with agent.beforeStart API

    1. // ${plugin_root}/agent.js
    2. const MyClient = require('my-client');
    3. module.exports = agent => {
    4. agent.myClient = new MyClient();
    5. agent.myClient.on('error', err => {
    6. agent.coreLogger.error(err);
    7. });
    8. agent.beforeStart(async () => {
    9. await agent.myClient.ready();
    10. agent.coreLogger.info('my client is ready');
    11. });
    12. };

Setup Schedule Task

  1. Setup dependencies of schedule plugin in package.json

    1. {
    2. "name": "your-plugin",
    3. "eggPlugin": {
    4. "name": "your-plugin",
    5. "dependencies": [ "schedule" ]
    6. }
    7. }
  2. Create a new file in ${plugin_root}/app/schedule/ directory to edit your schedule task

    1. exports.schedule = {
    2. type: 'worker',
    3. cron: '0 0 3 * * *',
    4. // interval: '1h',
    5. // immediate: true,
    6. };
    7. exports.task = async ctx => {
    8. // your logic code
    9. };

Best Practice of Global Instance Plugin

Some plugins are made to introduce existing service into framework, like egg-mysql,egg-oss.They all need to create corresponding instance in application. We notice that there are some common problems when developing this kind of plugins:

  • Use different instances of the same service in one application(e.g:connect to two different MySQL Databases)
  • Dynamically initialize connection after getting config from other service(gets MySQL server address from configuration center and then creates connection)

If each plugin makes their own implementation, all sorts of configs and initializations will be chaotic. So the framework supplies the app.addSingleton(name, creator) API to unify the creation of this kind of services. Note that while using the app.addSingleton(name, creator) method, the configuration file must have the client or clients key configuration as the config to the creator function.

Writing Plugin

We simplify the egg-mysql plugin and to see how to write such a plugin:

  1. // egg-mysql/app.js
  2. module.exports = app => {
  3. // The first parameter mysql defines the field mounted to app, we can access MySQL singleton instance via `app.mysql`
  4. // The second parameter createMysql accepts two parameters (config, app), and then returns a MySQL instance
  5. app.addSingleton('mysql', createMysql);
  6. }
  7. /**
  8. * @param {Object} config The config which already processed by the framework. If the application configured multiple MySQL instances, each config would be passed in and call multiple createMysql
  9. * @param {Application} app the current application
  10. * @return {Object} return the created MySQL instance
  11. */
  12. function createMysql(config, app) {
  13. assert(config.host && config.port && config.user && config.database);
  14. // create instance
  15. const client = new Mysql(config);
  16. // check before start the application
  17. app.beforeStart(async () => {
  18. const rows = await client.query('select now() as currentTime;');
  19. app.coreLogger.info(`[egg-mysql] init instance success, rds currentTime: ${rows[0].currentTime}`);
  20. });
  21. return client;
  22. }

The initialization function also support Async function, convenient for some special plugins that need to be asynchronous to get some configuration files.

  1. async function createMysql(config, app) {
  2. // get mysql configurations asynchronous
  3. const mysqlConfig = await app.configManager.getMysqlConfig(config.mysql);
  4. assert(mysqlConfig.host && mysqlConfig.port && mysqlConfig.user && mysqlConfig.database);
  5. // create instance
  6. const client = new Mysql(mysqlConfig);
  7. // check before start the application
  8. const rows = await client.query('select now() as currentTime;');
  9. app.coreLogger.info(`[egg-mysql] init instance success, rds currentTime: ${rows[0].currentTime}`);
  10. return client;
  11. }

As you can see, all we need to do for this plugin is passing in the field that need to be mounted and the corresponding initialization function. Framework will be in charge of managing all the configs and the ways to access the instances.

Application Layer Usage Case

Single Instance
  1. Declare MySQL config in config file

    1. // config/config.default.js
    2. module.exports = {
    3. mysql: {
    4. client: {
    5. host: 'mysql.com',
    6. port: '3306',
    7. user: 'test_user',
    8. password: 'test_password',
    9. database: 'test',
    10. },
    11. },
    12. };
  2. Access database through app.mysql directly

    1. // app/controller/post.js
    2. class PostController extends Controller {
    3. async list() {
    4. const posts = await this.app.mysql.query(sql, values);
    5. },
    6. }
Multiple Instances
  1. Of course we need to configure MySQL in the config file, but different from single instance, we need to add clients in the config to declare the configuration of different instances. meanwhile, the default field can be used to configure the shared configuration in multiple instances(e.g. host and port). Note that in this case,should use get function to specify the corresponding instance(eg: use app.mysql.get('db1').query() instead of using app.mysql.query() directly to get a undefined).

    1. // config/config.default.js
    2. exports.mysql = {
    3. clients: {
    4. // clientId, access the client instance by app.mysql.get('clientId')
    5. db1: {
    6. user: 'user1',
    7. password: 'upassword1',
    8. database: 'db1',
    9. },
    10. db2: {
    11. user: 'user2',
    12. password: 'upassword2',
    13. database: 'db2',
    14. },
    15. },
    16. // default configuration for all databases
    17. default: {
    18. host: 'mysql.com',
    19. port: '3306',
    20. },
    21. };
  2. Access the corresponding instance by app.mysql.get('db1')

    1. // app/controller/post.js
    2. class PostController extends Controller {
    3. async list() {
    4. const posts = await this.app.mysql.get('db1').query(sql, values);
    5. },
    6. }
Dynamically Instantiate

Instead of declaring the configuration in the configuration file in advance, We can dynamically initialize an instance at the runtime of the application.

  1. // app.js
  2. module.exports = app => {
  3. app.beforeStart(async () => {
  4. // get MySQL config from configuration center { host, post, password, ... }
  5. const mysqlConfig = await app.configCenter.fetch('mysql');
  6. // create MySQL instance dynamically
  7. app.database = app.mysql.createInstanceAsync(mysqlConfig);
  8. });
  9. };

Access the instance through app.database

  1. // app/controller/post.js
  2. class PostController extends Controller {
  3. async list() {
  4. const posts = await this.app.database.query(sql, values);
  5. },
  6. }

Attention, when creating the instance dynamically, framework would read the default configuration in the config file as the default configuration

Plugin Locate Rule

When loading the plugins in the framework, it will follow the rules to locate them as below:

  • If there is the path configuration, load them in path directly
  • If there is no path configuration, search them with the package name, the search orders are:

    1. node_modules directory of the application root
    2. node_modules directory of the dependencies
    3. node_modules of current directory(generally for unit test compatibility)

Plugin Specification

We are very welcome your contribution to the new plugins, but also hope you follow some of following specifications:

  • Naming Rules
    • npm packages must append prefix egg-,and all letters must be lowercase,for example:egg-xxx. The long names should be concatenated with middle-lines:egg-foo-bar.
    • The corresponding plugin should be named in camel-case. The name should be translated according to the middle-lines of the npm name:egg-foo-bar => fooBar.
    • The use of middle-lines is not compulsive,for example:userservice(egg-userservice) and user-service(egg-user-service) are both acceptable.
  • package.json Rules

    • Add eggPlugin property according to the details discussed before.
    • For convenient index, add egg,egg-plugin,eggPlugin in keywords.

      1. {
      2. "name": "egg-view-nunjucks",
      3. "version": "1.0.0",
      4. "description": "view plugin for egg",
      5. "eggPlugin": {
      6. "name": "nunjucks",
      7. "dep": [
      8. "security"
      9. ]
      10. },
      11. "keywords": [
      12. "egg",
      13. "egg-plugin",
      14. "eggPlugin",
      15. "egg-plugin-view",
      16. "egg-view",
      17. "nunjucks"
      18. ],
      19. }

Why do not use the npm package name as the plugin name?

Egg defines the plugin name through the eggPlugin.name, it is only unique in application or framework, that means many npm packages might get the same plugin name, why design in this way?

First, Egg plugin do not only support npm package, it also supports search plugins in local directory. In Chapter progressive we mentioned how to make progress by using these two configurations. Directory is more friendly to unit test. So, Egg can not ensure uniqueness through npm package name.

What’s more, Egg can use this feature to make Adapter. For example, the plugin defined inTemplate Develop Spec was named as view, but there are plugins named egg-view-nunjucks and egg-view-react, the users only need to change the plugin and modify the templates, no need to modify the Controller, because all these plugins have implemented the same API.

Giving the same plugin name and the same API to the same plugin can make quick switch between them. This is really really useful in template and database.