Gqlgen Custom Data Validation — Part 1

In this article, we will create our custom data validation for the gqlgen library.

Why Gqlgen?


Get Started

# Initialize
go mod init myapp
go get
go get
# gqlgen init
go run init
directory after gqlgen init

Define and Generating Our Schema

package graph//go:generate go run This file will not be regenerated automatically.//// It serves as dependency injection for your app, add any dependencies you require here.type Resolver struct{}
go generate ./...
after go generate ./…

Create User Service

Testing Our Code

go run server.go# output:
# connect to http://localhost:8080/ for GraphQL playground
get all users (empty)
create first user
create second user
get all users ()

Custom Validation with Directives

directive @goField(forceResolver: String, name: String) on FIELD_DEFINITION | INPUT_FIELD_DEFINITION
directive @binding(constraint: String!) on INPUT_FIELD_DEFINITION | ARGUMENT_DEFINITION
input NewUser {
name: String! @binding(constraint: "required,max=20")
email: String! @binding(constraint: "required,email")
age: Int! @binding(constraint: "gte=0,lte=128")
country_id: String! @binding(constraint: "required,iso3166_1_alpha2")
name ‘required’ failed
age greater than equal ‘0’ failed
age ‘gte’ failed
name ‘required’ failed
name ‘max’ failed
email ‘email’ failed (custom message)

Just a normal Go Programmer 👨‍💻