Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

统一多实例的插件创建方式,文档化提供最佳实践 #3

Closed
dead-horse opened this issue Jun 18, 2016 · 3 comments
Closed
Assignees
Milestone

Comments

@dead-horse
Copy link
Member

类似 oss / mysql 等都可能存在需要创建多个实例的需求,在插件里面现在有两种实现方式:

  1. 新增一个 createInstance 方法来自定义创建。
  2. 配置支持数组形式,然后通过 this.mysql.db1 来获取

对外的插件最好有一个统一的形式。特别是 aliyun-egg 估计会遇到挺多类似的问题

@dead-horse dead-horse added this to the v1.0 milestone Jun 18, 2016
@popomore
Copy link
Member

每个 client 的实例化方案都不一样,如何通过一个 API 搞定呢

@dead-horse
Copy link
Member Author

dead-horse commented Jun 21, 2016

提供一个 Singleton 类,所有的类似 oss / rds / mongo 这样的插件都继承于 Singleton

class Sigleton {
  constructor(opts) {
    this.clients = new Map();

    if (opts.clients) {
      for (const id in opts.clients) {
        this.set(id, this.create(opts.clients[id]));
      }
      return;
    }
  }

  get(id) {
    return this.clients.get(id);
  }

  set(id, client) {
  return this.clients.set(id, client);
  }

  create(config) {
    // 子类需要实现 create 方法    
  }
}

// lib/oss.js
const oss = require('ali-oss');
const Sigleton = require('egg-sigleton').;

class Oss extends Sigleton {
  constructor(opts) {
    super(opts);
  }

  create(config) {
    return oss(config);
  }
}

// app.js
const oss = require('./lib/oss');

module.exports = function (app) {
  app.oss = new Oss(app.config.oss);
  app.oss.set('cdn', app.oss.create(app.config.cdnOss));
  // or app.cdnOss = app.oss.create(app.config.cdnOss);
}

// services 中
get cdnOss() {
  return this.app.oss.get('cdnOss');
}

* upload(name, file) {
  yield this.cdnOss.upload(name, file);
}

@dead-horse
Copy link
Member Author

不过如果只有一个实例也要遵循这个方式...

elrrrrrrr pushed a commit to elrrrrrrr/egg that referenced this issue Feb 21, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants