Urigo / graphql-scalars

A library of custom GraphQL Scalars for creating precise type-safe GraphQL schemas.
https://www.the-guild.dev/graphql/scalars
MIT License
1.88k stars 133 forks source link

Scalar type factory (range validation, custom conditions) #757

Open andreialecu opened 3 years ago

andreialecu commented 3 years ago

Is your feature request related to a problem? Please describe.

I'd like to define some scalars that are for example positive integers limited to values between 0 to 6 (for a weekday index).

Describe the solution you'd like

It seems it would be possible to expose a factory method that could return a custom scalar with custom validation.

For example:

import { PositiveIntResolver, CustomStringResolver } from 'graphql-scalars';

const myResolverMap = {
  Weekday: PositiveIntResolver.create({name: "Weekday", description: "A value between 0 (Monday) and 6 (Sunday)", min: 0, max: 6}),
  CustomId: CustomStringResolver.create({name: "CustomId", description: "A string with custom validation", validation: /some-regex/ })
  ...

Describe alternatives you've considered

Manually defining my own scalars.

Additional context

Edit: it appears this is already a thing for regex validation: https://github.com/Urigo/graphql-scalars#using-the-regularexpression-scalar

Would really like it for numeric values as well.

Betree commented 2 years ago

This could be useful for us as well to implement things like a Percentage scalar that accepts float numbers between 0 and 100. Not too difficult to implement from scratch, but we would have used graphql-scalars if there was a simple helper for this like the one mentioned above:

import { PositiveFloatResolver } from 'graphql-scalars';

export const Percentage = PositiveFloatResolver.create({ name: 'Percentage', min: 0, max: 100 })