strichliste

package module
v0.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 22, 2019 License: LGPL-3.0 Imports: 10 Imported by: 1

README

go-strichliste: Go Bindings for the Strichliste API

GoDoc

This library implements a REST client and v2 API bindings for hackerspace bootstrap's strichliste, which is a pretty neat tally sheet server.

Please note that this library is not stable yet.

Packages are

All of the current API has been implemented, but test coverage is currently nonexistant, so the library is probably horribly buggy.

There's a sister project to this library, strichliste-cli, which implements a proper CLI-based application for strichliste and is also very WIP.

Example

package main

import (
    "fmt"
    s "github.com/jktr/go-strichliste"
    ss "github.com/jktr/go-strichliste/schema"
    "math"
    "os"
    "strconv"
    "strings"
)

func main() {

    if len(os.Args) <= 2 {
        fmt.Println("usage: example USER AMOUNT [COMMENT...]")
        os.Exit(1)
    }

    amount, err := strconv.ParseFloat(os.Args[2], 64)
    if err != nil || math.Abs(amount) < 0.005 {
        fmt.Println("error: invalid AMOUNT")
        os.Exit(1)
    }

    delta := int(math.Round(amount * 100))
    comment := ""
    if len(os.Args) > 2 {
        comment = strings.Join(os.Args[3:], " ")
    }

    client := s.NewClient(s.WithEndpoint(s.DefaultEndpoint))

    user, _, err := client.User.GetByName(os.Args[1])
    if err != nil {
        // API-specific errors can be disambiguated like this
        if er, ok := err.(*ss.ErrorResponse); ok {
            if er.Class == ss.ErrorUserNotFound {
                fmt.Println("error: no such user")
                os.Exit(1)
            }
        } else {
            fmt.Printf("error: %s", err.Error())
            os.Exit(1)
        }
    }

    tx, _, err := client.Transaction.Context(user.ID).WithComment(comment).Delta(delta)
    if err != nil {
        fmt.Println(err.Error())
        os.Exit(1)
    }

    fmt.Println("new balance:", float64(tx.Issuer.Balance)/100)
}

License

Copyright (C) 2019 Konrad Tegtmeier

This library is free software: you can redistribute it and/or modify
it under the terms of the Lesser GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
Lesser GNU General Public License for more details.

You should have received a copy of the Lesser GNU General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.

v1 API

If you're looking for the v1 API Bindings: There's a set of terribly legacy bindings baked into the legacy strichlist-cli for the v1 API, which can be found here.

Acknowledgments

The structure of this library is heavily based on the one of Hetzner's hcloud-go library. Thanks for open sourcing it!

Documentation

Index

Constants

