directdecisions

package module
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Jan 21, 2024 License: BSD-3-Clause Imports: 12 Imported by: 0

README

Direct Decisions API v1 Go client

Go PkgGoDev NewReleases

Package directdecisions is a Go client library for accessing the Direct Decisions v1 API.

You can view the client API docs here: https://pkg.go.dev/directdecisions.com/directdecisions

You can view Direct Decisions API v1 docs here: https://api.directdecisions.com/v1

Installation

This package requires Go 1.20 version or later.

Run go get directdecisions.com/directdecisions from command line.

Usage

import "directdecisions.com/directdecisions"

Create a new Client, then use the exposed services to access different parts of the API.

Features

This client implements all Direct API features.

  • Create votings
  • Retrieve voting information
  • Set voting choices
  • Delete votings
  • Vote with a ballot
  • Unvote
  • Get submitted ballot
  • Calculate results
  • Get voting choices' duels (pairwise comparisons)

Examples

To run a voting:

package main

import (
    "context"
    "log"

    "directdecisions.com/directdecisions"
)

func main() {
 client := directdecisions.NewClient("my-api-key", nil)

 ctx := context.Background()

 v, err := client.Votings.Create(ctx, []string{"Margarita", "Pepperoni", "Capricciosa"})
 if err != nil {
  log.Fatal(err)
 }

 log.Printf("Created voting with ID %s", v.ID)

 if _, err := client.Votings.Vote(ctx, v.ID, "Leonardo", map[string]int{
  "Pepperoni": 1,
  "Margarita": 2,
 }); err != nil {
  log.Fatal(err)
 }

 log.Printf("Leonardo Voted for Pepperoni in voting with ID %s", v.ID)

 if _, err := client.Votings.Vote(ctx, v.ID, "Michelangelo", map[string]int{
  "Capricciosa": 1,
  "Margarita":   2,
  "Pepperoni":   2,
 }); err != nil {
  log.Fatal(err)
 }

 log.Printf("Michelangelo Voted for Capricciosa in voting with ID %s", v.ID)

 results, tie, err := client.Votings.Results(ctx, v.ID)
 if err != nil {
  log.Fatal(err)
 }

 if tie {
  log.Printf("Voting with ID %s is tied", v.ID)
 } else {
  log.Printf("Voting with ID %s is not tied", v.ID)
 }

 log.Printf("Results for voting with ID %s: %v", v.ID, results)
}

Error handling with Go 1.20 multiple errors wrapped:

package main

import (
    "context"
    "log"

    "directdecisions.com/directdecisions"
)

func main() {
 client := directdecisions.NewClient("my-api-key", nil)

 ctx := context.Background()

 _, err := client.Votings.Create(ctx, []string{"Margarita", "Pepperoni", "Capricciosa"})
 if err != nil {
  if errors.Is(err, directdecisions.ErrHTTPStatusUnauthorized) {
   log.Fatal("Invalid API key")
  }
  if errors.Is(err, directdecisions.ErrChoiceTooLong) {
   log.Fatal("Some of the choices are too long")
  }
  // ...
  log.Fatal(err)
 }
}

Versioning

Each version of the client is tagged and the version is updated accordingly.

This package uses Go modules.

To see the list of past versions, run git tag.

Contributing

We love pull requests! Please see the contribution guidelines.

License

This library is distributed under the BSD-style license found in the LICENSE file.

Documentation

Overview

package directdecisions is the Direct Decisions API v1 client for Go.

Example (ErrorHandling)
package main

import (
	"context"
	"errors"
	"log"

	"directdecisions.com/directdecisions"
)

func main() {
	client := directdecisions.NewClient("my-api-key", nil)

	ctx := context.Background()

	_, err := client.Votings.Create(ctx, []string{"Margarita", "Pepperoni", "Capricciosa"})
	if err != nil {
		if errors.Is(err, directdecisions.ErrHTTPStatusUnauthorized) {
			log.Fatal("Invalid API key")
		}
		if errors.Is(err, directdecisions.ErrChoiceTooLong) {
			log.Fatal("Some of the choices are too long")
		}
		// ...
		log.Fatal(err)
	}
}
Output:

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	ErrHTTPStatusBadRequest          = errors.New("http status: " + http.StatusText(http.StatusBadRequest))
	ErrHTTPStatusUnauthorized        = errors.New("http status: " + http.StatusText(http.StatusUnauthorized))
	ErrHTTPStatusForbidden           = errors.New("http status: " + http.StatusText(http.StatusForbidden))
	ErrHTTPStatusNotFound            = errors.New("http status: " + http.StatusText(http.StatusNotFound))
	ErrHTTPStatusMethodNotAllowed    = errors.New("http status: " + http.StatusText(http.StatusMethodNotAllowed))
	ErrHTTPStatusTooManyRequests     = errors.New("http status: " + http.StatusText(http.StatusTooManyRequests))
	ErrHTTPStatusInternalServerError = errors.New("http status: " + http.StatusText(http.StatusInternalServerError))
	ErrHTTPStatusServiceUnavailable  = errors.New("http status: " + http.StatusText(http.StatusServiceUnavailable))
	ErrHTTPStatusBadGateway          = errors.New("http status: " + http.StatusText(http.StatusBadGateway))

	ErrInvalidData    = errors.New("Invalid Data")
	ErrMissingChoices = errors.New("Missing Choices")
	ErrChoiceRequired = errors.New("Choice Required")
	ErrChoiceTooLong  = errors.New("Choice Too Long")
	ErrTooManyChoices = errors.New("Too Many Choices")
	ErrBallotRequired = errors.New("Ballot Required")
	ErrVoterIDTooLong = errors.New("Voter ID Too Long")
	ErrInvalidVoterID = errors.New("Invalid Voter ID")
)

