Skip to content

Commit

Permalink
feat(fio): add FIO.node
Browse files Browse the repository at this point in the history
FIO.node is a simpler API to handle callback based async APIs in node.js
  • Loading branch information
tusharmath committed Jul 28, 2019
1 parent 60a5736 commit 0d83a82
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 0 deletions.
32 changes: 32 additions & 0 deletions src/main/FIO.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,15 @@ export type TaskR<A, R> = FIO<Error, A, R>
*/
export type UIO<A> = IO<never, A>

/**
* Callback function used in node.js to handle async operations.
* @ignore
*/
export type NodeJSCallback<A> = (
err: NodeJS.ErrnoException | null,
result?: A
) => void

/**
* @typeparam E1 Possible errors that could be thrown by the program.
* @typeparam A1 The output of the running the program successfully.
Expand Down Expand Up @@ -243,6 +252,29 @@ export class FIO<E1 = unknown, A1 = unknown, R1 = NoEnv> {
return new FIO(Tag.Never, undefined)
}

/**
* Simple API to create IOs from a node.js based callback.
*
* **Example:**
* ```ts
* // FIO<NodeJS.ErrnoException, number, unknown>
* const fsOpen = FIO.node(cb => fs.open('./data.txt', cb))
* ```
*/
public static node<A = never>(
fn: (cb: NodeJSCallback<A>, sh: IScheduler) => void
): IO<NodeJS.ErrnoException, A | undefined> {
return FIO.asyncIO<NodeJS.ErrnoException, A>((rej, res, sh) =>
sh.asap(() => {
try {
fn((err, result) => (err === null ? res(result as A) : rej(err)), sh)
} catch (e) {
rej(e as NodeJS.ErrnoException)
}
})
)
}

/**
* Represents a constant value
*/
Expand Down
32 changes: 32 additions & 0 deletions test/FIO.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -559,4 +559,36 @@ describe('FIO', () => {
assert.deepStrictEqual(actual, expected)
})
})

describe('node', () => {
it('should capture exceptions from Node API', () => {
const actual = testRuntime().executeSync(
FIO.node(cb => cb(new Error('Failed')))
)
const expected = new Error('Failed')

assert.deepStrictEqual('' + actual, '' + expected)
})

it('should capture sync exceptions', () => {
const actual = testRuntime().executeSync(
FIO.node(cb => {
throw new Error('Failed')
})
)
const expected = new Error('Failed')

assert.deepStrictEqual('' + actual, '' + expected)
})

it('should capture success results', () => {
const actual = testRuntime().executeSync(
// tslint:disable-next-line: no-null-keyword
FIO.node<number>(cb => cb(null, 1000))
)
const expected = 1000

assert.strictEqual(actual, expected)
})
})
})

0 comments on commit 0d83a82

Please sign in to comment.