summaryrefslogblamecommitdiff
path: root/grocy/user.go
blob: 493c4d5e3bb427844b9d687c7d7a76d17e895c2f (plain) (tree)
1
2
3
4
5



                 
                
































                                                                                   
















                                                                                  















                                                                                                         
package grocy

import (
	"context"
	"errors"
	"fmt"
	"net/http"
)

type (
	User struct {
		Id              int    `json:"id"`
		Username        string `json:"username"`
		FirstName       string `json:"first_name"`
		LastName        string `json:"last_name"`
		RowCreated      string `json:"row_created_timestamp"`
		DisplayName     string `json:"display_name"`
		PictureFileName string `json:"picture_file_name"`
	}
)

func (c *Client) GetUsers(ctx context.Context) ([]User, error) {
	req, err := http.NewRequest("GET", fmt.Sprintf("%s/users", c.BaseUrl), nil)

	if err != nil {
		return nil, err
	}
	req.Header.Add("GROCY-API-KEY", c.apiKey)
	req.WithContext(ctx)

	var res []User
	if err := c.sendRequest(req, &res); err != nil {
		return nil, err
	}

	return res, nil
}

func (c *Client) GetUser(ctx context.Context, userId int) (User, error) {
	// This is kinda hacky because grocy doesn't support getting LDAP users by
	// grocy ID :(
	res, err := c.GetUsers(ctx)
	if err != nil {
		return *new(User), err
	}

	for _, u := range res {
		if u.Id == userId {
			return u, nil
		}
	}

	return *new(User), errors.New("User Not Found")
}

func (c *Client) GetUserFields(ctx context.Context, userId int) (map[string]string, error) {
	req, err := http.NewRequest("GET", fmt.Sprintf("%s/userfields/users/%d", c.BaseUrl, userId), nil)

	if err != nil {
		return nil, err
	}

	req.WithContext(ctx)

	var res map[string]string
	if err := c.sendRequest(req, &res); err != nil {
		return nil, err
	}

	return res, nil
}