Errors that are returned by the API.

Functions

This section is empty.

Types

type ChoiceStrength added in v0.2.1

type ChoiceStrength struct {
	Choice   string
	Index    int
	Strength int
}

type Client

type Client struct {

	// Services that API provides.
	Votings *VotingsService
	// contains filtered or unexported fields
}

Client manages communication with the Direct Decisions API.

func NewClient

func NewClient(key string, o *ClientOptions) (c *Client)

NewClient constructs a new Client that uses API key authentication.

Example
package main

import (
	"context"
	"log"

	"directdecisions.com/directdecisions"
)

func main() {
	client := directdecisions.NewClient("my-api-key", nil)

	ctx := context.Background()

	v, err := client.Votings.Create(ctx, []string{"Margarita", "Pepperoni", "Capricciosa"})
	if err != nil {
		log.Fatal(err)
	}

	log.Printf("Created voting with ID %s", v.ID)

	if _, err := client.Votings.Vote(ctx, v.ID, "Leonardo", map[string]int{
		"Pepperoni": 1,
		"Margarita": 2,
	}); err != nil {
		log.Fatal(err)
	}

	log.Printf("Leonardo Voted for Pepperoni in voting with ID %s", v.ID)

	if _, err := client.Votings.Vote(ctx, v.ID, "Michelangelo", map[string]int{
		"Capricciosa": 1,
		"Margarita":   2,
		"Pepperoni":   2,
	}); err != nil {
		log.Fatal(err)
	}

	log.Printf("Michelangelo Voted for Capricciosa in voting with ID %s", v.ID)

	results, tie, err := client.Votings.Results(ctx, v.ID)
	if err != nil {
		log.Fatal(err)
	}

	if tie {
		log.Printf("Voting with ID %s is tied", v.ID)
	} else {
		log.Printf("Voting with ID %s is not tied", v.ID)
	}

	log.Printf("Results for voting with ID %s: %v", v.ID, results)
}
Output:

func (*Client) Rate

func (c *Client) Rate() (r Rate)

Rate returns the current request rate limit information.

type ClientOptions

type ClientOptions struct {
	HTTPClient *http.Client
	BaseURL    *url.URL
}

ClientOptions holds optional parameters for the Client.

type Duel added in v0.2.1

type Duel struct {
	Left  ChoiceStrength
	Right ChoiceStrength
}

type Rate

type Rate struct {
	Limit     int       // The maximum number of requests that the user is permitted to make per hour.
	Remaining int       // The number of requests remaining in the current rate limit window.
	Reset     time.Time // Seconds until current rate limit window will reset to the maximal value.
	Retry     time.Time // Seconds until new requests are permitted when limit is reached.
}

Rate contains the request rate limit information.

func (Rate) String

func (r Rate) String() (s string)

type Result

type Result struct {
	Choice     string
	Index      int
	Wins       int
	Percentage float64
	Strength   int
	Advantage  int
}

type Voting

type Voting struct {
	ID      string   `json:"id"`
	Choices []string `json:"choices,omitempty"`
}

Voting holds information about votings and ballots.

type VotingsService

type VotingsService service

VotingsService provides information and methods to manage votings and ballots.

func (*VotingsService) Ballot

func (s *VotingsService) Ballot(ctx context.Context, votingID, voterID string) (ballot map[string]int, err error)

func (*VotingsService) Create

func (s *VotingsService) Create(ctx context.Context, choices []string) (v *Voting, err error)

Create adds a new voting with a provided choices.

func (*VotingsService) Delete

func (s *VotingsService) Delete(ctx context.Context, votingID string) (err error)

Delete removes a voting referenced by its ID.

func (*VotingsService) Duels added in v0.2.1

func (s *VotingsService) Duels(ctx context.Context, votingID string) (results []Result, duels []Duel, tie bool, err error)

func (*VotingsService) Results

func (s *VotingsService) Results(ctx context.Context, votingID string) (results []Result, tie bool, err error)

func (*VotingsService) Set

func (s *VotingsService) Set(ctx context.Context, votingID, choice string, index int) (choices []string, err error)

Set adds, moves or removes a choice in a voting.

func (*VotingsService) Unvote

func (s *VotingsService) Unvote(ctx context.Context, votingID, voterID string) error

func (*VotingsService) Vote

func (s *VotingsService) Vote(ctx context.Context, votingID, voterID string, ballot map[string]int) (revoted bool, err error)

func (*VotingsService) Voting

func (s *VotingsService) Voting(ctx context.Context, votingID string) (v *Voting, err error)

Voting returns a specific voting referenced by its ID.

Jump to

Keyboard shortcuts

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