diff --git a/packages/core/strapi/lib/Strapi.js b/packages/core/strapi/lib/Strapi.js index ec417420e5..966b1b615c 100644 --- a/packages/core/strapi/lib/Strapi.js +++ b/packages/core/strapi/lib/Strapi.js @@ -8,6 +8,7 @@ const { Database } = require('@strapi/database'); const loadConfiguration = require('./core/app-configuration'); const { createHTTPServer } = require('./server'); +const { createContainer } = require('./container'); const loadModules = require('./core/load-modules'); const utils = require('./utils'); const bootstrap = require('./core/bootstrap'); @@ -32,6 +33,8 @@ const LIFECYCLES = { class Strapi { constructor(opts = {}) { + this.container = createContainer(this); + this.dir = opts.dir || process.cwd(); this.config = loadConfiguration(this.dir, opts); diff --git a/packages/core/strapi/lib/container.js b/packages/core/strapi/lib/container.js new file mode 100644 index 0000000000..024ef1b735 --- /dev/null +++ b/packages/core/strapi/lib/container.js @@ -0,0 +1,45 @@ +'use strict'; + +const createContainer = strapi => { + const registerd = new Map(); + const resolved = new Map(); + + return { + register(name, resolver) { + if (registerd.has(name)) { + throw new Error(`Cannot register already registered service ${name}`); + } + + registerd.set(name, resolver); + return this; + }, + + get(name, args) { + // TODO: handle singleton vs reinstanciation everytime + if (resolved.has(name)) { + return resolved.get(name); + } + + if (registerd.has(name)) { + const resolver = registerd.get(name); + + if (typeof resolver === 'function') { + resolved.set(name, resolver({ strapi }, args)); + } else { + resolved.set(name, resolver); + } + + return resolved.get(name); + } + + throw new Error(`Could not resovle service ${name}`); + }, + + // TODO: implement + extend() {}, + }; +}; + +module.exports = { + createContainer, +};