Git Product home page Git Product logo

Comments (3)

popomore avatar popomore commented on April 19, 2024

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

from egg.

dead-horse avatar dead-horse commented on April 19, 2024

提供一个 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);
}

from egg.

dead-horse avatar dead-horse commented on April 19, 2024

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

from egg.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.