From 5b8c0590eb2305381a6eff536f2c669afaa9776d Mon Sep 17 00:00:00 2001 From: Jack Ellis Date: Wed, 31 Jul 2024 09:57:50 +0100 Subject: [PATCH] feat: option to specify a fallback resolve value --- README.md | 8 +++++ src/resolver/__tests__/default.test.ts | 44 ++++++++++++++++++++++++++ src/resolver/utils.ts | 11 ++++++- src/types/JpexInstance.ts | 1 + 4 files changed, 63 insertions(+), 1 deletion(-) create mode 100644 src/resolver/__tests__/default.test.ts diff --git a/README.md b/README.md index 93f955e..1968d6a 100644 --- a/README.md +++ b/README.md @@ -302,6 +302,14 @@ boolean; When `true` if the dependency cannot be found or resolved, it will just return `undefined` rather than throwing an error. +### default + +```ts +any; +``` + +Provide a fallback value if the dependency cannot be found. + #### jpex.resolveAsync ```ts diff --git a/src/resolver/__tests__/default.test.ts b/src/resolver/__tests__/default.test.ts new file mode 100644 index 0000000..8d17ed4 --- /dev/null +++ b/src/resolver/__tests__/default.test.ts @@ -0,0 +1,44 @@ +import base from '../..'; + +const setup = () => { + const jpex = base.extend(); + + return { + jpex, + }; +}; + +test('if factory exists, it should be resolved', () => { + const { jpex } = setup(); + type Foo = string; + jpex.constant('foo'); + + const result = jpex.resolve({ default: 'bar' }); + + expect(result).toBe('foo'); +}); + +test('if factory does not exist, it should return the default', () => { + const { jpex } = setup(); + type Foo = string; + + const result = jpex.resolve({ default: 'bar' }); + + expect(result).toBe('bar'); +}); + +test('if factory does not exist and default not provided, it should throw an error', () => { + const { jpex } = setup(); + type Foo = string; + + expect(() => jpex.resolve()).toThrow(); +}); + +test('if factory does not exist and default is undefined, it should return undefined', () => { + const { jpex } = setup(); + type Foo = string; + + const result = jpex.resolve({ default: undefined }); + + expect(result).toBe(undefined); +}); diff --git a/src/resolver/utils.ts b/src/resolver/utils.ts index f5967ce..c4ef348 100644 --- a/src/resolver/utils.ts +++ b/src/resolver/utils.ts @@ -95,7 +95,7 @@ export const getFactory = ( jpex: JpexInstance, name: string, opts: ResolveOpts = {}, -) => { +): Factory | undefined => { validateName(name); const fns = [ getFromResolved, @@ -115,6 +115,15 @@ export const getFactory = ( return; } + if ('default' in opts) { + return { + fn: () => opts.default, + lifecycle: jpex.$$config.lifecycle, + resolved: true, + value: opts.default, + }; + } + throw new Error(`Unable to find required dependency [${name}]`); }; diff --git a/src/types/JpexInstance.ts b/src/types/JpexInstance.ts index ee94563..ce89a47 100644 --- a/src/types/JpexInstance.ts +++ b/src/types/JpexInstance.ts @@ -30,6 +30,7 @@ export interface ResolveOpts { optional?: boolean; with?: NamedParameters; async?: boolean; + default?: any; } export interface JpexInstance {