From 180668562137649e42b11fc7d5956b89a9486911 Mon Sep 17 00:00:00 2001 From: Jakub Sarnowski Date: Wed, 26 Sep 2018 00:19:12 +0200 Subject: [PATCH] call toJSON method on object types resolves #118 --- index.js | 10 +++++- test/toJSON.test.js | 83 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 92 insertions(+), 1 deletion(-) create mode 100644 test/toJSON.test.js diff --git a/index.js b/index.js index 61be0640..44dd5344 100644 --- a/index.js +++ b/index.js @@ -554,9 +554,17 @@ function addIfThenElse (schema, name, externalSchema, fullSchema) { return { code: code, laterCode: laterCode } } +function toJSON (variableName) { + return `typeof ${variableName}.toJSON === 'function' + ? ${variableName}.toJSON() + : ${variableName} + ` +} + function buildObject (schema, code, name, externalSchema, fullSchema) { code += ` - function ${name} (obj) { + function ${name} (input) { + var obj = ${toJSON('input')} var json = '{' var addComma = false ` diff --git a/test/toJSON.test.js b/test/toJSON.test.js new file mode 100644 index 00000000..25fd23d4 --- /dev/null +++ b/test/toJSON.test.js @@ -0,0 +1,83 @@ +'use strict' + +const test = require('tap').test +const build = require('..') + +test('use toJSON method on object types', (t) => { + t.plan(1) + + const stringify = build({ + title: 'simple object', + type: 'object', + properties: { + productName: { + type: 'string' + } + } + }) + const object = { + product: { name: 'cola' }, + toJSON: function () { + return { productName: this.product.name } + } + } + + t.equal('{"productName":"cola"}', stringify(object)) +}) + +test('use toJSON method on nested object types', (t) => { + t.plan(1) + + const stringify = build({ + title: 'simple array', + type: 'array', + items: { + type: 'object', + properties: { + productName: { + type: 'string' + } + } + } + }) + const array = [ + { + product: { name: 'cola' }, + toJSON: function () { + return { productName: this.product.name } + } + }, + { + product: { name: 'sprite' }, + toJSON: function () { + return { productName: this.product.name } + } + } + ] + + t.equal('[{"productName":"cola"},{"productName":"sprite"}]', stringify(array)) +}) + +test('not use toJSON if does not exist', (t) => { + t.plan(1) + + const stringify = build({ + title: 'simple object', + type: 'object', + properties: { + product: { + type: 'object', + properties: { + name: { + type: 'string' + } + } + } + } + }) + const object = { + product: { name: 'cola' } + } + + t.equal('{"product":{"name":"cola"}}', stringify(object)) +})