1

I want to write a wrapper function for FindOptions in my dbobject code so that I can avoid importing package options in my service code . Basically i'm trying to accomodate three func under one interface

SetSkip() 
SetLimit()
SetSort()

so that i should be able to do something like Find().SetSkip().SetLimit() in a single line , is that doable ?

Also I want to know the usage of MergeFindOptions

func MergeFindOptions(opts ...*FindOptions) *FindOptions

Any examples will be of great help.

Gopher_k
  • 273
  • 2
  • 9

1 Answers1

1

Just embed the options.FindOptions struct into a custom one. Additionally you could add a FindOptions function to initialize this custom struct, like the mongo package do by options.Find().

package your_db_package

type YourFindOptions struct {
    *options.FindOptions
}

func FindOptions() YourFindOptions {
    return YourFindOptions{options.Find()}
}

// ---
package your_service_package

import "your_db_package"

func GetItems() {
  opts := your_db_package.FindOptions().SetSkip(123).SetLimit(456)
} 

As the name MergeFindOptions and the documentation says it's for merging multiple FindOptions into a new one:

MergeFindOptions combines the given FindOptions instances into a single FindOptions in a last-one-wins fashion.

valentin1807
  • 108
  • 6
  • I tried the way you suggested but that did not work . It was not accepting it in a single line and gives me a nil pointer when I tried to run the code . `panic: runtime error: invalid memory address or nil pointer dereference [signal SIGSEGV: segmentation violation code=0x1 addr=0x18 pc=0x561becb9e9b4] goroutine 1 [running]:` – Gopher_k Nov 04 '22 at 04:04
  • 2
    @Karthik I've put the code into a [Go Playground](https://go.dev/play/p/OyIu2wzd4zD). Work's for me. Did you initialize the "FindOptions" correctly? – valentin1807 Nov 07 '22 at 08:36