Skip to content

Commit 03660fd

Browse files
fix: toString method validation check (fastify#513)
1 parent cd586bf commit 03660fd

File tree

2 files changed

+40
-1
lines changed

2 files changed

+40
-1
lines changed

index.js

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -901,7 +901,17 @@ function buildValue (location, input) {
901901
switch (type) {
902902
case 'string': {
903903
code += `
904-
${statement}(${input} === null || typeof ${input} === "${type}" || ${input} instanceof RegExp || (typeof ${input} === "object" && Object.prototype.hasOwnProperty.call(${input}, "toString")))
904+
${statement}(
905+
typeof ${input} === "string" ||
906+
${input} === null ||
907+
${input} instanceof RegExp ||
908+
(
909+
typeof ${input} === "object" &&
910+
typeof ${input}.toString === "function" &&
911+
${input}.toString !== Object.prototype.toString &&
912+
!(${input} instanceof Date)
913+
)
914+
)
905915
${nestedResult}
906916
`
907917
break

test/typesArray.test.js

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -438,6 +438,35 @@ test('object that is simultaneously a string and a json switched', (t) => {
438438
t.equal(valueObj, '{"simultaneously":{"foo":"hello"}}')
439439
})
440440

441+
test('class instance that is simultaneously a string and a json', (t) => {
442+
t.plan(2)
443+
444+
const schema = {
445+
type: 'object',
446+
properties: {
447+
simultaneously: {
448+
type: ['string', 'object'],
449+
properties: {
450+
foo: { type: 'string' }
451+
}
452+
}
453+
}
454+
}
455+
456+
class Test {
457+
toString () { return 'hello' }
458+
}
459+
460+
const likeObjectId = new Test()
461+
462+
const stringify = build(schema)
463+
const valueStr = stringify({ simultaneously: likeObjectId })
464+
t.equal(valueStr, '{"simultaneously":"hello"}')
465+
466+
const valueObj = stringify({ simultaneously: { foo: likeObjectId } })
467+
t.equal(valueObj, '{"simultaneously":{"foo":"hello"}}')
468+
})
469+
441470
test('should throw an error when type is array and object is null', (t) => {
442471
t.plan(1)
443472
const schema = {

0 commit comments

Comments
 (0)