Skip to content

Commit 77faaea

Browse files
authored
fix: update number constraint args to floats (#82)
fixes #78
1 parent 24e557a commit 77faaea

File tree

3 files changed

+923
-7
lines changed

3 files changed

+923
-7
lines changed

index.js

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,12 @@ function constraintDirective () {
1313
uniqueTypeName = directiveArgumentMap.uniqueTypeName.replace(/\W/g, '')
1414
} else {
1515
uniqueTypeName = `${fieldName}_${type.name}_${notNull ? 'NotNull_' : ''}` + Object.entries(directiveArgumentMap)
16-
.map(([key, value]) => `${key}_${value.toString().replace(/\W/g, '')}`)
16+
.map(([key, value]) => {
17+
if (key === 'min' || key === 'max' || key === 'exclusiveMin' || key === 'exclusiveMax' || key === 'multipleOf') {
18+
return `${key}_${value.toString().replace(/\W/g, 'dot')}`
19+
}
20+
return `${key}_${value.toString().replace(/\W/g, '')}`
21+
})
1722
.join('_')
1823
}
1924
const key = Symbol.for(uniqueTypeName)
@@ -86,11 +91,11 @@ const constraintDirectiveTypeDefs = `
8691
format: String
8792
8893
# Number constraints
89-
min: Int
90-
max: Int
91-
exclusiveMin: Int
92-
exclusiveMax: Int
93-
multipleOf: Int
94+
min: Float
95+
max: Float
96+
exclusiveMin: Float
97+
exclusiveMax: Float
98+
multipleOf: Float
9499
uniqueTypeName: String
95100
) on INPUT_FIELD_DEFINITION | FIELD_DEFINITION`
96101

scalars/number.js

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,11 @@ module.exports = class ConstraintNumberType extends GraphQLScalarType {
3030
}
3131
}
3232

33+
function divisible (a, b) {
34+
const eps = Number.EPSILON * 3
35+
return a % b < eps || a % b > b - eps
36+
}
37+
3338
function validate (fieldName, args, value) {
3439
if (args.min !== undefined && value < args.min) {
3540
throw new ValidationError(fieldName,
@@ -53,7 +58,7 @@ function validate (fieldName, args, value) {
5358
[{ arg: 'exclusiveMax', value: args.exclusiveMax }])
5459
}
5560

56-
if (args.multipleOf !== undefined && value % args.multipleOf !== 0) {
61+
if (args.multipleOf !== undefined && divisible(value, args.multipleOf) === false) {
5762
throw new ValidationError(fieldName,
5863
`Must be a multiple of ${args.multipleOf}`,
5964
[{ arg: 'multipleOf', value: args.multipleOf }])

0 commit comments

Comments
 (0)