Implements Validation Directive with Gqlgen Custom Plugin
In the previous article, we successfully create a @binding directive to validate the data from a request.
Now we will start to implement this thing to Plugin.
Plugin in a nutshell is creating your generator with some customization that gqlgen provides for us. There are 5 things that we can do according to this section.
We will use MutateConfig, and InjectSourceEarly to edit our generator configuration, so let's get started.
repository: https://github.com/david-yappeter/gqlgen-validation-library-example
Hands On
First, we will generate our go.mod
, the name must be the same as our repository name later.
go mod init github.com/david-yappeter/gqlgen-validation-library-example# import library
go get github.com/99designs/gqlgen
go get github.com/go-playground/validator/v10
go get github.com/go-playground/universal-translator
And then we will create our plugin struct in plugin/plugin.go
explanation:
- MutateConfig will add our binding to the list of directives before generating it.
- InjectSourceEarly will inject a file with Input in it, the file will not be generated.
The next step is to create our function for the directive in directives/binding.go
.
This part will provide the function to be used by the directive and Validation Translation which can customize the error message for a tag.
After our plugin & directive is ready, we will add the plugin to our main.go
.
The last thing we need to do is to push this code to a repository with the associated name that we defined earlier to our go.mod
.
Optionally you can add tagging to your repository for versioning for example v0.0.0
.
Usage
For example, we create a new project with gqlgen init
.
go mod init myapp
go get github.com/99designs/gqlgen
go run github.com/99designs/gqlgen init
and then we need to go get
our library with the right tag we want
go get github.com/david-yappeter/gqlgen-validation-library-example@v0.0.1
To use the library we just need to run a normal command that we use like the gqlgen library
go run github.com/david-yappeter/gqlgen-validation-library-example
This will automatically generate the directive which we can see in ExecutableSchema in server.go
Of course, after the binding directive is available, we can assign the function from our library to the directive.
c := generated.Config{Resolvers: &graph.Resolver{}}
c.Directives.Binding = directives.Binding
This is the end of the article, Hope it helps you :).