1

I created a GraphQLScalarType to prevent arguments with empty strings. The issue however is if I don't pass the argument at all when calling the mutation, the mutation succeeds and gives the field a value of null.

Usually, I'd wrap the type in a GraphQLNonNull type e.g GraphQLNonNull(GraphQLString). But that doesn't work with my custom scalar type.

function validateEmptyStrings(value) {
    if (typeof value !== 'string') {
        throw new TypeError('Value must be a string')
    }
    if (value === "") {
        throw new TypeError('Value cannot be empty')
    }
    return value
}

const NonEmptyString = new GraphQLScalarType({
    name: 'NonEmptyString',
    serialize: validateEmptyStrings,
    parseValue: validateEmptyStrings,
})

My mutation below

addClient: {
      type: ClientType,
      args: {
        name: {type: NonEmptyString, required: true},
      },
      resolve(parent, args) {
        const client = new Client ({
          name: args.name,
        })
        return client.save()
     }
}

Wrapping the arg 'name' type like GraphQLNonNull(NonEmptyString) doesn't work, and neither does the required: true do anything

Matthew Herbst
  • 29,477
  • 23
  • 85
  • 128
  • Is there a specific error you get when trying to create the GraphQLNonNull wrapped type? – Matthew Herbst Jul 18 '22 at 00:06
  • The error message was "Expected value of type \"NonEmptyString!\", found \"\"; Value cannot be empty" Which apparently is exactly what I'm looking for, dunno how I missed that. Thanks, Matthew – Itakpe Emmanuel Jul 20 '22 at 21:21

1 Answers1

1

Apparently, Wrapping the arg 'name' type like GraphQLNonNull(NonEmptyString) does indeed work.

I'm not sure how I skipped that part. Thanks Matthew Herbst for making me take a second look