Skip to content
This repository has been archived by the owner on Jul 23, 2019. It is now read-only.

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
moeriki committed Oct 9, 2017
1 parent e0df883 commit 9d9c161
Show file tree
Hide file tree
Showing 13 changed files with 601 additions and 0 deletions.
7 changes: 7 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
[*]
charset = utf-8
indent_style = space
indent_size = 2
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
8 changes: 8 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
module.exports = {
root: true,
extends: [
'muriki',
'muriki/env/common-js',
'muriki/es/2015',
],
};
63 changes: 63 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
# Created by https://www.gitignore.io/api/node

### Node ###
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage

# nyc test coverage
.nyc_output

# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# Typescript v1 declaration files
typings/

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variables file
.env

# End of https://www.gitignore.io/api/node
7 changes: 7 additions & 0 deletions .npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
.editorconfig
.eslintrc.js
.gitignore
.npmignore
.npmrc
.travis.yml
test/
1 change: 1 addition & 0 deletions .npmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
package-lock=false
24 changes: 24 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
language: "node_js"

node_js:
- "4"
- "6"
- "8"

install:
- "npm install"
- "npm install -D coveralls"

script:
- "npm run test:coverage"

after_success:
- "cat ./coverage/lcov.info | coveralls"

notifications:
email: false
slack:
rooms:
- moeriki:Gqf2TnMQj95R0y9cNLQhw6Eo#updates
on_success: change
on_failure: always
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2016 Dieter Luypaert

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
111 changes: 111 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
<p align="center">
<h3 align="center">depin 📦</h3>
<p align="center">A simple dependency injection container.<p>
<p align="center">
<a href="https://www.npmjs.com/package/depin">
<img src="https://img.shields.io/npm/v/depin.svg" alt="npm version">
</a>
<a href="https://david-dm.org/moeriki/depin">
<img src="https://david-dm.org/moeriki/depin/status.svg" alt="dependencies Status"></img>
</a>
<a href="https://snyk.io/test/github/moeriki/depin">
<img src="https://snyk.io/test/github/moeriki/depin/badge.svg" alt="Known Vulnerabilities"></img>
</a>
</p>
</p>

---

## Install

```sh
npm install --save depin
```

## Quick start

```js
const depin = require('depin');

const app = depin();

app.set('beatles', [
{ name: 'George' },
{ name: 'John' },
{ name: 'Paul' },
{ name: 'Ringo' },
]);

app.register('beatleService' (beatles) => ({
getCount() {
return beatles.length;
},
}));

app.get('beatleService').count(); // 4
```

## API


#### `apply( factory:function ) :*`

Run a function with all arguments injected from the DI container by name and return the result.

```js
app.set({ one: 1, two: 2, three: 3 });
app.apply((one, two, three) => one + two + three); // 6
```

#### `get( [name:string] ) :*`

Get a value from the DI container.

```js
app.set({ one: 1 });
app.get('one'); // value
```

When no name is passed `app.get` will return a dependency picker which is very useful when combined with object destructuring.

```js
app.set({ one: 1, two: 2 });
const { one, two } = app.get();
```

#### `register( factory:function ) :app`

Register a factory.

```js
app.set({ one: 1, two: 2 });
app.register(function myManager(one, two) {
return { add: () => one + two };
});
app.get('myManager').add(); // 3
```

Or set its name directly.

```js
app.set({ one: 1, two: 2 });
app.register('myManager', (one, two) => {
return { add: () => one + two };
});
app.get('myManager').add(); // 3
```

#### `run( func:function ) :app`

Run a function with all arguments injected from the DI container by name.

```js
app.set({ one: 1, two: 2 });
app.run((one, two) => {
//
});
```

#### `set( properties:object ) :app` / `set( name:string, value:* ):app`

Set values in the DI container.
128 changes: 128 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
'use strict';

const fnArgs = require('fn-args');

// exports

/**
* @param {object} app
* @return {object} with bottle functions
*/
function depinFactory() {

const container = {};
const depin = {};

// private

const pick = new Proxy(depin, {
get(target, property) {
return target.get(property);
},
});

// expose

Object.assign(depin, {

/**
* @param {function} func
* @return {*}
*/
apply(func) {
const dependencies = fnArgs(func);
return func(...dependencies.map(depin.get));
},

/**
* @param {string} [name]
* @return {*|Proxy} value or Proxy to pick values from
*/
get(name) {
if (name == null) {
return pick;
}
return container[name];
},

/**
* @param {string} [name]
* @param {function} factory
* @param {...*} [dependencies]
* @return {object} app
*/
register(...args) {
let dependencies, factory, name;

if (typeof args[0] === 'function') {
[factory] = args;
name = factory.$name || factory.name;
dependencies = args.slice(1);
} else {
[name, factory] = args;
dependencies = args.slice(2);
}

if (!name) {
throw new TypeError(
'Cannot register anonymous provider. Either name your provider, or pass a name argument while registering.'
);
}

if (dependencies.length === 0) {
dependencies = fnArgs(factory);
}

Object.defineProperty(container, name, {
get() {
return factory(...dependencies.map(depin.get));
},
});

return depin;
},

/**
* @param {function} func
* @return {object} app
*/
run(func) {
depin.apply(func);
return depin;
},

/**
* @param {string|object} nameOrValues
* @param {*} [value] only needed when first arg is name
* @return {object} app
* @example
* app.set('key1', 'value1');
* app.set({
* key2: 'value2',
* key3: 'value3',
* });
*/
set(nameOrValues, value) {
// option 1: args = [values:object]
if (typeof nameOrValues === 'object') {
const values = nameOrValues;
for (const name of Object.keys(values)) {
depin.set(name, values[name]);
}
return depin;
}
// option 2: args = [key:string, value:*]
const name = nameOrValues;
if (typeof name !== 'string') {
throw new TypeError(`Expected value key to be of type 'string'. Instead received '${typeof name}'.`);
}
container[name] = value;
return depin;
},

});

return depin;
}

module.exports = depinFactory;
Loading

0 comments on commit 9d9c161

Please sign in to comment.