View Source
const (
	LibName         = "go-strichliste"
	LibVersion      = "0.3.0"
	ApiVersion      = "2:1.6.1" // compatible with this Strichliste API version
	DefaultEndpoint = "https://demo.strichliste.org/api"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type ArticleClient

type ArticleClient struct {
	// contains filtered or unexported fields
}

An ArticleClient carries the necessary context to interact with the /article endpoint

func (*ArticleClient) Create

POST /article

  • ErrorParameterMissing
  • ErrorParameterInvalid

Creates a new article and returns it.

func (*ArticleClient) Deactivate

func (s *ArticleClient) Deactivate(id int) (*schema.Article, *Response, error)

DELETE /article/{articleId}

  • ErrorArticleNotFound

Deactivates an article by ID; returns the deactivated article. Note that actual deletion is not possible.

func (*ArticleClient) Get

func (s *ArticleClient) Get(id int) (*schema.Article, *Response, error)

GET /article/{articleId}

Retrieves an article by ID.

func (*ArticleClient) List

func (s *ArticleClient) List(opt *ListOpts) ([]schema.Article, *Response, error)

GET /article

Retrieves a list of articles (both active and inactive). Pagination is possible via ListOpts, which can be nil.

func (*ArticleClient) SearchByBarcode

func (s *ArticleClient) SearchByBarcode(barcode string, opt *ListOpts) ([]schema.Article, *Response, error)

GET /article/search

Retrieves a list of articles whose barcodes match, or include, the passed barcode. Pagination is possible via ListOpts, which can be nil.

func (*ArticleClient) SearchByName

func (s *ArticleClient) SearchByName(name string, opt *ListOpts) ([]schema.Article, *Response, error)

GET /article/search

Retrieves a list of articles whose names match, or include, the passed name. Pagination is possible via ListOpts, which can be nil.

func (*ArticleClient) Update

func (s *ArticleClient) Update(id int, article *schema.ArticleUpdateRequest) (*schema.Article, *Response, error)

POST /article/{articleId}

  • ErrorArticleNotFound
  • ErrorParameterMissing
  • ErrorParameterInvalid

Updates an article by ID. Note that this operation checks for referential integrity and may not update the article, but instead create a new one, referencing and deactivating the old version. The returned article is always new version — either replaced or updated.

type Client

type Client struct {
	User        UserClient
	Transaction TransactionClient
	Article     ArticleClient
	Settings    SettingsClient
	Metrics     MetricsClient
	// contains filtered or unexported fields
}

Contains the necessary context to make API requests.

func NewClient

func NewClient(options ...ClientOption) *Client

Create a new API client. This is the library's entrypoint.

func (*Client) Do

func (c *Client) Do(req *http.Request, obj interface{}) (*Response, error)

Executes an API call. Parses the response and any errors. A suitable reqest may be prepared via NewRequest. Obj may be any one of the …Single-/MultiResponse strichliste.schema structs.

func (*Client) NewRequest

func (c *Client) NewRequest(method, path string, body interface{}) (*http.Request, error)

Builds a http.Request suitable for contacting the API endpoint. Method should be GET/POST/DELETE/etc. Body may be any one of the …Request strichliste.schema structs.

type ClientOption

type ClientOption func(*Client)

func WithApplication

func WithApplication(name, version string) ClientOption

Configure the application's name and version to use when contacting the API endpoint. The User Agent for requests derives from this value. Not setting this option will default to LibName and LibVersion.

func WithEndpoint

func WithEndpoint(endpoint string) ClientOption

Configure the URL of the API endpoint. Not setting this option will default to DefaultEndpoint.

type ListOpts

type ListOpts struct {
	Page    uint // page number (1-indexed, 0 means all on one page)
	PerPage uint // items per page (0 means default size)
}

Allows for result pagination and result limitation.

Pagination works by passing a page number and the number of items on each page.

Limiting results works by keeping Page at 0 and setting PerPage to the desired number of total entries.

Note that endpoint semantics differ; some use "most recent items" and some "oldest items". TODO document this behaviour.

type MetricsClient

type MetricsClient struct {
	// contains filtered or unexported fields
}

A MetricsClient carries the necessary context to interact with the /metrics endpoint

func (*MetricsClient) ForSystem

func (s *MetricsClient) ForSystem() (*schema.SystemMetrics, *Response, error)

GET /metrics

Retrieves the current server metrics.

func (*MetricsClient) ForUser

func (s *MetricsClient) ForUser(id int) (*schema.UserMetrics, *Response, error)

GET /user/{userId}/metrics

Retrieves the current user metrics by user ID.

type Response

type Response struct {
	*http.Response
}

Wraps a http.Response with additional Metadata.

type SettingsClient

type SettingsClient struct {
	// contains filtered or unexported fields
}

A SettingsClient carries the necessary context to interact with the /settings endpoint

func (*SettingsClient) Get

func (s *SettingsClient) Get() (*schema.Settings, *Response, error)

GET /settings

Retrieves the current server settings.

type TransactionClient

type TransactionClient struct {
	// contains filtered or unexported fields
}

An ArticleClient carries the necessary context to interact with the /transaction endpoint.

func (*TransactionClient) Context

func (c *TransactionClient) Context(user int) *TransactionContext

Create a user-specific context by user ID, which allows issuing transactions as that user.

func (*TransactionClient) List

GET /transaction

Retrieves a list of recent transactions. Pagination is possible via ListOpts, which can be nil.

type TransactionContext

type TransactionContext struct {
	TransactionClient
	// contains filtered or unexported fields
}

TransactionContext extends the TransactionClient with additional user-specific context.

func (*TransactionContext) Create

POST /user/{userId}/transaction

  • ErrorUserNotFound
  • ErrorParameterMissing
  • ErrorParameterInvalid
  • ErrorAccountBalanceBoundary
  • ErrorTransactionBoundary
  • TODO ErrorArticleNotFound?

Creates a raw transaction and returns it. Consider using these wrappers for specific use-cases:

  • Delta
  • Purchase
  • TransferFunds

func (*TransactionContext) Delta

func (c *TransactionContext) Delta(amount int) (*schema.Transaction, *Response, error)

Utility wrapper for Create; see Create for possible errors. Deposit or withdraw funds for the current User; returns the created transaction.

func (*TransactionContext) Get

GET /user/{userId}/transaction/{txId}

  • ErrorUserNotFound
  • ErrorTransactionNotFound

Retrieves a transaction by ID.

func (*TransactionContext) List

GET /user/{userId}/transaction

  • ErrorUserNotFound

Retrieves a list of transactions issued by this user. Pagination is possible via ListOpts, which can be nil.

func (*TransactionContext) Purchase

func (c *TransactionContext) Purchase(article int, count int) (*schema.Transaction, *Response, error)

Utility wrapper for Create; see Create for possible errors. Purchase a number of articles by ID with the current user; returns the created transaction.

func (*TransactionContext) Revert

func (c *TransactionContext) Revert(id int) (*schema.Transaction, *Response, error)

DELETE /user/{userId}/transaction

  • ErrorUserNotFound
  • ErrorTransactionNotFound
  • ErrorTransactionNotDeletable

Revert a transaction by ID; returns the reversed transaction. Not all transactions are reversible; check Transaction.IsReversible. Note that actual deletion is not possible.

func (*TransactionContext) TransferFunds

func (c *TransactionContext) TransferFunds(recipient int, amount int) (*schema.Transaction, *Response, error)

Utility wrapper for Create; see Create for possible errors. Transfer an amount of funds from the current user to another by ID; returns the created transaction.

func (*TransactionContext) WithComment

func (c *TransactionContext) WithComment(comment string) *TransactionContext

Set the comment to use for all new transactions that use the returned context.

type UserClient

type UserClient struct {
	// contains filtered or unexported fields
}

A UserClient carries the necessary context to interact with the /user endpoint

func (*UserClient) Create

func (c *UserClient) Create(user *schema.UserCreateRequest) (*schema.User, *Response, error)

POST /user

  • ErrorUserAlreadyExists

Creates a new user and returns it.

func (*UserClient) Deactivate

func (c *UserClient) Deactivate(id int) (*schema.User, *Response, error)

Deactivates a user by ID; returns the deactivated user. Note that actual deletion is not possible.

func (*UserClient) Get

func (c *UserClient) Get(id int) (*schema.User, *Response, error)

GET /user/{userId}

  • ErrorUserNotFound

Retrieves a user by ID.

func (*UserClient) GetByName

func (c *UserClient) GetByName(name string) (*schema.User, *Response, error)

GET /user/{userID}

  • ErrorUserNotFound

Retrieves a user by name.

func (*UserClient) List

func (c *UserClient) List(opt *ListOpts) ([]schema.User, *Response, error)

GET /user

Retrieves the list of users (both active and inactive). Pagination is possible via ListOpts, which can be nil.

func (*UserClient) Search

func (c *UserClient) Search(query string, opt *ListOpts) ([]schema.User, *Response, error)

GET /user/search

Retrieves a list of users whose names match, or include, the passed name. Pagination is possible via ListOpts, which can be nil.

func (*UserClient) Update

func (c *UserClient) Update(id int, user *schema.UserUpdateRequest) (*schema.User, *Response, error)

POST /user/{userId}

  • ErrorUserNotFound
  • ErrorUserAlreadyExists
  • ErrorParameterMissing
  • ErrorParameterInvalid

Updates a user by ID and returns it.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL