Skip to content

Commit

Permalink
Merge pull request #1 from chris-pardy/v2
Browse files Browse the repository at this point in the history
Version 2
  • Loading branch information
chris-pardy authored Apr 26, 2018
2 parents 92d8164 + ab2ea02 commit 431aeba
Show file tree
Hide file tree
Showing 15 changed files with 4,759 additions and 599 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
/node_modules
yarn-error.log
/lib
3 changes: 0 additions & 3 deletions .npmignore

This file was deleted.

1 change: 1 addition & 0 deletions .nvmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
8
5 changes: 3 additions & 2 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
language: node_js
node_js:
- '7'
before_deploy:
- yarn package
- cd lib
deploy:
provider: npm
email: "[email protected]"
Expand Down
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2018 Christopher Pardy

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.
192 changes: 100 additions & 92 deletions ReadMe.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[![Build Status](https://travis-ci.org/chris-pardy/cider-di.svg?branch=master)](https://travis-ci.org/chris-pardy/cider-di)
# cider
Super simple dependency injection.
Super simple dependency inversion/injection for javascript.

## Installation
```npm install --save cider-di```
Expand All @@ -10,137 +10,145 @@ Super simple dependency injection.
const service = require('./service');
const database = require('./database');
const cider = require('cider-di');
const injector = cider(
(bind) => {
bind('service').to(cider.singleton((inject) => new service(inject('database'))));
}, (bind) => {
bind('database').to(cider.singleton((inject) => new database()));
});
const my_service = injector('service');
```
Cider uses named bindings to create a map of name to provider function.
Each provider function is supplied an injector which can be used to fetch dependencies.
const injector = cider.createInjector({
service: cider.singleton(
({database}) => new service(database)
),
database: cider.singleton(
() => new database()
)
});
const my_service = injector.dependencies.service;
```
Cider uses named bindings to create a map of name to *binding* function.
Each *binding* function is supplied 3 values.
* dependencies - an object where each key corresponds to provided value.
* providers - an object where each key corresponds to a *provider*.
* context - a javascript object that can be used for providers to communicate with each other.

## Components
### cider([...modules])
* `modules` [function](#modulebind)
### cider.createInjector(module)
* `module` [function](#Module)

Returns [`injector`](#Injector)

Takes 0 or more functions which act as module definitions, each module is passed an argument `bind` which is used to declare dependencies.

Takes 0 or more functions which act as module definitions, each module is passed
an argument `bind` which is used to declare dependencies. Returns an `injector`.
### cider.singleton(binding)
* `binding` [binding](#Bindingdependenciesproviderscontext)

### cider.singleton(provider)
* `provider` [function](#providerinjectargs)
Returns [binding](#Bindingdependenciesproviderscontext)

Given a provider function ensures that the function is only called once for each
injector instance that it's used from. Returns a `provider`.
Given a binding function ensures that the function is only called once for each injector instance that it's used from.
```
bind('my_service').to(cider.singleton((inject) => new service(inject('dependency'))));
my_service: cider.singleton(
({dependency}) => new service(dependency)
)
```

### cider.instance(value)
* `value` any

Given a value create a provider that will provide that value. Returns a `provider`.
Returns [`binding`](#Bindingdependenciesproviderscontext)

Given a value create a binding that will provide that value.
```
bind('should_run').to(cider.instance(false));
should_run: cider.instance(false)
```

### cider.alias(name)
* `name` string

Given a name creates a provider that provides the value bound to that name.
This acts as a way to alias bindings. Returns a `provider`.
Returns [`binding`](#Bindingdependenciesproviderscontext)

Given a name creates a binding that provides the value bound to that name. This acts as a way to alias bindings. Note that tags won't be transferred.
```
bind('database').to(cider.alias('postgres'));
database: cider.alias('postgres')
```

### cider.list(providers)
* `providers` array of [providers](#providernameargs)
### cider.tagged(tags, binding)
* `tags` string[],
* binding [`binding`](#Bindingdependenciesproviderscontext)

Given an array of providers creates a provider that returns a list of the bound
values, maintaining order. Returns a `provider`.
Returns [`binding`](#Bindingdependenciesproviderscontext)

Given a set of tags and a binding, returns a binding with the given set of tags appended to the tags on the given binding.
```
bind('options').to(cider.list([
cider.alias('should_run'),
cider.alias('is_production')
]));
stripe_processor: cider.tagged(
['payment_processor'],
cider.singleton(
() => new Stripe()
)
)
```

### cider.obj(providers)
* `providers` Object of [providers](#providernameargs)
### Module
#### properties
* [`name` string] [`binding`](#Bindingdependenciesproviderscontext)

Given an object containing a mapping of keys to providers, creates a provider that
returns an object with the bound values mapped to the keys. Returns a `provider`.
A module is a standard javascript object with a name mapped to a binding.
```
bind('options').to(cider.obj({
should_run: cider.alias('should_run'),
is_production: cider.alias('is_production')
}));
module.exports = {
database: () => new Database(),
service: cider.singleton(
({database}) => new Service(database)
)
}
```

### cider.override([...override_modules]).with([...with_modules])
* `override_modules` [function](#modulebind)
* `with_modules` [function](#modulebind)
### Binding(dependencies,providers,context)
* `dependencies` [object](#Dependencies)
* `providers` [object](#Providers)
* context object
#### properties
* `tags` optional string[]

Given 2 sets of modules allows `with_modules` to define bindings that have already
been defined by the `override_modules` overriding these values. Returns a `module`.
Returns any

A binding is given 3 values that can be used to get dependencies, and retuns the value of the dependency.
```
const my_module = (bind) => { bind('is_production').to(cider.instance(true)); };
const injector = cider(cider.override(
my_module, your_module
).with(
(bind) => {
bind('is_production').to(cider.instance(false));
})
);
some_binding: ({database},{query}, context) => {
if (context.should_run_query) {
return database.execute(query());
}
return null;
}
```

### injector(name[,...args])
* `name` string
* `args` any
### Dependencies
#### properties
* [`name` string] any

Given a name resolve the provider bound to the name and invoke it with the given args.
Returns the result of the provider.
```
const db = injector('database',table_name);
```
Map of binding name to value;

### injector.child([...modules])
* `modules` [function](#modulebind)
### Providers
#### properties
* [`name` string] [`provider`](#provider)

Creates a child injector, with new modules. Providers bound for the child injector
are only accessible from the child injector, but providers bound for a parent injector
are available through the child. Singletons bound to the child are scoped to the child.
Returns an `injector`
```
function add_injector(req,resp,next) {
if(!req.injector) {
req.injector = injector.child(requestModule);
}
next();
}
```
Map of binding name to provider;

### *bind*(name).to(provider)
* `name` string
* `provider` [function](#providerinjectargs)
### Injector
#### properties
* `dependencies` [object](#Dependencies)
* `providers` [object](#Providers)
* `context` object

Specify a binding from the `name` to the `provider`.
Injectors hold all the dependency mappings.
```
function module (bind) {
bind('my_service').to((inject) => new service(inject('database')));
}
const db = injector.dependencies.database;
```

### *module*(bind)
* `bind` [function](#bindnametoprovider)
### provider()
#### properties
* `tags` string[]

Returns any

A function that when called supplies the value as a result of invoking the corresponding binding. The tags (if any) that were defined by the corresponding binding will be available on the provider

A module is simply a function that takes a single argument, `bind`.
## Philosophy
While cider borrowers some terminology from popular Java DI frameworks like Guice it's designed from the ground up to take advantage of javascript features. Primarily this takes the form of using object destructuring in function arguments rather than attempting to provide some form of function annotation.

### *provider*([inject[,...args]])
* `inject` [function](#injectornameargs)
* `args` any
The [`dependencies`](#Dependencies) parameter that is passed to a binding uses property getters to lazily resolve the dependency chain. Cider does simple cycle detection whenever a dependency is being resolved, this prevents cases of circular dependencies.

A provider is a function that takes an inject function and any additional arguments
that were passed when the binding was requested. The inject function is an injector
and can be used to fetch dependency from the provider.
The [`providers`](#Providers) parameter contains the same keys as `dependencies` however each value is a function. The result of invoking the function is the same as getting the value of a property on `dependencies`. A Provider should be used whenever possible to lazily initialize a dependency, doing so allows for what would otherwise be unacceptable circular references.
37 changes: 37 additions & 0 deletions gulpfile.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
const gulp = require('gulp');
const clean = require('gulp-clean');
const {createProject} = require('gulp-typescript');
const jest = require('gulp-jest').default;

gulp.task('build', function() {
let failed = false;
const tsProject = createProject('tsconfig.json');
return gulp.src([
'src/**/*.ts',
'!**/__tests__/**'
], {nodir: true})
.pipe(tsProject())
.on('error', () => failed = true)
.on('finish', () => failed && process.exit(1))
.pipe(gulp.dest('lib'));
});

gulp.task('copy-config', function() {
return gulp.src([
'package.json',
'README.md',
'LICENSE'
]).pipe(gulp.dest('lib'));
})

gulp.task('test', function() {
return gulp.src('src/**/__tests__/**/*.ts')
.pipe(jest());
});

gulp.task('clean', () => {
return gulp.src('lib', {read: false})
.pipe(clean());
})

gulp.task('default',['build', 'test', 'copy-config']);
12 changes: 12 additions & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
const {join} = require('path');

module.exports = {
verbose: true,
transform: {
"^.+\\.ts$": 'ts-jest',
},
moduleFileExtensions: [
'json', 'ts', 'js'
],
testMatch: ['**/__tests__/**/*.ts']
}
Loading

0 comments on commit 431aeba

Please sign in to comment.