Skip to content

Instantly share code, notes, and snippets.

@tabvn
Created March 27, 2020 07:47
Show Gist options
  • Save tabvn/c70768955715126c1b29605c4428f782 to your computer and use it in GitHub Desktop.
Save tabvn/c70768955715126c1b29605c4428f782 to your computer and use it in GitHub Desktop.
func (r *queryResolver) FindUsers(ctx context.Context, search *string, first *int, last *int, after *string, before *string) (*model.UserConnection, error) {
var (
nodes []*model.User
edges []*model.UserEdge
pageInfo model.PageInfo
)
query := r.DB.Model(&nodes)
if search != nil {
s := *search
if len(s) > 0 {
s = "%" + s + "%"
query.WhereGroup(func(q *orm.Query) (*orm.Query, error) {
q = q.
WhereOr("first_name LIKE ?", s).
WhereOr("last_name LIKE ?", s).
WhereOr("email LIKE ?", s)
return q, nil
})
}
}
if last != nil {
query.Limit(*last + 1).Order("id ASC")
pageInfo.HasNextPage = false
}
if first != nil {
pageInfo.HasPreviousPage = false
query.Limit(*first + 1).Order("id DESC")
}
if before != nil {
if len(*before) > 0 {
_, realId := unique.DecodeGlobalID(*before)
query.Where("id < ?", realId)
}
}
if after != nil {
if len(*after) > 0 {
_, realId := unique.DecodeGlobalID(*after)
query.Where("id > ?", realId)
}
}
count, err := query.SelectAndCount()
if err != nil {
return nil, err
}
if last != nil {
if count >= *last+1 {
pageInfo.HasPreviousPage = true
}
}
if first != nil {
if count >= *first+1 {
pageInfo.HasNextPage = true
}
}
if first != nil || last != nil {
shouldMinusOne := false
if first != nil {
if count >= *first+1 {
shouldMinusOne = true
}
}
if last != nil {
if count >= *last+1 {
shouldMinusOne = true
}
}
if shouldMinusOne {
nodes = nodes[0:(len(nodes) - 1)]
}
}
for index, node := range nodes {
cursor := node.ToGlobalID()
if index == 0 {
pageInfo.StartCursor = &cursor
}
pageInfo.EndCursor = &cursor
edges = append(edges, &model.UserEdge{
Cursor: cursor,
Node: node,
})
}
res := &model.UserConnection{
Edges: edges,
Count: count,
PageInfo: &pageInfo,
}
return res, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment