From 8072d28e70d7b53bb81c22b6c0d784b34f736083 Mon Sep 17 00:00:00 2001 From: Gajus Kuizinas Date: Thu, 26 Nov 2020 09:20:10 -0600 Subject: [PATCH] feat: throw an error if task name is duplicate --- src/errors.ts | 13 +++++++++ src/factories/createPlanton.ts | 7 +++++ src/index.ts | 1 + test/planton/factories/createPlanton.ts | 35 +++++++++++++++++++++++++ 4 files changed, 56 insertions(+) diff --git a/src/errors.ts b/src/errors.ts index 5f0a0ad..a8834eb 100644 --- a/src/errors.ts +++ b/src/errors.ts @@ -14,6 +14,19 @@ export class UnexpectedStateError extends ExtendableError { } } +export class DuplicateTaskNameError extends UnexpectedStateError { + duplicateTaskName: string; + + constructor (duplicateTaskName: any) { + super( + 'Task name is duplicate.', + 'DUPLICATE_TASK_NAME', + ); + + this.duplicateTaskName = duplicateTaskName; + } +} + export class UnexpectedTaskInstructionsError extends UnexpectedStateError { unexpectedTaskInstructions: any; diff --git a/src/factories/createPlanton.ts b/src/factories/createPlanton.ts index 7450200..17010c3 100644 --- a/src/factories/createPlanton.ts +++ b/src/factories/createPlanton.ts @@ -4,6 +4,7 @@ import { } from 'serialize-error'; import Logger from '../Logger'; import { + DuplicateTaskNameError, UnexpectedTaskInstructionsError, } from '../errors'; import type { @@ -83,6 +84,12 @@ const createPlanton = (configuration: PlantonConfigurationInput): Planton => { for (const inputTask of configuration.tasks) { log.debug('registered %s task', inputTask.name); + for (const existingTask of tasks) { + if (existingTask.name === inputTask.name) { + throw new DuplicateTaskNameError(existingTask.name); + } + } + const calculateDelay = inputTask.delay || (() => { return 1_000; }); diff --git a/src/index.ts b/src/index.ts index 99ed172..19c57c0 100644 --- a/src/index.ts +++ b/src/index.ts @@ -2,5 +2,6 @@ export { createPlanton, } from './factories'; export { + DuplicateTaskNameError, UnexpectedTaskInstructionsError, } from './errors'; diff --git a/test/planton/factories/createPlanton.ts b/test/planton/factories/createPlanton.ts index abb169d..756686b 100644 --- a/test/planton/factories/createPlanton.ts +++ b/test/planton/factories/createPlanton.ts @@ -32,6 +32,41 @@ test('schedules tasks at a interval', async (t) => { await planton.terminate(); }); +test('throws if multiple tasks are registered with the same name', (t) => { + const error = t.throws(() => { + createPlanton({ + getActiveTaskInstructions: () => { + return []; + }, + tasks: [ + { + delay: () => { + return 90; + }, + name: 'foo', + schedule: async () => { + return []; + }, + }, + { + delay: () => { + return 90; + }, + name: 'foo', + schedule: async () => { + return []; + }, + }, + ], + }); + }); + + t.like(error, { + code: 'DUPLICATE_TASK_NAME', + duplicateTaskName: 'foo', + }); +}); + test('stops scheduling after Planton is terminated', async (t) => { const schedule = sinon .stub()