Skip to content

Commit

Permalink
fix(retrieve): Allowing a slice of pointed structs (#6)
Browse files Browse the repository at this point in the history
Allowing a slice of pointed structs
  • Loading branch information
Jacobbrewer1 authored Oct 14, 2024
1 parent da27a9f commit a3dc12d
Showing 1 changed file with 21 additions and 6 deletions.
27 changes: 21 additions & 6 deletions query_builder.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package pagefilter

import (
"errors"
"fmt"
"net/http"
"reflect"
Expand All @@ -9,6 +10,11 @@ import (
"github.com/jmoiron/sqlx"
)

var (
// ErrNoDestination is returned when the destination is nil
ErrNoDestination = errors.New("destination is nil")
)

// Paginator is the struct that provides the paging.
type Paginator struct {
db DB
Expand Down Expand Up @@ -228,22 +234,31 @@ func (p *Paginator) Pivot() (string, error) {
}

// Retrieve pulls the next page given the pivot point and requires a destination *[]struct to load the data into.
func (p *Paginator) Retrieve(pivot string, dest interface{}) error {
func (p *Paginator) Retrieve(pivot string, dest any) error {
if dest == nil {
return ErrNoDestination
}

// Gracefully locate all the columns to load.
t := reflect.TypeOf(dest)
if t.Kind() != reflect.Ptr {
return fmt.Errorf("unexpected type %s (expected pointer)", t.Kind())
}
if t = t.Elem(); t.Kind() != reflect.Slice {
t = t.Elem()
if t.Kind() != reflect.Slice {
return fmt.Errorf("unexpected type %s (expected slice)", t.Kind())
}
if t = t.Elem(); t.Kind() != reflect.Struct {
return fmt.Errorf("unexpected type %s (expected struct)", t.Kind())
elemType := t.Elem()
if elemType.Kind() == reflect.Ptr {
elemType = elemType.Elem()
}
if elemType.Kind() != reflect.Struct {
return fmt.Errorf("unexpected type %s (expected struct)", elemType.Kind())
}

var cols strings.Builder
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
for i := 0; i < elemType.NumField(); i++ {
field := elemType.Field(i)
dbTag := field.Tag.Get("db")
switch dbTag {
case "":
Expand Down

0 comments on commit a3dc12d

Please sign in to comment.