diff options
author | Shin'ya Ueoka <ueokande@i-beam.org> | 2019-12-03 10:02:37 +0000 |
---|---|---|
committer | GitHub <noreply@github.com> | 2019-12-03 10:02:37 +0000 |
commit | 3c7230c3036e8bb2b2e9a752be9b0ef4a0a7349d (patch) | |
tree | 8c1bb889656f06ee6bc018ae053cf35e12613dfb /src/shared/settings/Settings.ts | |
parent | feac179504a9276ad2e841702bf3fc1d89251679 (diff) | |
parent | 5205da572980f24d1632d0fa7df85124322ca960 (diff) |
Merge pull request #684 from ueokande/jsonschema-settings
Parse settings by JSON Schema
Diffstat (limited to 'src/shared/settings/Settings.ts')
-rw-r--r-- | src/shared/settings/Settings.ts | 52 |
1 files changed, 30 insertions, 22 deletions
diff --git a/src/shared/settings/Settings.ts b/src/shared/settings/Settings.ts index 2c9e37f..97dda7f 100644 --- a/src/shared/settings/Settings.ts +++ b/src/shared/settings/Settings.ts @@ -1,13 +1,16 @@ +import Ajv from 'ajv'; + import Keymaps, { KeymapsJSON } from './Keymaps'; import Search, { SearchJSON } from './Search'; import Properties, { PropertiesJSON } from './Properties'; import Blacklist, { BlacklistJSON } from './Blacklist'; +import validate from './validate'; export type SettingsJSON = { - keymaps: KeymapsJSON, - search: SearchJSON, - properties: PropertiesJSON, - blacklist: BlacklistJSON, + keymaps?: KeymapsJSON, + search?: SearchJSON, + properties?: PropertiesJSON, + blacklist?: BlacklistJSON, }; export default class Settings { @@ -36,25 +39,30 @@ export default class Settings { this.blacklist = blacklist; } - static fromJSON(json: any): Settings { + static fromJSON(json: unknown): Settings { + let valid = validate(json); + if (!valid) { + let message = (validate as any).errors!! + .map((err: Ajv.ErrorObject) => { + return `'${err.dataPath}' ${err.message}`; + }) + .join('; '); + throw new TypeError(message); + } + + let obj = json as SettingsJSON; let settings = { ...DefaultSetting }; - for (let key of Object.keys(json)) { - switch (key) { - case 'keymaps': - settings.keymaps = Keymaps.fromJSON(json.keymaps); - break; - case 'search': - settings.search = Search.fromJSON(json.search); - break; - case 'properties': - settings.properties = Properties.fromJSON(json.properties); - break; - case 'blacklist': - settings.blacklist = Blacklist.fromJSON(json.blacklist); - break; - default: - throw new TypeError('unknown setting: ' + key); - } + if (obj.keymaps) { + settings.keymaps = Keymaps.fromJSON(obj.keymaps); + } + if (obj.search) { + settings.search = Search.fromJSON(obj.search); + } + if (obj.properties) { + settings.properties = Properties.fromJSON(obj.properties); + } + if (obj.blacklist) { + settings.blacklist = Blacklist.fromJSON(obj.blacklist); } return new Settings(settings); } |