Skip to content

Commit fc49114

Browse files
jsardevmcollina
authored andcommitted
call toJSON method on object types (#120)
resolves #118
1 parent 84f8301 commit fc49114

File tree

2 files changed

+92
-1
lines changed

2 files changed

+92
-1
lines changed

index.js

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -554,9 +554,17 @@ function addIfThenElse (schema, name, externalSchema, fullSchema) {
554554
return { code: code, laterCode: laterCode }
555555
}
556556

557+
function toJSON (variableName) {
558+
return `typeof ${variableName}.toJSON === 'function'
559+
? ${variableName}.toJSON()
560+
: ${variableName}
561+
`
562+
}
563+
557564
function buildObject (schema, code, name, externalSchema, fullSchema) {
558565
code += `
559-
function ${name} (obj) {
566+
function ${name} (input) {
567+
var obj = ${toJSON('input')}
560568
var json = '{'
561569
var addComma = false
562570
`

test/toJSON.test.js

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
'use strict'
2+
3+
const test = require('tap').test
4+
const build = require('..')
5+
6+
test('use toJSON method on object types', (t) => {
7+
t.plan(1)
8+
9+
const stringify = build({
10+
title: 'simple object',
11+
type: 'object',
12+
properties: {
13+
productName: {
14+
type: 'string'
15+
}
16+
}
17+
})
18+
const object = {
19+
product: { name: 'cola' },
20+
toJSON: function () {
21+
return { productName: this.product.name }
22+
}
23+
}
24+
25+
t.equal('{"productName":"cola"}', stringify(object))
26+
})
27+
28+
test('use toJSON method on nested object types', (t) => {
29+
t.plan(1)
30+
31+
const stringify = build({
32+
title: 'simple array',
33+
type: 'array',
34+
items: {
35+
type: 'object',
36+
properties: {
37+
productName: {
38+
type: 'string'
39+
}
40+
}
41+
}
42+
})
43+
const array = [
44+
{
45+
product: { name: 'cola' },
46+
toJSON: function () {
47+
return { productName: this.product.name }
48+
}
49+
},
50+
{
51+
product: { name: 'sprite' },
52+
toJSON: function () {
53+
return { productName: this.product.name }
54+
}
55+
}
56+
]
57+
58+
t.equal('[{"productName":"cola"},{"productName":"sprite"}]', stringify(array))
59+
})
60+
61+
test('not use toJSON if does not exist', (t) => {
62+
t.plan(1)
63+
64+
const stringify = build({
65+
title: 'simple object',
66+
type: 'object',
67+
properties: {
68+
product: {
69+
type: 'object',
70+
properties: {
71+
name: {
72+
type: 'string'
73+
}
74+
}
75+
}
76+
}
77+
})
78+
const object = {
79+
product: { name: 'cola' }
80+
}
81+
82+
t.equal('{"product":{"name":"cola"}}', stringify(object))
83+
})

0 commit comments

Comments
 (0)