parse icon indicating copy to clipboard operation
parse copied to clipboard

How to use a client object other than the defaultClient?

Open junpayment opened this issue 7 years ago • 1 comments

Hi,

It seems that the defaultClient is present in the parse package as a singleton.

https://github.com/kylemcc/parse/blob/master/rest.go#L75

var defaultClient *clientT

// Initialize the parse library with your API keys
func Initialize(appId, restKey, masterKey string) {
    defaultClient = &clientT{
        appId:      appId,
        restKey:    restKey,
        masterKey:  masterKey,
        userAgent:  "github.com/kylemcc/parse",
        httpClient: &http.Client{},
    }
}

Therefore, for example, if I want to access multiple parse endpoints, it seems to be necessary to initialize each time, like below.

func (cli *ParseClient) initParseClient() {
	parse.Initialize(cli.appId, cli.restKey, cli.masterKey)
	parse.ServerURL(cli.serverUrl)
}

func (cli *ParseClient) NewQuery(m interface{}) (parse.Query, error) {
	cli.initParseClient()
	query, err := parse.NewQuery(m)
	if err != nil {
		return nil, err
	}

	return query, nil
}

I would like to use multiple client objects, how can I do that?

Thanks your great product!

junpayment avatar Nov 19 '18 02:11 junpayment

Hello, @junpayment, unfortunately, that's not possible with the current API. I remember thinking of that when I was putting this together, but never ended up needing it.

It should be easy enough to modify the current API to add an exported Client type, then have the DefaultClient be just that - sort of like Go's http package.

Unfortunately, I don't have time to work on it, but I'll happily accept a PR. If you'd like to take a stab at it, I might do something like the following:

  • Add a Client interface
  • Make all of the things that use defaultClient methods on the Client interface, e.g. NewQuery
  • Implement the Client interface on this type
  • Add new package-level functions such as NewQuery to wrap defaultClient.NewQuery
  • Add a client field to each of unexported struct types returned by those methods, e.g. the query type
  • Add a new package-level function, e.g. NewClient with the same API as Initialize

The result should be a new client type that behaves the same way as the package-level client.

kylemcc avatar Nov 21 '18 19:11 kylemcc