Skip to content

Commit

Permalink
fix: toString method validation check (#513)
Browse files Browse the repository at this point in the history
  • Loading branch information
ivan-tymoshenko committed Aug 27, 2022
1 parent cd586bf commit 03660fd
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
12 changes: 11 additions & 1 deletion index.js
Expand Up @@ -901,7 +901,17 @@ function buildValue (location, input) {
switch (type) {
case 'string': {
code += `
${statement}(${input} === null || typeof ${input} === "${type}" || ${input} instanceof RegExp || (typeof ${input} === "object" && Object.prototype.hasOwnProperty.call(${input}, "toString")))
${statement}(
typeof ${input} === "string" ||
${input} === null ||
${input} instanceof RegExp ||
(
typeof ${input} === "object" &&
typeof ${input}.toString === "function" &&
${input}.toString !== Object.prototype.toString &&
!(${input} instanceof Date)
)
)
${nestedResult}
`
break
Expand Down
29 changes: 29 additions & 0 deletions test/typesArray.test.js
Expand Up @@ -438,6 +438,35 @@ test('object that is simultaneously a string and a json switched', (t) => {
t.equal(valueObj, '{"simultaneously":{"foo":"hello"}}')
})

test('class instance that is simultaneously a string and a json', (t) => {
t.plan(2)

const schema = {
type: 'object',
properties: {
simultaneously: {
type: ['string', 'object'],
properties: {
foo: { type: 'string' }
}
}
}
}

class Test {
toString () { return 'hello' }
}

const likeObjectId = new Test()

const stringify = build(schema)
const valueStr = stringify({ simultaneously: likeObjectId })
t.equal(valueStr, '{"simultaneously":"hello"}')

const valueObj = stringify({ simultaneously: { foo: likeObjectId } })
t.equal(valueObj, '{"simultaneously":{"foo":"hello"}}')
})

test('should throw an error when type is array and object is null', (t) => {
t.plan(1)
const schema = {
Expand Down

0 comments on commit 03660fd

Please sign in to comment.