Skip to content
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
10 changes: 9 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
`
Expand Down
83 changes: 83 additions & 0 deletions test/toJSON.test.js
Original file line number Diff line number Diff line change
@@ -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))
})