This project serves as an accessible and extensible example and template for a GraphQL server. Its primary goal is to dismiss the often intricate initial setup involved in configuring ent (an entity framework) and gqlgen (a GraphQL code generator), since once the setup is complete adding new features becomes remarkably straightforward.
- Go
- Docker
- make
-
Clone the repository:
git clone https://github.com/lucasshuan/go-ent-graphql-example.git cd go-ent-graphql-example
-
Install dependencies:
make deps
-
Start Docker containers:
make docker-up
-
Start the server:
make server
Adding new functionality is fairly simple: To create a new database entity (in this example, we are creating an Item entity), just run the following command and enter a name when name input is asked:
make entity Item
You will notice that a new file is generated in directory ./ent/schema. Read more about Fields and Edges.
type Item struct {
ent.Schema
}
func (Item) Fields() []ent.Field {
return []ent.Field{
field.String("name"),
field.String("description"),
}
}
func (Item) Edges() []ent.Edge {
return nil
}
The go generate .
command auto-migrates your database tables for every ./ent/schema/*.go file. However, at most times, one may want the types generated by ent to be used by the resolvers. This is fairly easy to achieve and also the most important feature of this integration, and the only necessary step is to add an Annotations method in your newly created entity file:
func (Item) Annotations() []schema.Annotation {
return []schema.Annotation{
entgql.QueryField(),
entgql.Mutations(entgql.MutationCreate(), entgql.MutationUpdate()),
}
}
The code block adds the default queries and mutations to be added to your ./graphql/schema/ent.graphql schema when running the command go generate .
. Resolvers will be created in ./graphql/resolvers directory for each new file, where you will be able to implement all of your queries and mutations.