Skip to content

Commit

Permalink
Merge pull request #22 from SoftwareBrothers/fix/safe-parse-number
Browse files Browse the repository at this point in the history
fix: check if string param is numeric before converting to Number
  • Loading branch information
dziraf authored May 11, 2021
2 parents f9b06bc + 988381f commit 46dc226
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
5 changes: 3 additions & 2 deletions src/Resource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { BaseResource, ValidationError, Filter, BaseRecord, flat } from 'admin-b

import { Property } from './Property'
import { convertFilter } from './utils/filter/filter.converter'
import safeParseNumber from './utils/safe-parse-number'

type ParamsType = Record<string, any>;

Expand Down Expand Up @@ -146,9 +147,9 @@ export class Resource extends BaseResource {

if (type === 'number') {
if (property.isArray()) {
preparedParams[key] = param ? param.map((p) => Number(p)) : param
preparedParams[key] = param ? param.map((p) => safeParseNumber(p)) : param
} else {
preparedParams[key] = Number(param)
preparedParams[key] = safeParseNumber(param)
}
}

Expand Down
16 changes: 16 additions & 0 deletions src/utils/safe-parse-number.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
/* eslint-disable no-restricted-globals */
const isNumeric = (value: null | string | number | undefined): boolean => {
const stringValue = (String(value)).replace(/,/g, '.')

if (isNaN(parseFloat(stringValue))) return false

return isFinite(Number(stringValue))
}

const safeParseNumber = (value?: null | string | number): string | number | null | undefined => {
if (isNumeric(value)) return Number(value)

return value
}

export default safeParseNumber

0 comments on commit 46dc226

Please sign in to comment.