go-zendesk icon indicating copy to clipboard operation
go-zendesk copied to clipboard

Add Client.GetAs generic method

Open dolmen opened this issue 2 years ago • 1 comments

I propose to add a GetAs method that wraps Client.Get but adds the json.Unmarshal step. That method will be convenient for users as well as allow to simplify the internal implementation of all the API wrappers.

Here is the full implementation (that I will submit as PR if this is accepted):

func (z *Client) GetAs(ctx context.Context, path string, target any) error {
	b, err := z.Get(ctx, path)
	if err != nil {
		return err
	}

	return json.Unmarshal(b, target)
}

Here is a usage example:

func GetMe(ctx context.Context, client *zendesk.Client) (*zendesk.User, error) {
	var body struct {
		User *zendesk.User `json:"user"`
	}
	err := client.GetAs(ctx, "/users/me.json", &body)
	if err != nil {
		return nil, err
	}
	return body.User, nil
}

dolmen avatar Nov 29 '23 15:11 dolmen

@nukosuke What do you think? I'm waiting for your feedback before submitting a PR.

If approved, in which file should I put this utility function?

dolmen avatar Jun 10 '24 16:06 dolmen