Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for generics #144

Open
Hades32 opened this issue Aug 16, 2023 · 2 comments
Open

Add support for generics #144

Hades32 opened this issue Aug 16, 2023 · 2 comments

Comments

@Hades32
Copy link

Hades32 commented Aug 16, 2023

Search results are untyped (map[string]any) which makes this very unergonomic to use

Currently we're working around it with a custom search method

func searchCollection[TDoc any](ctx context.Context, collection string, params *api.SearchCollectionParams) (*Result[TDoc], error) {
	resp, err := typesenseApiClient.SearchCollection(ctx, collection, params)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	if resp.StatusCode > 299 {
		return nil, utils.ErrHighStatusCode
	}
	var results Result[TDoc]
	err = json.NewDecoder(resp.Body).Decode(&results)
	if err != nil {
		return nil, err
	}
	return &results, nil
}

and matching types

type  Result[TDoc any] struct {
	GroupedHits []GroupedHit[TDoc] `json:"grouped_hits,omitempty"`
	Hits []*ResultHit[TDoc] `json:"hits,omitempty"`
...
@tadejsv
Copy link

tadejsv commented Nov 6, 2023

@Hades32 The way you are doing it is the only way possible, it wouldn't be possible to use generics using the methods from this library (for example something like client.Collection("companies").Documents().Search[Company](searchParameters)), because Go does not allow parametrized methods.

The only way would be to set the result type at client creation, but then that client is effectively bound to one index only. Or well, provide a convenience function like you did.

Another way would be to allow you to provide a pointer to the result struct that you want to unmarshall the result into - the signature for that argument in the Search function would simply be interface{}, so this wouldn't even require generics.

@kishorenc
Copy link
Member

Happy to accept a PR with any helper / utility functions that help with usability.

@elee1766 elee1766 mentioned this issue Mar 27, 2024
1 task
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants