Skip to content

Commit

Permalink
feat: simplify integration
Browse files Browse the repository at this point in the history
  • Loading branch information
solufa committed Jul 28, 2020
1 parent bbf3045 commit 39a2d1f
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 11 deletions.
9 changes: 2 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -182,8 +182,6 @@ await expect(injectedFn('test.txt', text)).resolves.toBe(text)

## Integration test

Always call "inject" method with no arguments when passing a function wrapped in velona to depend.

`add.ts`
```ts
export const add = (a: number, b: number) => a + b
Expand All @@ -206,7 +204,7 @@ import { depend } from 'velona'
import { grandchild } from './grandchild'

export const child = depend(
{ grandchild: grandchild.inject() }, // call "inject" method with no arguments
{ grandchild },
({ grandchild }, a: number, b: number, c: number) => grandchild(a, b) * c
)
```
Expand All @@ -217,10 +215,7 @@ import { depend } from 'velona'
import { child } from './child'

export const parentFn = depend(
{
child: child.inject(), // call "inject" method with no arguments
print: (data: number) => alert(data)
},
{ child, print: (data: number) => alert(data) },
({ child, print }, a: number, b: number, c: number) => print(child(a, b, c))
)
```
Expand Down
4 changes: 2 additions & 2 deletions __tests__/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,11 @@ test('integration', () => {
const add = (a: number, b: number) => a + b
const grandchild = depend({ add }, ({ add }, a: number, b: number) => add(a, b))
const child = depend(
{ grandchild: grandchild.inject() },
{ grandchild },
({ grandchild }, a: number, b: number, c: number) => grandchild(a, b) * c
)
const parentFn = depend(
{ child: child.inject(), print: (data: number) => alert(data) },
{ child, print: (data: number) => alert(data) },
({ child, print }, a: number, b: number, c: number) => print(child(a, b, c))
)

Expand Down
11 changes: 9 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,15 @@
type Deps<T extends Record<string, any>> = {
[P in keyof T]: T[P] extends { _velone: boolean }
? (...deps: Parameters<T[P]>) => ReturnType<T[P]>
: T[P]
}

export const depend = <T extends Record<string, any>, U extends [] | [any, ...any[]], V>(
dependencies: T,
cb: (deps: T, ...params: U) => V
cb: (deps: Deps<T>, ...params: U) => V
) => {
const fn = (...args: U) => cb(dependencies, ...args)
fn.inject = (deps = dependencies) => (...args: U) => cb(deps, ...args)
fn._velone = true
fn.inject = (deps: Deps<T>) => (...args: U) => cb(deps, ...args)
return fn
}

0 comments on commit 39a2d1f

Please sign in to comment.