Skip to content

Commit

Permalink
feat(tasks): adds task runner function run
Browse files Browse the repository at this point in the history
  • Loading branch information
rafamel committed Feb 17, 2021
1 parent 2883ee0 commit c6afed2
Show file tree
Hide file tree
Showing 4 changed files with 49 additions and 0 deletions.
23 changes: 23 additions & 0 deletions src/helpers/create-context.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { Context } from '../definitions';
import { into } from 'pipettes';

const cancellation = new Promise<void>(() => undefined);

export function createContext(context?: Partial<Context>): Context {
return into(
context || {},
(context: Partial<Context>): Context => ({
cwd: context.cwd || process.cwd(),
env: context.env || { ...process.env },
args: context.args || [],
stdio: context.stdio || [process.stdin, process.stdout, process.stderr],
level: context.level || 'info',
route: context.route || [],
prefix: context.prefix || 'none',
cancellation: context.cancellation
? context.cancellation.then(() => undefined)
: cancellation
}),
(context) => Object.freeze(context)
);
}
1 change: 1 addition & 0 deletions src/tasks/consume/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './run';
24 changes: 24 additions & 0 deletions src/tasks/consume/run.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { Task, Context } from '../../definitions';
import { createContext } from '../../helpers/create-context';
import { isCancelled } from '../../utils';
import { log } from '../create/log';
import { into } from 'pipettes';

const noop = (): void => undefined;

export async function run(
task: Task,
context?: Partial<Context>
): Promise<void> {
const ctx = createContext(context);
const safe = { ...ctx, cancellation: ctx.cancellation.catch(noop) };

try {
if (await isCancelled(safe)) return await ctx.cancellation;
await task(safe);
if (await isCancelled(safe)) return await ctx.cancellation;
} catch (err) {
into(safe, log('error', err));
throw err;
}
}
1 change: 1 addition & 0 deletions src/tasks/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export * from './consume';
export * from './create';

0 comments on commit c6afed2

Please sign in to comment.