Skip to content

Instantly share code, notes, and snippets.

@akshendra
Last active April 16, 2017 12:01
Show Gist options
  • Save akshendra/a2570d9b02412ba91b8ffbb963d5f86e to your computer and use it in GitHub Desktop.
Save akshendra/a2570d9b02412ba91b8ffbb963d5f86e to your computer and use it in GitHub Desktop.
'use strict';
/**
* =============================================================================================
* A state container
* @exports {Object} Continer
*
* // in the very beginning
* const con = require('container.js')
* con.add('logger', new Logger('log'));
* con.add('debug', new Logger('debug'));
*
* // some other place
* const con = require('container.js')
* const logger = con.get('logger');
* const debug = con.get('debug');
* =============================================================================================
*/
const is = require('is_js');
const emit = require('./emitter');
function emitError(type, error, data = {}) {
emit.error('container', type, error, data);
}
class Container {
/**
* @param {Object} data -> intialize with this data
*/
constructor(data) {
this.data = Object.assign({}, data);
this.IOC = Container;
}
/**
* It won't rewrite if the key already exists, use update
*/
add(key, value) {
if (is.not.undefined(this.data[key])) {
const error = new Error(`Can't add <${key}>, already existing`);
emitError('key', error, {
key,
});
throw error;
}
this.data = Object.assign(this.data, {
[key]: value,
});
}
get(key, silent) {
const value = this.data[key];
if (!silent && is.undefined(value)) {
const error = new Error(`No key <${key}> found`);
emitError('key', error, {
key,
});
throw error;
}
return value;
}
/**
* This will add or update
*/
set(key, value) {
this.data = Object.assign(this.data, {
[key]: value,
});
}
/**
* Unpack, just expose the data object
*/
unpack() {
return this.data;
}
}
module.exports = new Container();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment