GraphQL Integration

    In order to enable the entgql extension to your project, you need to use the entc (ent codegen) package as described . Follow these 3 steps to enable it to your project:

    1. Create a new Go file named ent/entc.go, and paste the following content:

    ent/entc.go

    1. Edit the ent/generate.go file to execute the ent/entc.go file:

    ent/generate.go

    1. package ent
    2. //go:generate go run -mod=mod entc.go

    Note that ent/entc.go is ignored using a build tag, and it’s executed by the go generate command through the generate.go file. The full example can be found in the ent/contrib repository.

    1. Run codegen for your ent project:
    1. go generate ./...

    After running codegen, the following add-ons will be added to your project.

    Node API

    A new file named ent/gql_node.go was created that implements the Relay Node interface.

    In order to use the new generated ent.Noder interface in the , add the Node method to the query resolver, and look at the configuration section to understand how to use it.

    If you are using the option in the schema migration, the NodeType is derived from the id value and can be used as follows:

    1. func (r *queryResolver) Node(ctx context.Context, id int) (ent.Noder, error) {
    2. return r.client.Noder(ctx, id)
    3. }

    However, if you use a custom format for the global unique identifiers, you can control the NodeType as follows:

    1. func (r *queryResolver) Node(ctx context.Context, guid string) (ent.Noder, error) {
    2. typ, id := parseGUID(guid)
    3. return r.client.Noder(ctx, id, ent.WithFixedNodeType(typ))
    4. }

    GQL Configuration

    1. schema:
    2. - todo.graphql
    3. resolver:
    4. # Tell gqlgen to generate resolvers next to the schema file.
    5. layout: follow-schema
    6. dir: .
    7. # gqlgen will search for any type names in the schema in the generated
    8. # ent package. If they match it will use them, otherwise it will new ones.
    9. autobind:
    10. - entgo.io/contrib/entgql/internal/todo/ent
    11. models:
    12. ID:
    13. model:
    14. Node:
    15. model:
    16. # ent.Noder is the new interface generated by the Node template.
    17. - entgo.io/contrib/entgql/internal/todo/ent.Noder

    The pagination template adds a pagination support according to the Relay Cursor Connections Spec. More info about the Relay Spec can be found in its .

    Connection Ordering

    The ordering option allows us to apply an ordering on the edges returned from a connection.

    • The generated types will be autobinded to GraphQL types if a naming convention is preserved (see example below).
    • Ordering can only be defined on ent fields (no edges).
    • Ordering fields should normally be to avoid full table DB scan.
    • Pagination queries can be sorted by a single field (no order by … then by … semantics).

    Example

    Let’s go over the steps needed in order to add ordering to an existing GraphQL type. The code example is based on a todo-app that can be found in .

    Defining order fields in ent/schema

    Ordering can be defined on any comparable field of ent by annotating it with entgql.Annotation. Note that the given OrderField name must match its enum value in graphql schema.

    That’s all the schema changes required, make sure to run go generate to apply them.

    Next we need to define the ordering types in graphql schema:

    1. ASC
    2. DESC
    3. }
    4. enum TodoOrderField {
    5. CREATED_AT
    6. PRIORITY
    7. STATUS
    8. TEXT
    9. }
    10. input TodoOrder {
    11. direction: OrderDirection!
    12. field: TodoOrderField
    13. }

    Note that the naming must take the form of <T>OrderField / <T>Order for autobinding to the generated ent types. Alternatively directive can be used for manual type binding.

    Adding orderBy argument to the pagination query

    1. type Query {
    2. todos(
    3. after: Cursor
    4. first: Int
    5. before: Cursor
    6. last: Int
    7. orderBy: TodoOrder
    8. ): TodoConnection
    9. }

    That’s all for the GraphQL schema changes, let’s run gqlgen code generation.

    Update the underlying resolver

    Head over to the Todo resolver and update it to pass orderBy argument to .Paginate() call:

    1. func (r *queryResolver) Todos(ctx context.Context, after *ent.Cursor, first *int, before *ent.Cursor, last *int, orderBy *ent.TodoOrder) (*ent.TodoConnection, error) {
    2. return r.client.Todo.Query().
    3. Paginate(ctx, after, first, before, last,
    4. ent.WithTodoOrder(orderBy),
    5. )
    6. }
    1. query {
    2. todos(first: 3, orderBy: {direction: DESC, field: TEXT}) {
    3. edges {
    4. node {
    5. text
    6. }
    7. }
    8. }
    9. }

    Fields Collection

    For example, given this GraphQL query:

    1. edges {
    2. node {
    3. photos {
    4. link
    5. }
    6. posts {
    7. content
    8. comments {
    9. content
    10. }
    11. }
    12. }
    13. }
    14. }
    15. }

    The client will execute 1 query for getting the users, 1 for getting the photos, and another 2 for getting the posts, and their comments (4 in total). This logic works both for root queries/resolvers and for the node(s) API.

    Schema configuration

    In order to configure this option to specific edges, use the entgql.Annotation as follows:

    Usage and Configuration

    The GraphQL extension generates also edge-resolvers for the nodes under the gql_edge.go file as follows:

    1. func (t *Todo) Children(ctx context.Context) ([]*Todo, error) {
    2. result, err := t.Edges.ChildrenOrErr()
    3. if IsNotLoaded(err) {
    4. result, err = t.QueryChildren().All(ctx)
    5. }
    6. return result, err
    7. }

    However, if you need to explicitly write these resolvers by hand, you can add the option to your GraphQL schema:

    1. type Todo implements Node {
    2. id: ID!
    3. children: [Todo]! @goField(forceResolver: true)
    4. }

    Then, you can implement it on your type resolver.

    1. func (r *todoResolver) Children(ctx context.Context, obj *ent.Todo) ([]*ent.Todo, error) {
    2. // Do something here.
    3. return obj.Edges.ChildrenOrErr()
    4. }

    The enum template implements the MarshalGQL/UnmarshalGQL methods for enums generated by ent.

    Transactional Mutations

    The entgql.Transactioner handler executes each GraphQL mutation in a transaction. The injected client for the resolver is a . Hence, code that uses ent.Client won’t need to be changed. In order to use it, follow these steps:

    1. In the GraphQL server initialization, use the entgql.Transactioner handler as follows:
    1. srv := handler.NewDefaultServer(todo.NewSchema(client))
    2. srv.Use(entgql.Transactioner{TxOpener: client})
    1. Then, in the GraphQL mutations, use the client from context as follows:
    1. func (mutationResolver) CreateTodo(ctx context.Context, todo TodoInput) (*ent.Todo, error) {
    2. client := ent.FromContext(ctx)
    3. return client.Todo.
    4. Create().
    5. SetStatus(todo.Status).
    6. SetNillablePriority(todo.Priority).
    7. SetText(todo.Text).
    8. SetNillableParentID(todo.Parent).
    9. Save(ctx)

    Examples

    The contains several examples at the moment:

    1. A complete GraphQL server with a simple Todo App with numeric ID field
    2. The same in 1, but with UUID type for the ID field
    3. The same Todo App in 1 and 2, but with a prefixed or PULID as the ID field. This example supports the Relay Node API by prefixing IDs with the entity type rather than employing the ID space partitioning in Universal IDs.