From 2d0968a70b78710e854075d96a8e643e2cd2b3a7 Mon Sep 17 00:00:00 2001 From: Shin'ya Ueoka Date: Sun, 1 Oct 2017 11:58:34 +0900 Subject: [PATCH] add setting validator --- src/shared/validators/setting.js | 33 ++++++++++++++++++++++++++ test/shared/validators/setting.test.js | 25 +++++++++++++++++++ 2 files changed, 58 insertions(+) create mode 100644 src/shared/validators/setting.js create mode 100644 test/shared/validators/setting.test.js diff --git a/src/shared/validators/setting.js b/src/shared/validators/setting.js new file mode 100644 index 0000000..df04e50 --- /dev/null +++ b/src/shared/validators/setting.js @@ -0,0 +1,33 @@ +import operations from '../../operations'; + +const VALID_TOP_KEYS = ['keymaps']; +const VALID_OPERATION_VALUES = Object.keys(operations).map((key) => { + return operations[key]; +}); + +const validateInvalidTopKeys = (settings) => { + let invalidKey = Object.keys(settings).find((key) => { + return !VALID_TOP_KEYS.includes(key); + }); + if (invalidKey) { + throw Error(`Unknown key: "${invalidKey}"`); + } +}; + +const validateKeymaps = (keymaps) => { + for (let key of Object.keys(keymaps)) { + let value = keymaps[key]; + if (!VALID_OPERATION_VALUES.includes(value.type)) { + throw Error(`Unknown operation: "${value.type}"`); + } + } +}; + +const validate = (settings) => { + validateInvalidTopKeys(settings); + if (settings.keymaps) { + validateKeymaps(settings.keymaps); + } +}; + +export { validate }; diff --git a/test/shared/validators/setting.test.js b/test/shared/validators/setting.test.js new file mode 100644 index 0000000..8bf0cbe --- /dev/null +++ b/test/shared/validators/setting.test.js @@ -0,0 +1,25 @@ +import { expect } from "chai"; +import { validate } from '../../../src/shared/validators/setting'; + +describe("setting validator", () => { + describe("unknown top keys", () => { + it('throws an error for unknown settings', () => { + let settings = { keymaps: {}, poison: 123 }; + let fn = validate.bind(undefined, settings) + expect(fn).to.throw(Error, 'poison'); + }) + }); + + describe("keymaps settings", () => { + it('throws an error for unknown operation', () => { + let settings = { + keymaps: { + a: { 'type': 'scroll.home' }, + b: { 'type': 'poison.dressing' }, + } + }; + let fn = validate.bind(undefined, settings) + expect(fn).to.throw(Error, 'poison.dressing'); + }); + }); +});