Skip to content

Commit

Permalink
Added a custom type to the pagination content to facilitate conversio…
Browse files Browse the repository at this point in the history
…n to the desired slice and item type.
  • Loading branch information
Gabriel Cataldo committed Jan 30, 2024
1 parent 8eb9c9e commit 96bb670
Show file tree
Hide file tree
Showing 9 changed files with 44 additions and 29 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ MongoDB Template
<!--suppress ALL -->
<img align="right" src="gopher-mongo.png" alt="">

[![Project status](https://img.shields.io/badge/version-v1.1.5-vividgreen.svg)](https://github.com/GabrielHCataldo/go-mongo-template/releases/tag/v1.1.5)
[![Project status](https://img.shields.io/badge/version-v1.1.6-vividgreen.svg)](https://github.com/GabrielHCataldo/go-mongo-template/releases/tag/v1.1.6)
[![Go Report Card](https://goreportcard.com/badge/github.com/GabrielHCataldo/go-mongo-template)](https://goreportcard.com/report/github.com/GabrielHCataldo/go-mongo-template)
[![Coverage Status](https://coveralls.io/repos/GabrielHCataldo/go-mongo-template/badge.svg?branch=main&service=github)](https://coveralls.io/github/GabrielHCataldo/go-mongo?branch=main)
[![Open Source Helpers](https://www.codetriage.com/gabrielhcataldo/go-mongo-template/badges/users.svg)](https://www.codetriage.com/gabrielhcataldo/go-mongo)
Expand Down Expand Up @@ -577,7 +577,7 @@ func main() {
logger.Error("error find pageable documents:", err)
} else {
var dest []test
_ = pageOutput.Content.Parse(&dest)
_ = pageOutput.Content.Decode(&dest)
logger.Info("find pageable documents successfully:", pageOutput)
logger.Info("find pageable get first value:", dest[0])
}
Expand Down
2 changes: 1 addition & 1 deletion _example/find/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ func findPageable() {
logger.Error("error find pageable documents:", err)
} else {
var dest []test
_ = pageOutput.Content.Parse(&dest)
_ = pageOutput.Content.Decode(&dest)
logger.Info("find pageable documents successfully:", pageOutput)
logger.Info("find pageable get first value:", dest[0])
}
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ go 1.21.3
require (
github.com/GabrielHCataldo/go-errors v1.1.1
github.com/GabrielHCataldo/go-helper v1.3.5
github.com/GabrielHCataldo/go-logger v1.2.2
github.com/GabrielHCataldo/go-logger v1.2.3
github.com/iancoleman/orderedmap v0.3.0
go.mongodb.org/mongo-driver v1.13.1
)
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ github.com/GabrielHCataldo/go-logger v1.2.1 h1:5pKq4449safXvGR5rYkq7Op2lGgqeDR4B
github.com/GabrielHCataldo/go-logger v1.2.1/go.mod h1:Q7+M9m9gu1MtgGiFkoYOHtobLLM/kJCPZVhszIJtsJ0=
github.com/GabrielHCataldo/go-logger v1.2.2 h1:+CFRBha2Pr7mwHpQrPI+4i+XX8J2WSFo7bNotZg7E8U=
github.com/GabrielHCataldo/go-logger v1.2.2/go.mod h1:Q7+M9m9gu1MtgGiFkoYOHtobLLM/kJCPZVhszIJtsJ0=
github.com/GabrielHCataldo/go-logger v1.2.3 h1:qkmmluuxsi5e2XZw6X4eU+fSr/cdlO/DvXxFKSGxH/k=
github.com/GabrielHCataldo/go-logger v1.2.3/go.mod h1:Q7+M9m9gu1MtgGiFkoYOHtobLLM/kJCPZVhszIJtsJ0=
github.com/cockroachdb/apd v1.1.0 h1:3LFP3629v+1aKXU5Q37mxmRxX/pIu1nijXydLShEq5I=
github.com/cockroachdb/apd v1.1.0/go.mod h1:8Sl8LxpKi29FqWXR16WEFZRNSz3SoPzUzeMeY4+DwBQ=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
Expand Down
14 changes: 7 additions & 7 deletions mongo/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -279,7 +279,7 @@ type testListIndexes struct {
var mongoTemplate *Template

type testStruct struct {
Id primitive.ObjectID `json:"id,omitempty" bson:"_id,omitempty" database:"test" collection:"test"`
Id primitive.ObjectID `json:"id" bson:"_id,omitempty" database:"test" collection:"test"`
Random int `json:"random,omitempty" bson:"random,omitempty"`
Name string `json:"name,omitempty" bson:"name,omitempty"`
BirthDate primitive.DateTime `json:"birthDate,omitempty" bson:"birthDate,omitempty"`
Expand Down Expand Up @@ -308,9 +308,9 @@ type testEmptyStruct struct {

func TestMain(t *testing.M) {
initMongoTemplate()
clearCollection()
//clearCollection()
t.Run()
clearCollection()
//clearCollection()
disconnectMongoTemplate()
}

Expand Down Expand Up @@ -1243,7 +1243,7 @@ func initListTestFindPageable() []testFindPageable {
pageInput: PageInput{
Page: 0,
PageSize: 10,
Ref: testStruct{},
Ref: "",
Sort: nil,
},
option: initOptionFindPageable(),
Expand Down Expand Up @@ -1588,9 +1588,9 @@ func initListTestWatchHandler() []testWatchHandler {
handler: func(ctx *EventContext) {
var testStr string
var test testStruct
_ = ctx.Event.FullDocument.ParseToStruct(testStr)
_ = ctx.Event.FullDocument.ParseToStruct(&testStr)
_ = ctx.Event.FullDocument.ParseToStruct(&test)
_ = ctx.Event.FullDocument.Decode(testStr)
_ = ctx.Event.FullDocument.Decode(&testStr)
_ = ctx.Event.FullDocument.Decode(&test)
logger.Info("watch handler ctx:", ctx, "fullDocument:", test)
},
option: initOptionWatchHandler(),
Expand Down
18 changes: 12 additions & 6 deletions mongo/page.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,14 @@ import (
)

type PageInput struct {
Page int64
// Page current page (default 0)
Page int64
// PageSize page size (required)
PageSize int64
Ref any
Sort any
// Ref slice of the struct reference contained database and collection configured
Ref any
// Sort value sort to result
Sort any
}

type PageResult struct {
Expand All @@ -26,15 +30,17 @@ type PageResult struct {
type pageContent []pageItemContent
type pageItemContent map[string]any

func (p pageContent) Parse(dest any) error {
// Decode parse pageResult.Content to dest param
func (p pageContent) Decode(dest any) error {
if helper.IsNotSlice(dest) {
return errors.NewSkipCaller(2, "mongo: dest is not a slice or array")
}
err := helper.ConvertToDest(p, dest)
return errors.NewSkipCaller(2, err)
}

func (p pageItemContent) Parse(dest any) error {
// Decode parse pageResult item to dest param
func (p pageItemContent) Decode(dest any) error {
err := helper.ConvertToDest(p, dest)
return errors.NewSkipCaller(2, err)
}
Expand All @@ -50,7 +56,7 @@ func newPageResult(pageInput PageInput, result any, countTotal int64) *PageResul
var content pageContent
_ = helper.ConvertToDest(result, &content)
return &PageResult{
Page: pageInput.Page,
Page: 0,
PageSize: pageInput.PageSize,
PageTotal: int64(pageTotal),
TotalElements: countTotal,
Expand Down
15 changes: 11 additions & 4 deletions mongo/template.go
Original file line number Diff line number Diff line change
Expand Up @@ -515,9 +515,6 @@ func (t *Template) FindAll(ctx context.Context, dest any, opts ...*option.Find)
// For more information about the command, see https://www.mongodb.com/docs/manual/reference/command/find/.
func (t *Template) FindPageable(ctx context.Context, filter any, input PageInput, opts ...*option.FindPageable) (
*PageResult, error) {
if helper.IsNotSlice(input.Ref) {
return nil, errors.NewSkipCaller(2, "mongo: input.Ref can be a slice")
}
_, collection, err := t.getMongoInfosByAny(2, input.Ref)
if helper.IsNotNil(err) {
return nil, err
Expand All @@ -544,8 +541,9 @@ func (t *Template) FindPageable(ctx context.Context, filter any, input PageInput
Sort: input.Sort,
Let: opt.Let,
})
defer t.closeCursor(ctx, cursor)
if helper.IsNil(err) {
dest := input.Ref
dest := reflect.MakeSlice(reflect.TypeOf(input.Ref), 0, 0).Interface()
err = cursor.All(ctx, &dest)
if helper.IsNil(err) {
countTotal, _ := collection.CountDocuments(ctx, filter)
Expand Down Expand Up @@ -611,6 +609,7 @@ func (t *Template) Aggregate(ctx context.Context, pipeline any, dest any, opts .
Let: opt.Let,
Custom: opt.Custom,
})
defer t.closeCursor(ctx, cursor)
if helper.IsNil(err) {
err = cursor.All(ctx, dest)
}
Expand Down Expand Up @@ -875,6 +874,7 @@ func (t *Template) ListIndexes(ctx context.Context, ref any, opts ...*option.Lis
BatchSize: opt.BatchSize,
MaxTime: opt.MaxTime,
})
defer t.closeCursor(ctx, cursor)
var results []IndexResult
if helper.IsNil(err) {
err = cursor.All(ctx, &results)
Expand Down Expand Up @@ -1168,6 +1168,7 @@ func (t *Template) find(ctx context.Context, filter, dest any, opts ...*option.F
Sort: opt.Sort,
Let: opt.Let,
})
defer t.closeCursor(ctx, cursor)
if helper.IsNil(err) {
err = cursor.All(ctx, dest)
}
Expand Down Expand Up @@ -1431,6 +1432,12 @@ func (t *Template) endSession(ctx context.Context) {
}
}

func (t *Template) closeCursor(ctx context.Context, cursor *mongo.Cursor) {
if helper.IsNotNil(cursor) {
_ = cursor.Close(ctx)
}
}

func (t *Template) getMongoInfosByAny(skipCaller int, a any) (*mongo.Database, *mongo.Collection, error) {
skipCaller++
var databaseName string
Expand Down
12 changes: 6 additions & 6 deletions mongo/template_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -329,12 +329,12 @@ func TestTemplateFindPageable(t *testing.T) {
t.Log("err expected:", err)
} else {
var destContent []testStruct
_ = v.Content.Parse(destContent)
_ = v.Content.Parse(&destContent)
logger.Info("result pageable:", destContent)
_ = v.Content.Decode(destContent)
_ = v.Content.Decode(&destContent)
logger.Info("result pageable:", v)
if helper.IsGreaterThan(len(v.Content), 0) {
var destItemContent testStruct
_ = v.Content[0].Parse(&destItemContent)
_ = v.Content[0].Decode(&destItemContent)
logger.Info("result item content:", destItemContent)
}
}
Expand All @@ -354,7 +354,7 @@ func TestTemplateExists(t *testing.T) {
} else if helper.IsNotNil(err) {
t.Log("err expected:", err)
} else {
logger.Info("result pageable:", v)
logger.Info("result:", v)
}
})
}
Expand All @@ -372,7 +372,7 @@ func TestTemplateExistsById(t *testing.T) {
} else if helper.IsNotNil(err) {
t.Log("err expected:", err)
} else {
logger.Info("result pageable:", v)
logger.Info("result:", v)
}
})
}
Expand Down
4 changes: 2 additions & 2 deletions mongo/watch.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,8 @@ type EventContext struct {

type EventHandler func(ctx *EventContext)

// ParseToStruct convert Event.FullDocument to struct
func (f FullDocument) ParseToStruct(dest any) error {
// Decode convert Event.FullDocument to struct
func (f FullDocument) Decode(dest any) error {
if helper.IsNotStruct(dest) {
return errDestIsNotStruct(2)
}
Expand Down

0 comments on commit 96bb670

Please sign in to comment.