graphql-go / graphql

An implementation of GraphQL for Go / Golang
MIT License
9.93k stars 840 forks source link

Pagination #509

Open amedeiros opened 5 years ago

amedeiros commented 5 years ago

Is there any plan to add pagination support? https://graphql.org/learn/pagination/

sfriedel commented 5 years ago

Connections are part of the relay specification. https://github.com/graphql-go/relay may be what you are looking for

tamago-cn commented 4 years ago

You can do pagination yourself by build a pageType from origin Type, then use the pageType in your field, do the pagination logic in your database query, I think it‘s better than the relay solution,because we cache no data and do not rely on react When you do query, add index and size args such as:

{
    userPage(index: 1, size: 100){
         list{
             # fields of userType
         }
         index
         size
         total
    }
}
func addPageParamsToArgs(args graphql.FieldConfigArgument) graphql.FieldConfigArgument {
    args["index"] = &graphql.ArgumentConfig{
        Type:         graphql.Int,
        Description:  "page index",
        DefaultValue: 0,
    }
    args["size"] = &graphql.ArgumentConfig{
        Type:         graphql.Int,
        Description:  "page size, 0 means do not page",
        DefaultValue: 0,
    }
    return args
}

func buildPageType(t graphql.Type) *graphql.Object {
    fields := graphql.Fields{}

    fields["list"] = &graphql.Field{
        Name: t.Name() + "List",
        Type: graphql.NewList(t),
    }

    fields["index"] = &graphql.Field{
        Name:        "number",
        Type:        graphql.Int,
        Description: "page index",
    }

    fields["size"] = &graphql.Field{
        Name:        "size",
        Type:        graphql.Int,
        Description: "page size",
    }

    fields["total"] = &graphql.Field{
        Name:        "total",
        Type:        graphql.Int,
        Description: "total count",
    }

    pageType := graphql.NewObject(
        graphql.ObjectConfig{
            Name:        t.Name() + "Page",
            Description: fmt.Sprintf("%s page data", t.Name()),
            Fields:      fields,
        },
    )

    return pageType
}
carlosstrand commented 4 years ago

I created a library that helps in creating pagination in graphql-go: https://github.com/carlosstrand/graphql-pagination-go