Skip to content

Fix 604 #605

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Feb 22, 2023
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
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)) {
Copy link
Member

@ivan-tymoshenko ivan-tymoshenko Feb 22, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Uzlopak I will approve it because I'm not sure if it makes any perf difference with i === Infinity || i === -Infinity, but if it does, feel free to open a new PR.

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.')
}