Itakpe Emmanuel
Itakpe Emmanuel

Reputation: 31

How to use custom GraphQLScalarType with default GraphQL types?

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

Upvotes: 2

Views: 350

Answers (1)

Itakpe Emmanuel
Itakpe Emmanuel

Reputation: 31

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

Upvotes: 1

Related Questions