Skip to content

Commit

Permalink
feat: option to specify a fallback resolve value
Browse files Browse the repository at this point in the history
  • Loading branch information
jackmellis committed Jul 31, 2024
1 parent 1665921 commit 5b8c059
Show file tree
Hide file tree
Showing 4 changed files with 63 additions and 1 deletion.
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
44 changes: 44 additions & 0 deletions src/resolver/__tests__/default.test.ts
Original file line number Diff line number Diff line change
@@ -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>('foo');

const result = jpex.resolve<Foo>({ 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<Foo>({ 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<Foo>()).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<Foo>({ default: undefined });

expect(result).toBe(undefined);
});
11 changes: 10 additions & 1 deletion src/resolver/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ export const getFactory = (
jpex: JpexInstance,
name: string,
opts: ResolveOpts = {},
) => {
): Factory | undefined => {
validateName(name);
const fns = [
getFromResolved,
Expand All @@ -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}]`);
};

Expand Down
1 change: 1 addition & 0 deletions src/types/JpexInstance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ export interface ResolveOpts {
optional?: boolean;
with?: NamedParameters;
async?: boolean;
default?: any;
}

export interface JpexInstance {
Expand Down

0 comments on commit 5b8c059

Please sign in to comment.