From 0bf30ab160a409e532af6c513630900bebd549d6 Mon Sep 17 00:00:00 2001 From: dangoodman Date: Fri, 31 Aug 2018 20:40:02 +0300 Subject: [PATCH] Add support for the JSON MySQL type MySQL supports the JSON type since 5.7.8 which is a nice way to store and work with nested documents. --- lib/types.js | 9 +++++++++ test/specs/types.js | 13 +++++++++++++ 2 files changed, 22 insertions(+) diff --git a/lib/types.js b/lib/types.js index bd0f9c0..1cf5e20 100644 --- a/lib/types.js +++ b/lib/types.js @@ -66,6 +66,15 @@ const NATIVE_TYPES = { val = val.replace(controlRegex, '') return val } + }, + 'JSON': { + type: 'JSON', + convert: val => { + if (val === null || val === undefined) { + return null + } + return sqlstring.escape(JSON.stringify(val)) + } } } diff --git a/test/specs/types.js b/test/specs/types.js index 4dcc1c6..a783308 100644 --- a/test/specs/types.js +++ b/test/specs/types.js @@ -79,4 +79,17 @@ describe('Momy Types', () => { assert.equal(convert(undefined), "''") assert.equal(convert('\x07'), "''") // skip a control char }) + + it('JSON', () => { + const convert = NATIVE_TYPES.JSON.convert + assert.equal(convert(null), null) + assert.equal(convert(undefined), null) + assert.equal(convert({a: null, b: undefined}), '\'{\\"a\\":null}\'') + assert.equal(convert(true), '\'true\'') + assert.equal(convert(false), '\'false\'') + assert.equal(convert('string'), '\'\\"string\\"\'') + assert.equal(convert([1, 2, '3']), '\'[1,2,\\"3\\"]\'') + assert.equal(convert({age: 1, name: 'John', ids: [5, 10, 15]}), '\'{\\"age\\":1,\\"name\\":\\"John\\",\\"ids\\":[5,10,15]}\'') + assert.equal(convert('\x07\r\n\t'), '\'\\"\\\\u0007\\\\r\\\\n\\\\t\\"\'') // escape control chars + }) })