Skip to content

Commit

Permalink
feat: reduce complexity of bag class used by services and parameters
Browse files Browse the repository at this point in the history
  • Loading branch information
Marcachi committed Jun 11, 2023
1 parent b01cba2 commit ad18d50
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 7 deletions.
4 changes: 3 additions & 1 deletion src/__tests__/parameters.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import Klient from '..';
import Klient, { Bag } from '..';

class Test {}

Expand Down Expand Up @@ -31,6 +31,7 @@ test('constructor', () => {
expect(klient.url).toBe('http://localhost');
expect(klient.debug).toBe(true);
expect(klient.parameters.get('request.headers.Content-Type')).toBe('application/json');
expect(klient.parameters).toBeInstanceOf(Bag);

const customParam = klient.parameters.get('customParam');

Expand All @@ -40,5 +41,6 @@ test('constructor', () => {
expect(customParam[1]).toBeInstanceOf(Test);

expect(klient.parameters.all()).toBeInstanceOf(Object);
expect(klient.parameters.all()).not.toBeInstanceOf(Bag);
expect(klient.parameters.all().name).toBe('KlientTest');
});
28 changes: 22 additions & 6 deletions src/services/bag.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,30 +3,46 @@ import * as objectPath from 'object-path';

type BagItems = Record<string, unknown>;

export default class Bag {
constructor(private items: BagItems = {}) {}
export default class Bag implements BagItems {
[x: string]: unknown;

constructor(items: BagItems = {}) {
Object.keys(items).forEach((key) => {
this.set(key, items[key]);
});
}

get(path: string) {
return objectPath.get(this.items, path);
return objectPath.get(this, path);
}

set(path: string, value: unknown): this {
objectPath.set(this.items, path, value);
objectPath.set(this, path, value);
return this;
}

merge(...items: BagItems[]): this {
this.items = deepmerge.all<BagItems>([this.items, ...items], {
const nextState = deepmerge.all<BagItems>([this, ...items], {
// Replacing array with next value
arrayMerge: (_destinationArray: unknown[], sourceArray: unknown[]) => sourceArray,
// Merge only array & plain object
isMergeableObject: (o: object) => o?.constructor === Array || o?.constructor === Object
});

Object.keys(nextState).forEach((key) => {
this.set(key, nextState[key]);
});

return this;
}

all() {
return this.items;
const all: BagItems = {};

Object.keys(this).forEach((key) => {
all[key] = this[key];
});

return all;
}
}

0 comments on commit ad18d50

Please sign in to comment.