Skip to content

Commit

Permalink
Fix 604 (#605)
Browse files Browse the repository at this point in the history
* Revert "improve performance of asNumber (#595)"

This reverts commit 07a9bcc.

* add regression test

Signed-off-by: Matteo Collina <hello@matteocollina.com>

---------

Signed-off-by: Matteo Collina <hello@matteocollina.com>
  • Loading branch information
mcollina authored Feb 22, 2023
1 parent 75c7d62 commit cb736a2
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 9 deletions.
15 changes: 6 additions & 9 deletions lib/serializer.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,17 +50,14 @@ module.exports = class Serializer {
}

asNumber (i) {
if (typeof i !== 'number') {
i = Number(i)
}
// NaN !== NaN
if (i !== i) { // eslint-disable-line no-self-compare
const num = Number(i)
if (Number.isNaN(num)) {
throw new Error(`The value "${i}" cannot be converted to a number.`)
} else if (!Number.isFinite(num)) {
return null
} else {
return '' + num
}
if (i === Infinity || i === -Infinity) {
return 'null'
}
return '' + i
}

asBoolean (bool) {
Expand Down
24 changes: 24 additions & 0 deletions test/fix-604.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
'use strict'

const t = require('tap')
const fjs = require('..')
const schema = {
type: 'object',
properties: {
fullName: { type: 'string' },
phone: { type: 'number' }
}
}

const input = {
fullName: 'Jone',
phone: 'phone'
}

const render = fjs(schema)

try {
render(input)
} catch (err) {
t.equal(err.message, 'The value "phone" cannot be converted to a number.')
}

0 comments on commit cb736a2

Please sign in to comment.