mcnk
mcnk

Reputation: 2341

Do not allow empty strings in GraphQL Schema

We have a field which expects a non-nullable string with type String! however Apollo will except this field if it is an empty string or string with just empty spaces.

We have tried using scalar type NonEmptyString however no luck.

Is there a way to add non-empty string type to our Apollo Server graphql schema?

Thanks

Upvotes: 3

Views: 4603

Answers (1)

Honza
Honza

Reputation: 703

Hi this should be possibe using the custom scalar

export const NonEmptyString = new GraphQLScalarType({
  name: 'NonEmptyString',
  description: 'Non empty string',
  serialize: (value: unknown): string => {
    if (typeof value !== 'string' || value === '') { // or any custom validation
      throw new Error('Wrong value type');
    }

    return value
  },
  parseValue: (value: unknown): string => {
    if (typeof value !== 'string' || value === '') {
      throw new Error('Wrong value type');
    }

    return value
  },
});

Upvotes: 4

Related Questions