Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement mapOf setting type #12703

Merged
merged 3 commits into from
Jul 7, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 68 additions & 0 deletions platform/lib/schema/__tests__/MapOfSetting.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import { mapOf, object, string, number } from '../';

test('handles object as input', () => {
const setting = mapOf(string(), string());
const value = {
name: 'foo'
};
const expected = new Map([['name', 'foo']]);

expect(setting.validate(value)).toEqual(expected);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

note: not for this PR, but maybe for the future discussion, from my experience validate usually has one of the two behaviours:

  • Returns bool (is validated or not);
  • Throws if can't validate.

And never modifies anything.

In this case it validates and transforms value somehow, so validate name is a bit misleading, but maybe that's just me.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree, I just haven't found a better name 🙈

});

test('fails when not receiving expected value type', () => {
const setting = mapOf(string(), string());
const value = {
name: 123
};

expect(() => setting.validate(value)).toThrowErrorMatchingSnapshot();
});

test('fails when not receiving expected key type', () => {
const setting = mapOf(number(), string());
const value = {
name: 'foo'
};

expect(() => setting.validate(value)).toThrowErrorMatchingSnapshot();
});

test('returns default value if undefined', () => {
const obj = new Map([['foo', 'bar']]);

const setting = mapOf(string(), string(), {
defaultValue: obj
});

expect(setting.validate(undefined)).toEqual(obj);
});

test('mapOf within mapOf', () => {
const setting = mapOf(string(), mapOf(string(), number()));
const value = {
foo: {
bar: 123
}
};
const expected = new Map([['foo', new Map([['bar', 123]])]]);

expect(setting.validate(value)).toEqual(expected);
});

test('object within mapOf', () => {
const setting = mapOf(
string(),
object({
bar: number()
})
);
const value = {
foo: {
bar: 123
}
};
const expected = new Map([['foo', { bar: 123 }]]);

expect(setting.validate(value)).toEqual(expected);
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`fails when not receiving expected key type 1`] = `"[name]: expected value of type [number] but got [string]"`;
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These errors aren't fantastic at giving you context yet (e.g. this doesn't separate between if the key failed or the value failed), but I think that's a separate PR cleaning it up across the Setting stuff.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it's good enough for now. I still need to learn what these jest snapshot are about :)


exports[`fails when not receiving expected value type 1`] = `"[name]: expected value of type [string] but got [number]"`;
57 changes: 57 additions & 0 deletions platform/lib/schema/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -436,6 +436,55 @@ export class ObjectSetting<P extends Props> extends Setting<
}
}

function isMap<K, V>(o: any): o is Map<K, V> {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

question: what is stopping us from using something like this?

function isMap<K, V>(o: Map<K, V>) {
  return o instanceof Map;
}

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🙈 "search internet, copy first answer" didn't work :partyparrot: <--- github needs to add this asap

return o instanceof Map;
}

type MapOfOptions<K, V> = SettingOptions<Map<K, V>>;

export class MapOfSetting<K, V> extends Setting<Map<K, V>> {
constructor(
private readonly keySetting: Setting<K>,
private readonly valueSetting: Setting<V>,
options: MapOfOptions<K, V> = {}
) {
super(options);
}

process(obj: any, context?: string): Map<K, V> {
if (isPlainObject(obj)) {
const entries = Object.keys(obj).map(key => [key, obj[key]]);
return this.processEntries(entries);
}

if (isMap(obj)) {
return this.processEntries([...obj.entries()]);
}

throw new SettingError(
`expected value of type [Map] or [object] but got [${typeDetect(obj)}]`,
context
);
}

processEntries(entries: any[][], context?: string) {
const res = entries.map(([key, value]) => {
const validatedKey = this.keySetting.validate(
key,
toContext(context, String(key))
);
const validatedValue = this.valueSetting.validate(
value,
toContext(context, String(key))
);

return [validatedKey, validatedValue] as [K, V];
});

return new Map(res);
}
}

export function boolean(options?: SettingOptions<boolean>): Setting<boolean> {
return new BooleanSetting(options);
}
Expand Down Expand Up @@ -483,6 +532,14 @@ export function arrayOf<T>(
return new ArraySetting(itemSetting, options);
}

export function mapOf<K, V>(
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: it would suuuuuuuper-awesome if you can add proper JSDoc for this exported function (with tiny example maybe) :)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍 I'll create a separate PR where I add a jsdoc for all of these

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice!

keySetting: Setting<K>,
valueSetting: Setting<V>,
options?: MapOfOptions<K, V>
): Setting<Map<K, V>> {
return new MapOfSetting(keySetting, valueSetting, options);
}

export function oneOf<A, B, C, D>(
types: [Setting<A>, Setting<B>, Setting<C>, Setting<D>],
options?: SettingOptions<A | B | C | D>
Expand Down
2 changes: 1 addition & 1 deletion platform/plugins/pid/PidFile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,4 +47,4 @@ export class PidFile {
this.log.debug(`deleting pid file [${path}]`);
unlinkSync(path);
}
}
}