wanikaniapi

package module
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Mar 12, 2023 License: MIT Imports: 15 Imported by: 2

README

wanikaniapi Build Status Go Reference

A Go client for WaniKani's API.

Usage

See the full API reference on Go.dev.

Contents:

Client initialization

All API requests are made through wanikaniapi.Client. Make sure to include an API token:

package main

import (
	"os"

	"github.com/brandur/wanikaniapi"
)

func main() {
	client := wanikaniapi.NewClient(&wanikaniapi.ClientConfig{
		APIToken: os.Getenv("WANI_KANI_API_TOKEN"),
	})

	...
}
Making API requests

Use an initialized client to make API requests:

package main

import (
	"os"

	"github.com/brandur/wanikaniapi"
)

func main() {
	client := wanikaniapi.NewClient(&wanikaniapi.ClientConfig{
		APIToken: os.Getenv("WANI_KANI_API_TOKEN"),
	})

	voiceActors, err := client.VoiceActorList(&wanikaniapi.VoiceActorListParams{})
	if err != nil {
		panic(err)
	}

	...
}

Function naming follows the pattern of <API resource><Action> like AssignmentList. Most resources support *Get and *List, and some support mutating operations like *Create or *Start.

Setting API parameters

Go makes no distinction between a value that was left unset versus one set to an empty value (e.g. "" for a string), so API parameters use pointers so it can be determined which values were meant to be sent and which ones weren't.

The package provides a set of helper functions to make setting pointers easy:

package main

import (
	"os"

	"github.com/brandur/wanikaniapi"
)

func main() {
	client := wanikaniapi.NewClient(&wanikaniapi.ClientConfig{
		APIToken: os.Getenv("WANI_KANI_API_TOKEN"),
	})

	voiceActors, err := client.VoiceActorList(&wanikaniapi.VoiceActorListParams{
		IDs:          []wanikaniapi.WKID{1, 2, 3},
		UpdatedAfter: wanikaniapi.Time(time.Now()),
	})
	if err != nil {
		panic(err)
	}

	...
}

The following helpers are available:

No helpers are needed for setting slices like IDs because slices are nil by default.

Nil versus non-nil on API response structs

Values in API responses may be a pointer or non-pointer based on whether they're defined as nullable or not nullable by the WaniKani API:

type LevelProgressionData struct {
	AbandonedAt *time.Time `json:"abandoned_at"`
	CreatedAt   time.Time  `json:"created_at"`

	...

CreatedAt always has a value and is therefore time.Time. AbandonedAt may be set or unset, and is therefore *time.Time instead.

Pagination

List endpoints return list objects which contain only a single page worth of data, although they do have a pointer to where the next page's worth can be fetched:

package main

import (
	"fmt"
	"os"

	"github.com/brandur/wanikaniapi"
)

func main() {
	client := wanikaniapi.NewClient(&wanikaniapi.ClientConfig{
		APIToken: os.Getenv("WANI_KANI_API_TOKEN"),
	})

	subjects, err := client.SubjectList(&wanikaniapi.SubjectListParams{})
	if err != nil {
		panic(err)
	}

	fmt.Printf("next page URL: %+v\n", subjects.Pages.NextURL)
}

Use the PageFully helper to fully paginate an endpoint:

package main

import (
	"fmt"
	"os"

	"github.com/brandur/wanikaniapi"
)

func main() {
	client := wanikaniapi.NewClient(&wanikaniapi.ClientConfig{
		APIToken: os.Getenv("WANI_KANI_API_TOKEN"),
	})

	var subjects []*wanikaniapi.Subject
	err := client.PageFully(func(id *wanikaniapi.WKID) (*wanikaniapi.PageObject, error) {
		page, err := client.SubjectList(&wanikaniapi.SubjectListParams{
			ListParams: wanikaniapi.ListParams{
				PageAfterID: id,
			},
		})
		if err != nil {
			return nil, err
		}

		subjects = append(subjects, page.Data...)
		return &page.PageObject, nil
	})
	if err != nil {
		panic(err)
	}

	fmt.Printf("num subjects: %v\n", len(subjects))
}

But remember to cache aggressively to minimize load on WaniKani. See conditional requests below.

Logging

Configure a logger by passing a Logger parameter while initializing a client:

package main

import (
	"github.com/brandur/wanikaniapi"
)

func main() {
	client := wanikaniapi.NewClient(&wanikaniapi.ClientConfig{
		Logger: &wanikaniapi.LeveledLogger{Level: wanikaniapi.LevelDebug},
	})

	...
}

Logger expects a LeveledLoggerInterface:

type LeveledLoggerInterface interface {
	Debugf(format string, v ...interface{})
	Errorf(format string, v ...interface{})
	Infof(format string, v ...interface{})
	Warnf(format string, v ...interface{})
}

The package includes a basic logger called LeveledLogger that implements it.

Some popular loggers like Logrus and Zap's SugaredLogger also support this interface out-of-the-box so it's possible to set DefaultLeveledLogger to a *logrus.Logger or *zap.SugaredLogger directly. For others it may be necessary to write a shim layer to support them.

Handling errors

API errors are returned as the special error struct *APIError:

package main

import (
	"fmt"
	"os"

	"github.com/brandur/wanikaniapi"
)

func main() {
	client := wanikaniapi.NewClient(&wanikaniapi.ClientConfig{
		APIToken: os.Getenv("WANI_KANI_API_TOKEN"),
	})

	_, err := client.SubjectList(&wanikaniapi.SubjectListParams{})
	if err != nil {
		if apiErr, ok := err.(*wanikaniapi.APIError); ok {
			fmt.Printf("WaniKani API error; status: %v, message: %s\n",
				apiErr.StatusCode, apiErr.Message)
		} else {
			fmt.Printf("other error: %+v\n", err)
		}
	}

	...
}

API calls may still return non-APIError errors for non-API problems (e.g. network error, TLS error, unmarshaling error, etc.).

Configuring HTTP client

Pass your own HTTP client into wanikaniapi.NewClient:

package main

import (
	"fmt"
    "net/http"
	"os"
    "time"

	"github.com/brandur/wanikaniapi"
)

func main() {
	httpClient := &http.Client{
		Transport: &http.Transport{
			MaxIdleConns:       10,
			IdleConnTimeout:    30 * time.Second,
			DisableCompression: true,
		},
	}

	client := wanikaniapi.NewClient(&wanikaniapi.ClientConfig{
		APIToken:   os.Getenv("WANI_KANI_API_TOKEN"),
		HTTPClient: httpClient,
	})

    ...
}
Contexts

Go contexts can be passed through Params:

package main

import (
	"context"
	"os"

	"github.com/brandur/wanikaniapi"
)

func main() {
	client := wanikaniapi.NewClient(&wanikaniapi.ClientConfig{
		APIToken: os.Getenv("WANI_KANI_API_TOKEN"),
	})

	_, err := client.SubjectList(&wanikaniapi.SubjectListParams{
		Params: wanikaniapi.Params{
			Context: &ctx,
		},
	})
	if err != nil {
		panic(err)
	}

	...
}
Conditional requests

Conditional requests reduce load on the server by asking for a response only when data has changed. There are two separate mechanisms for this: If-Modified-Since and If-None-Match.

If-Modified-Since works by feeding a value of the Last-Modified header into future requests:

package main

import (
	"os"

	"github.com/brandur/wanikaniapi"
)

func main() {
	client := wanikaniapi.NewClient(&wanikaniapi.ClientConfig{
		APIToken: os.Getenv("WANI_KANI_API_TOKEN"),
	})

	subjects1, err := client.SubjectList(&wanikaniapi.SubjectListParams{})
	if err != nil {
		panic(err)
	}

	subjects2, err := client.SubjectList(&wanikaniapi.SubjectListParams{
		Params: wanikaniapi.Params{
			IfModifiedSince: wanikaniapi.Time(subjects1.LastModified),
		},
	})
	if err != nil {
		panic(err)
	}

	...
}

If-None-Match works by feeding a value of the Etag header into future requests:

package main

import (
	"os"

	"github.com/brandur/wanikaniapi"
)

func main() {
	client := wanikaniapi.NewClient(&wanikaniapi.ClientConfig{
		APIToken: os.Getenv("WANI_KANI_API_TOKEN"),
	})

	subjects1, err := client.SubjectList(&wanikaniapi.SubjectListParams{})
	if err != nil {
		panic(err)
	}

	subjects2, err := client.SubjectList(&wanikaniapi.SubjectListParams{
		Params: wanikaniapi.Params{
			IfNoneMatch: wanikaniapi.String(subjects1.ETag),
		},
	})
	if err != nil {
		panic(err)
	}

	...
}
Automatic retries

The client can be configured to automatically retry errors that are known to be safe to retry:

package main

import (
	"os"

	"github.com/brandur/wanikaniapi"
)

func main() {
	client := wanikaniapi.NewClient(&wanikaniapi.ClientConfig{
		APIToken:   os.Getenv("WANI_KANI_API_TOKEN"),
		MaxRetries: 2,
	})

	...
}

Development

Run tests

Run the test suite:

go test .

Tests generally compare recorded requests so that they don't have to make live API calls, but there are a few tests for the trickier cases which will only run when an API token is set:

export WANI_KANI_API_TOKEN=
go test .
Gofmt

All code expects to be formatted. Check the current state with:

scripts/check_gofmt.sh

Format code with:

gofmt -w -s *.go
Creating a release
  • Add entry and summarize changes to CHANGELOG.md.
  • Commit changes with message like "Bump to v0.1.0".
  • Tag with git tag v0.1.0.
  • Push commit and tag with git push --tags origin master.

Make sure to follow semantic versioning and introduce breaking changes only across major versions. Publish as few major versions as possible though, so try not to introduce breaking changes.

Major version changes will also necessitate changes in the Go import path like a bump from /v1 to /v2. See publishing Go modules.

Documentation

Overview

Package wanikaniapi provides a Go language API library for the WaniKani API.

Index

Examples

Constants

View Source
const (
	ObjectTypeAssignment             = WKObjectType("assignment")
	ObjectTypeCollection             = WKObjectType("collection")
	ObjectTypeKanji                  = WKObjectType("kanji")
	ObjectTypeLevelProgression       = WKObjectType("level_progression")
	ObjectTypeRadical                = WKObjectType("radical")
	ObjectTypeReport                 = WKObjectType("report")
	ObjectTypeReset                  = WKObjectType("reset")
	ObjectTypeReview                 = WKObjectType("review")
	ObjectTypeReviewStatistic        = WKObjectType("review_statistic")
	ObjectTypeSpacedRepetitionSystem = WKObjectType("spaced_repetition_system")
	ObjectTypeStudyMaterial          = WKObjectType("study_material")
	ObjectTypeUser                   = WKObjectType("user")
	ObjectTypeVocabulary             = WKObjectType("vocabulary")
	ObjectTypeVoiceActor             = WKObjectType("voice_actor")
)

Constants for the various object types that may be returned in the object field of WaniKani's API resources.

View Source
const WaniKaniAPIURL = "https://api.wanikani.com"

WaniKaniAPIURL is the base URL of the WaniKani API.

View Source
const WaniKaniRevision = "20170710"

WaniKaniRevision is the revision of the WaniKani API.

Variables

This section is empty.

Functions

func Bool

func Bool(b bool) *bool

Bool is a helper function that returns a pointer to the given value. This is useful for setting values in parameter structs.

func Int

func Int(i int) *int

Int is a helper function that returns a pointer to the given value. This is useful for setting values in parameter structs.

func String

func String(s string) *string

String is a helper function that returns a pointer to the given value. This is useful for setting values in parameter structs.

Types

type APIError

type APIError struct {
	// Error is the error message that came back with the API error.
	//
	// This is called Message instead of Error so as not to conflict with the
	// Error function on Go's error interface.
	Message string `json:"error"`

	// StatusCode is the HTTP status code that came back with the API error.
	StatusCode int `json:"code"`
}

APIError represents an HTTP status API error that came back from WaniKani's API. It may be caused by a variety of problems like a bad access token resulting in a 401 Unauthorized or making too many requests resulting in a 429 Too Many Requests.

Inspect Code and Error for details, and see the API reference for more information:

https://docs.api.wanikani.com/20170710/#errors

func (APIError) Error

func (e APIError) Error() string

Error returns the error message that came back with the API error.

type Assignment

type Assignment struct {
	Object
	Data *AssignmentData `json:"data"`
}

Assignment contains information about a user's progress on a particular subject, including their current state and timestamps for various progress milestones. Assignments are created when a user has passed all the components of the given subject and the assignment is at or below their current level for the first time.

type AssignmentData

type AssignmentData struct {
	AvailableAt   *time.Time   `json:"available_at"`
	BurnedAt      *time.Time   `json:"burned_at"`
	CreatedAt     time.Time    `json:"created_at"`
	Hidden        bool         `json:"hidden"`
	PassedAt      *time.Time   `json:"passed_at"`
	ResurrectedAt *time.Time   `json:"resurrected_at"`
	SRSStage      int          `json:"srs_stage"`
	StartedAt     *time.Time   `json:"started_at"`
	SubjectID     WKID         `json:"subject_id"`
	SubjectType   WKObjectType `json:"subject_type"`
	UnlockedAt    *time.Time   `json:"unlocked_at"`
}

AssignmentData contains core data of Assignment.

type AssignmentGetParams

type AssignmentGetParams struct {
	Params
	ID *WKID
}

AssignmentGetParams are parameters for AssignmentGet.

type AssignmentListParams

type AssignmentListParams struct {
	ListParams
	Params

	AvailableAfter                 *WKTime
	AvailableBefore                *WKTime
	Burned                         *bool
	Hidden                         *bool
	IDs                            []WKID
	ImmediatelyAvailableForLessons *bool
	ImmediatelyAvailableForReview  *bool
	InReview                       *bool
	Levels                         []int
	SRSStages                      []int
	Started                        *bool
	SubjectIDs                     []WKID
	SubjectTypes                   []WKObjectType `json:"subject_types"`
	Unlocked                       *bool
	UpdatedAfter                   *WKTime
}

AssignmentListParams are parameters for AssignmentList.

func (*AssignmentListParams) EncodeToQuery

func (p *AssignmentListParams) EncodeToQuery() string

EncodeToQuery encodes parametes to a query string.

type AssignmentPage

type AssignmentPage struct {
	PageObject
	Data []*Assignment `json:"data"`
}

AssignmentPage represents a single page of Assignments.

type AssignmentStartParams

type AssignmentStartParams struct {
	Params
	ID        *WKID   `json:"-"`
	StartedAt *WKTime `json:"started_at"`
}

AssignmentStartParams are parameters for AssignmentStart.

type Client

type Client struct {
	// APIToken is the WaniKani API token to use for authentication.
	APIToken string

	// Logger is the logger to send logging messages to.
	Logger LeveledLoggerInterface

	// MaxRetries is the maximum number of retries for network errors and other
	// types of error.
	MaxRetries int

	// NoRetrySleep forces the client to not sleep on retries. This is for
	// testing only. Don't use.
	NoRetrySleep bool

	// RecordMode stubs out any actual HTTP calls, and instead starts storing
	// request data to RecordedRequests.
	RecordMode bool

	// RecordedRequests are requests that have been recorded when RecordMode is
	// on. This is generally used only in tests.
	RecordedRequests []*RecordedRequest

	// RecordedResponses are responses to be injected when RecordMode is on.
	// This is generally used only in tests.
	RecordedResponses []*RecordedResponse
	// contains filtered or unexported fields
}

Client is a WaniKani API client.

Example (ConditionalRequestsIfModifiedSince)
package main

import (
	"fmt"
	"os"

	"github.com/brandur/wanikaniapi"
)

func main() {
	client := wanikaniapi.NewClient(&wanikaniapi.ClientConfig{
		APIToken: os.Getenv("WANI_KANI_API_TOKEN"),
	})

	subjects1, err := client.SubjectList(&wanikaniapi.SubjectListParams{})
	if err != nil {
		panic(err)
	}

	subjects2, err := client.SubjectList(&wanikaniapi.SubjectListParams{
		Params: wanikaniapi.Params{
			IfModifiedSince: wanikaniapi.Time(*subjects1.LastModified),
		},
	})
	if err != nil {
		panic(err)
	}

	fmt.Printf("not modified 1: %v\n", subjects1.NotModified)
	fmt.Printf("not modified 2: %v\n", subjects2.NotModified)
}
Output:

Example (ConditionalRequestsIfNoneMatch)
package main

import (
	"fmt"
	"os"

	"github.com/brandur/wanikaniapi"
)

func main() {
	client := wanikaniapi.NewClient(&wanikaniapi.ClientConfig{
		APIToken: os.Getenv("WANI_KANI_API_TOKEN"),
	})

	subjects1, err := client.SubjectList(&wanikaniapi.SubjectListParams{})
	if err != nil {
		panic(err)
	}

	subjects2, err := client.SubjectList(&wanikaniapi.SubjectListParams{
		Params: wanikaniapi.Params{
			IfNoneMatch: wanikaniapi.String(subjects1.ETag),
		},
	})
	if err != nil {
		panic(err)
	}

	fmt.Printf("not modified 1: %v\n", subjects1.NotModified)
	fmt.Printf("not modified 2: %v\n", subjects2.NotModified)
}
Output:

Example (ConfiguringHTTPClient)
package main

import (
	"net/http"
	"os"
	"time"

	"github.com/brandur/wanikaniapi"
)

func main() {
	httpClient := &http.Client{
		Transport: &http.Transport{
			MaxIdleConns:       10,
			IdleConnTimeout:    30 * time.Second,
			DisableCompression: true,
		},
	}

	_ = wanikaniapi.NewClient(&wanikaniapi.ClientConfig{
		APIToken:   os.Getenv("WANI_KANI_API_TOKEN"),
		HTTPClient: httpClient,
	})
}
Output:

Example (Contexts)
package main

import (
	"context"
	"os"

	"github.com/brandur/wanikaniapi"
)

func main() {
	client := wanikaniapi.NewClient(&wanikaniapi.ClientConfig{
		APIToken: os.Getenv("WANI_KANI_API_TOKEN"),
	})

	ctx := context.Background()

	_, err := client.SubjectList(&wanikaniapi.SubjectListParams{
		Params: wanikaniapi.Params{
			Context: &ctx,
		},
	})
	if err != nil {
		panic(err)
	}
}
Output:

Example (HandlingErrors)
package main

import (
	"fmt"
	"os"

	"github.com/brandur/wanikaniapi"
)

func main() {
	client := wanikaniapi.NewClient(&wanikaniapi.ClientConfig{
		APIToken: os.Getenv("WANI_KANI_API_TOKEN"),
	})

	_, err := client.SubjectList(&wanikaniapi.SubjectListParams{})
	if err != nil {
		if apiErr, ok := err.(*wanikaniapi.APIError); ok {
			fmt.Printf("WaniKani API error; status: %v, message: %s\n",
				apiErr.StatusCode, apiErr.Message)
		} else {
			fmt.Printf("other error: %+v\n", err)
		}
	}
}
Output:

Example (Initialize)
package main

import (
	"os"

	"github.com/brandur/wanikaniapi"
)

func main() {
	_ = wanikaniapi.NewClient(&wanikaniapi.ClientConfig{
		APIToken: os.Getenv("WANI_KANI_API_TOKEN"),
	})
}
Output:

Example (Logging)
package main

import (
	"github.com/brandur/wanikaniapi"
)

func main() {
	_ = wanikaniapi.NewClient(&wanikaniapi.ClientConfig{
		Logger: &wanikaniapi.LeveledLogger{Level: wanikaniapi.LevelDebug},
	})
}
Output:

Example (MakingAPIRequests)
package main

import (
	"fmt"
	"os"

	"github.com/brandur/wanikaniapi"
)

func main() {
	client := wanikaniapi.NewClient(&wanikaniapi.ClientConfig{
		APIToken: os.Getenv("WANI_KANI_API_TOKEN"),
	})

	voiceActors, err := client.VoiceActorList(&wanikaniapi.VoiceActorListParams{})
	if err != nil {
		panic(err)
	}

	fmt.Printf("all voice actors: %+v\n", voiceActors)
}
Output:

Example (SettingAPIParameters)
package main

import (
	"fmt"
	"os"
	"time"

	"github.com/brandur/wanikaniapi"
)

func main() {
	client := wanikaniapi.NewClient(&wanikaniapi.ClientConfig{
		APIToken: os.Getenv("WANI_KANI_API_TOKEN"),
	})

	voiceActors, err := client.VoiceActorList(&wanikaniapi.VoiceActorListParams{
		IDs:          []wanikaniapi.WKID{1, 2, 3},
		UpdatedAfter: wanikaniapi.Time(time.Now()),
	})
	if err != nil {
		panic(err)
	}

	fmt.Printf("all voice actors: %+v\n", voiceActors)
}
Output:

Example (SinglePage)
package main

import (
	"fmt"
	"os"

	"github.com/brandur/wanikaniapi"
)

func main() {
	client := wanikaniapi.NewClient(&wanikaniapi.ClientConfig{
		APIToken: os.Getenv("WANI_KANI_API_TOKEN"),
	})

	subjects, err := client.SubjectList(&wanikaniapi.SubjectListParams{})
	if err != nil {
		panic(err)
	}

	fmt.Printf("next page URL: %+v\n", subjects.Pages.NextURL)
}
Output:

func NewClient

func NewClient(config *ClientConfig) *Client

NewClient returns a new WaniKani API client.

func (*Client) AssignmentGet

func (c *Client) AssignmentGet(params *AssignmentGetParams) (*Assignment, error)

AssignmentGet retrieves a specific assignment by its ID.

func (*Client) AssignmentList

func (c *Client) AssignmentList(params *AssignmentListParams) (*AssignmentPage, error)

AssignmentList returns a collection of all assignments, ordered by ascending CreatedAt, 500 at a time.

func (*Client) AssignmentStart

func (c *Client) AssignmentStart(params *AssignmentStartParams) (*Assignment, error)

AssignmentStart marks the assignment as started, moving the assignment from the lessons queue to the review queue. Returns the updated assignment.

func (*Client) LevelProgressionGet

func (c *Client) LevelProgressionGet(params *LevelProgressionGetParams) (*LevelProgression, error)

LevelProgressionGet retrieves a specific level progression by its ID.

func (*Client) LevelProgressionList

func (c *Client) LevelProgressionList(params *LevelProgressionListParams) (*LevelProgressionPage, error)

LevelProgressionList returns a collection of all level progressions, ordered by ascending CreatedAt, 500 at a time.

func (*Client) PageFully

func (c *Client) PageFully(onPage func(*WKID) (*PageObject, error)) error

PageFully is a helper for fully paginating a resource in the WaniKani API.

Example
package main

import (
	"fmt"
	"os"

	"github.com/brandur/wanikaniapi"
)

func main() {
	client := wanikaniapi.NewClient(&wanikaniapi.ClientConfig{
		APIToken: os.Getenv("WANI_KANI_API_TOKEN"),
	})

	var subjects []*wanikaniapi.Subject
	err := client.PageFully(func(id *wanikaniapi.WKID) (*wanikaniapi.PageObject, error) {
		page, err := client.SubjectList(&wanikaniapi.SubjectListParams{
			ListParams: wanikaniapi.ListParams{
				PageAfterID: id,
			},
		})
		if err != nil {
			return nil, err
		}

		subjects = append(subjects, page.Data...)
		return &page.PageObject, nil
	})
	if err != nil {
		panic(err)
	}

	fmt.Printf("num subjects: %v\n", len(subjects))
}
Output:

func (*Client) ResetGet

func (c *Client) ResetGet(params *ResetGetParams) (*Reset, error)

ResetGet retrieves a specific reset by its ID.

func (*Client) ResetList

func (c *Client) ResetList(params *ResetListParams) (*ResetPage, error)

ResetList returns a collection of all resets, ordered by ascending CreatedAt, 500 at a time.

func (*Client) ReviewCreate

func (c *Client) ReviewCreate(params *ReviewCreateParams) (*Review, error)

ReviewCreate creates a review for a specific AssignmentID. Using the related subject_id is also a valid alternative to using AssignmentID.

Some criteria must be met in order for a review to be created: AvailableAt must be not null and in the past.

When a review is registered, the associated assignment and review statistic are both updated. These are returned in the response body under ResourcesUpdated.

func (*Client) ReviewGet

func (c *Client) ReviewGet(params *ReviewGetParams) (*Review, error)

ReviewGet retrieves a specific review by its ID.

func (*Client) ReviewList

func (c *Client) ReviewList(params *ReviewListParams) (*ReviewPage, error)

ReviewList returns a collection of all reviews, ordered by ascending CreatedAt, 1000 at a time.

func (*Client) ReviewStatisticGet

func (c *Client) ReviewStatisticGet(params *ReviewStatisticGetParams) (*ReviewStatistic, error)

ReviewStatisticGet retrieves a specific review statistic by its ID.

func (*Client) ReviewStatisticList

func (c *Client) ReviewStatisticList(params *ReviewStatisticListParams) (*ReviewStatisticPage, error)

ReviewStatisticList returns a collection of all review statistics, ordered by ascending CreatedAt, 500 at a time.

func (*Client) SpacedRepetitionSystemGet

func (c *Client) SpacedRepetitionSystemGet(params *SpacedRepetitionSystemGetParams) (*SpacedRepetitionSystem, error)

SpacedRepetitionSystemGet retrieves a specific spaced repetition system by its ID.

func (*Client) SpacedRepetitionSystemList

func (c *Client) SpacedRepetitionSystemList(params *SpacedRepetitionSystemListParams) (*SpacedRepetitionSystemPage, error)

SpacedRepetitionSystemList returns a collection of all spaced repetition systems, ordered by ascending ID, 500 at a time.

func (*Client) StudyMaterialCreate

func (c *Client) StudyMaterialCreate(params *StudyMaterialCreateParams) (*StudyMaterial, error)

StudyMaterialCreate creates a study material for a specific subject.

The owner of the API key can only create one study material per subject.

func (*Client) StudyMaterialGet

func (c *Client) StudyMaterialGet(params *StudyMaterialGetParams) (*StudyMaterial, error)

StudyMaterialGet retrieves a specific study material by its ID.

func (*Client) StudyMaterialList

func (c *Client) StudyMaterialList(params *StudyMaterialListParams) (*StudyMaterialPage, error)

StudyMaterialList returns a collection of all study material, ordered by ascending CreatedAt, 500 at a time.

func (*Client) StudyMaterialUpdate

func (c *Client) StudyMaterialUpdate(params *StudyMaterialUpdateParams) (*StudyMaterial, error)

StudyMaterialUpdate updates a study material for a specific ID.

func (*Client) SubjectGet

func (c *Client) SubjectGet(params *SubjectGetParams) (*Subject, error)

SubjectGet retrieves a specific subject by its ID. The structure of the response depends on the subject type.

func (*Client) SubjectList

func (c *Client) SubjectList(params *SubjectListParams) (*SubjectPage, error)

SubjectList returns a collection of all subjects, ordered by ascending CreatedAt, 1000 at a time.

func (*Client) SummaryGet

func (c *Client) SummaryGet(params *SummaryGetParams) (*Summary, error)

SummaryGet retrieves a summary report.

func (*Client) UserGet

func (c *Client) UserGet(params *UserGetParams) (*User, error)

UserGet returns a summary of user information.

func (*Client) UserUpdate

func (c *Client) UserUpdate(params *UserUpdateParams) (*User, error)

UserUpdate returns an updated summary of user information.

func (*Client) VoiceActorGet

func (c *Client) VoiceActorGet(params *VoiceActorGetParams) (*VoiceActor, error)

VoiceActorGet retrieves a specific voice_actor by its ID.

func (*Client) VoiceActorList

func (c *Client) VoiceActorList(params *VoiceActorListParams) (*VoiceActorPage, error)

VoiceActorList returns a collection of all voice actors, ordered by ascending CreatedAt, 500 at a time.

type ClientConfig

type ClientConfig struct {
	// APIToken is the WaniKani API token to use for authentication.
	APIToken string

	// HTTPClient is your own HTTP client. The library will otherwise use a
	// parameter-less `&http.Client{}`, resulting in default everything.
	HTTPClient *http.Client

	// Logger is the logger to send logging messages to.
	Logger LeveledLoggerInterface

	// MaxRetries is the maximum number of retries for network errors and other
	// types of error. Defaults to zero.
	MaxRetries int
}

ClientConfig specifies configuration with which to initialize a WaniKani API client.

type Level

type Level uint32

Level represents a logging level.

const (
	// LevelNull sets a logger to show no messages at all.
	LevelNull Level = 0

	// LevelError sets a logger to show error messages only.
	LevelError Level = 1

	// LevelWarn sets a logger to show warning messages or anything more
	// severe.
	LevelWarn Level = 2

	// LevelInfo sets a logger to show informational messages or anything more
	// severe.
	LevelInfo Level = 3

	// LevelDebug sets a logger to show informational messages or anything more
	// severe.
	LevelDebug Level = 4
)

type LevelProgression

type LevelProgression struct {
	Object
	Data *LevelProgressionData `json:"data"`
}

LevelProgression contains information about a user's progress through the WaniKani levels.

type LevelProgressionData

type LevelProgressionData struct {
	AbandonedAt *time.Time `json:"abandoned_at"`
	CompletedAt *time.Time `json:"completed_at"`
	CreatedAt   time.Time  `json:"created_at"`
	Level       int        `json:"level"`
	PassedAt    *time.Time `json:"passed_at"`
	StartedAt   *time.Time `json:"started_at"`
	UnlockedAt  *time.Time `json:"unlocked_at"`
}

LevelProgressionData contains core data of LevelProgression.

type LevelProgressionGetParams

type LevelProgressionGetParams struct {
	Params
	ID *WKID
}

LevelProgressionGetParams are parameters for LevelProgressionGet.

type LevelProgressionListParams

type LevelProgressionListParams struct {
	ListParams
	Params

	IDs          []WKID
	UpdatedAfter *WKTime
}

LevelProgressionListParams are parameters for LevelProgressionList.

func (*LevelProgressionListParams) EncodeToQuery

func (p *LevelProgressionListParams) EncodeToQuery() string

EncodeToQuery encodes parametes to a query string.

type LevelProgressionPage

type LevelProgressionPage struct {
	PageObject
	Data []*LevelProgression `json:"data"`
}

LevelProgressionPage represents a single page of LevelProgressions.

type LeveledLogger

type LeveledLogger struct {
	// Level is the minimum logging level that will be emitted by this logger.
	//
	// For example, a Level set to LevelWarn will emit warnings and errors, but
	// not informational or debug messages.
	//
	// Always set this with a constant like LevelWarn because the individual
	// values are not guaranteed to be stable.
	Level Level
	// contains filtered or unexported fields
}

LeveledLogger is a leveled logger implementation.

It prints warnings and errors to `os.Stderr` and other messages to `os.Stdout`.

func (*LeveledLogger) Debugf

func (l *LeveledLogger) Debugf(format string, v ...interface{})

Debugf logs a debug message using Printf conventions.

func (*LeveledLogger) Errorf

func (l *LeveledLogger) Errorf(format string, v ...interface{})

Errorf logs a warning message using Printf conventions.

func (*LeveledLogger) Infof

func (l *LeveledLogger) Infof(format string, v ...interface{})

Infof logs an informational message using Printf conventions.

func (*LeveledLogger) Warnf

func (l *LeveledLogger) Warnf(format string, v ...interface{})

Warnf logs a warning message using Printf conventions.

type LeveledLoggerInterface

type LeveledLoggerInterface interface {
	// Debugf logs a debug message using Printf conventions.
	Debugf(format string, v ...interface{})

	// Errorf logs a warning message using Printf conventions.
	Errorf(format string, v ...interface{})

	// Infof logs an informational message using Printf conventions.
	Infof(format string, v ...interface{})

	// Warnf logs a warning message using Printf conventions.
	Warnf(format string, v ...interface{})
}

LeveledLoggerInterface provides a basic leveled logging interface for printing debug, informational, warning, and error messages.

It's implemented by LeveledLogger and also provides out-of-the-box compatibility with a Logrus Logger, but may require a thin shim for use with other logging libraries that you use less standard conventions like Zap.

type ListParams

type ListParams struct {
	PageAfterID  *WKID
	PageBeforeID *WKID
}

ListParams contains the common parameters for every list endpoint in the WaniKani API.

type Object

type Object struct {
	DataUpdatedAt time.Time `json:"data_updated_at"`
	ID            WKID      `json:"id"`

	// ETag is an opaque token that can be used to make conditional requests by
	// passing its value to Params.IfNoneMatch for a future request.
	ETag string `json:"-"`

	// LastModified is a date that can be used to make conditional requests by
	// passing its value to Params.IfModifiedSince for a future request. It's
	// returned on most requests, but may not be for specific parameter
	// combinations.
	LastModified *time.Time `json:"-"`

	// NotModified is set to true if the response indicated not modified when a
	// `If-None-Match` or `If-Modified-Since` header was passed in.
	NotModified bool `json:"-"`

	ObjectType WKObjectType `json:"object"`
	URL        string       `json:"url"`
}

Object contains the common fields of every resource in the WaniKani API.

func (*Object) GetObject

func (o *Object) GetObject() *Object

GetObject returns the underlying Object object.

type ObjectInterface

type ObjectInterface interface {
	GetObject() *Object
}

ObjectInterface is a common interface implemented by response structures.

type PageObject

type PageObject struct {
	Object

	TotalCount int64 `json:"total_count"`

	Pages struct {
		NextURL     string `json:"next_url"`
		PerPage     int    `json:"per_page"`
		PreviousURL string `json:"previous_url"`
	} `json:"pages"`
}

PageObject contains the common fields of every list resource in the WaniKani API.

type Params

type Params struct {
	// Context is a Go context that's injected into API requests.
	Context *context.Context `json:"-"`

	// IfModifiedSince sets a value for the `If-Modified-Since` header so that
	// a response is conditional on an update since the last given time.
	IfModifiedSince *WKTime `json:"-"`

	// IfNoneMatch sets a value for the `If-None-Match` header so that a
	// response is conditional on an update since the last given Etag.
	IfNoneMatch *string `json:"-"`
}

Params contains the common fields of every resource in the WaniKani API.

func (*Params) EncodeToQuery

func (p *Params) EncodeToQuery() string

EncodeToQuery encodes the parameters to be included in a query string. Defaults to encoding to an empty string.

func (*Params) GetParams

func (p *Params) GetParams() *Params

GetParams returns the underlying Params object.

type ParamsInterface

type ParamsInterface interface {
	// EncodeToQuery encodes the parameters to be included in a query string.
	EncodeToQuery() string

	// GetParams returns the underlying Params object.
	GetParams() *Params
}

ParamsInterface is a common interface implemented by parameters.

type RecordedRequest

type RecordedRequest struct {
	Body   []byte
	Header http.Header
	Method string
	Path   string
	Query  string
}

RecordedRequest is a request recorded when RecordMode is on.

type RecordedResponse

type RecordedResponse struct {
	Body       []byte
	StatusCode int
}

RecordedResponse is a reponse injected when RecordMode is on.

type Reset

type Reset struct {
	Object
	Data *ResetData `json:"data"`
}

Reset represents a user reset.

Users can reset their progress back to any level at or below their current level. When they reset to a particular level, all of the assignments and review_statistics at that level or higher are set back to their default state.

Resets contain information about when those resets happen, the starting level, and the target level.

type ResetData

type ResetData struct {
	ConfirmedAt   *time.Time `json:"confirmed_at"`
	CreatedAt     time.Time  `json:"created_at"`
	OriginalLevel int        `json:"original_evel"`
	TargetLevel   int        `json:"target_level"`
}

ResetData contains core data of Reset.

type ResetGetParams

type ResetGetParams struct {
	Params
	ID *WKID
}

ResetGetParams are parameters for ResetGet.

type ResetListParams

type ResetListParams struct {
	ListParams
	Params

	IDs          []WKID
	UpdatedAfter *WKTime
}

ResetListParams are parameters for ResetList.

func (*ResetListParams) EncodeToQuery

func (p *ResetListParams) EncodeToQuery() string

EncodeToQuery encodes parametes to a query string.

type ResetPage

type ResetPage struct {
	PageObject
	Data []*Reset `json:"data"`
}

ResetPage represents a single page of Resets.

type Review

type Review struct {
	Object
	Data *ReviewData `json:"data"`
}

Review logs all the correct and incorrect answers provided through the 'Reviews' section of WaniKani. Review records are created when a user answers all the parts of a subject correctly once; some subjects have both meaning or reading parts, and some only have one or the other. Note that reviews are not created for the quizzes in lessons.

type ReviewCreateParams

type ReviewCreateParams struct {
	Params
	AssignmentID            *WKID   `json:"assignment_id,omitempty"`
	CreatedAt               *WKTime `json:"created_at,omitempty"`
	IncorrectMeaningAnswers *int    `json:"incorrect_meaning_answers,omitempty"`
	IncorrectReadingAnswers *int    `json:"incorrect_reading_answers,omitempty"`
	SubjectID               *WKID   `json:"subject_id,omitempty"`
}

ReviewCreateParams are parameters for ReviewCreate.

type ReviewData

type ReviewData struct {
	AssignmentID             WKID      `json:"assignment_id"`
	CreatedAt                time.Time `json:"created_at"`
	EndingSRSStage           int       `json:"ending_srs_stage"`
	IncorrectMeaningAnswers  int       `json:"incorrect_meaning_answers"`
	IncorrectReadingAnswers  int       `json:"incorrect_reading_answers"`
	SpacedRepetitionSystemID WKID      `json:"spaced_repetition_system_id"`
	StartingSRSStage         int       `json:"starting_srs_stage"`
	SubjectID                WKID      `json:"subject_id"`
}

ReviewData contains core data of Review.

type ReviewGetParams

type ReviewGetParams struct {
	Params
	ID *WKID
}

ReviewGetParams are parameters for ReviewGet.

type ReviewListParams

type ReviewListParams struct {
	ListParams
	Params

	AssignmentIDs []WKID
	IDs           []WKID
	SubjectIDs    []WKID
	UpdatedAfter  *WKTime
}

ReviewListParams are parameters for ReviewList.

func (*ReviewListParams) EncodeToQuery

func (p *ReviewListParams) EncodeToQuery() string

EncodeToQuery encodes parametes to a query string.

type ReviewPage

type ReviewPage struct {
	PageObject
	Data []*Review `json:"data"`
}

ReviewPage represents a single page of Reviews.

type ReviewStatistic

type ReviewStatistic struct {
	Object
	Data *ReviewStatisticData `json:"data"`
}

ReviewStatistic summarizes the activity recorded in reviews. They contain sum the number of correct and incorrect answers for both meaning and reading. They track current and maximum streaks of correct answers. They store the overall percentage of correct answers versus total answers.

A review statistic is created when the user has done their first review on the related subject.

type ReviewStatisticData

type ReviewStatisticData struct {
	CreatedAt            time.Time    `json:"created_at"`
	Hidden               bool         `json:"hidden"`
	MeaningCorrect       int          `json:"meaning_correct"`
	MeaningCurrentStreak int          `json:"meaning_current_streak"`
	MeaningIncorrect     int          `json:"meaning_incorrect"`
	MeaningMaxStreak     int          `json:"meaning_max_streak"`
	PercentageCorrect    int          `json:"percentage_correct"`
	ReadingCorrect       int          `json:"reading_correct"`
	ReadingCurrentStreak int          `json:"reading_current_streak"`
	ReadingIncorrect     int          `json:"reading_incorrect"`
	ReadingMaxStreak     int          `json:"reading_max_streak"`
	SubjectID            WKID         `json:"subject_id"`
	SubjectType          WKObjectType `json:"subject_type"`
}

ReviewStatisticData contains core data of ReviewStatistic.

type ReviewStatisticGetParams

type ReviewStatisticGetParams struct {
	Params
	ID *WKID
}

ReviewStatisticGetParams are parameters for ReviewStatisticGet.

type ReviewStatisticListParams

type ReviewStatisticListParams struct {
	ListParams
	Params

	Hidden                 *bool
	IDs                    []WKID
	PercentagesGreaterThan *int
	PercentagesLesserThan  *int
	SubjectIDs             []WKID
	SubjectTypes           []WKObjectType
	UpdatedAfter           *WKTime
}

ReviewStatisticListParams are parameters for ReviewStatisticList.

func (*ReviewStatisticListParams) EncodeToQuery

func (p *ReviewStatisticListParams) EncodeToQuery() string

EncodeToQuery encodes parametes to a query string.

type ReviewStatisticPage

type ReviewStatisticPage struct {
	PageObject
	Data []*ReviewStatistic `json:"data"`
}

ReviewStatisticPage represents a single page of ReviewStatistics.

type SpacedRepetitionSystem

type SpacedRepetitionSystem struct {
	Object
	Data *SpacedRepetitionSystemData `json:"data"`
}

SpacedRepetitionSystem is an available spaced repetition system used for calculating SRSStage changes to Assignments and Reviews. Has relationship with Subjects.

type SpacedRepetitionSystemData

type SpacedRepetitionSystemData struct {
	BurningStagePosition   int                                   `json:"burning_stage_position"`
	CreatedAt              time.Time                             `json:"created_at"`
	Description            string                                `json:"description"`
	Name                   string                                `json:"name"`
	PassingStagePosition   int                                   `json:"passing_stage_position"`
	Stages                 []*SpacedRepetitionSystemStagedObject `json:"stages"`
	StartingStagePosition  int                                   `json:"starting_stage_position"`
	UnlockingStagePosition int                                   `json:"unlocking_stage_position"`
}

SpacedRepetitionSystemData contains core data of SpacedRepetitionSystem.

type SpacedRepetitionSystemGetParams

type SpacedRepetitionSystemGetParams struct {
	Params
	ID *WKID
}

SpacedRepetitionSystemGetParams are parameters for SpacedRepetitionSystemGet.

type SpacedRepetitionSystemListParams

type SpacedRepetitionSystemListParams struct {
	ListParams
	Params

	IDs          []WKID
	UpdatedAfter *WKTime
}

SpacedRepetitionSystemListParams are parameters for SpacedRepetitionSystemList.

func (*SpacedRepetitionSystemListParams) EncodeToQuery

func (p *SpacedRepetitionSystemListParams) EncodeToQuery() string

EncodeToQuery encodes parametes to a query string.

type SpacedRepetitionSystemPage

type SpacedRepetitionSystemPage struct {
	PageObject
	Data []*SpacedRepetitionSystem `json:"data"`
}

SpacedRepetitionSystemPage represents a single page of SpacedRepetitionSystems.

type SpacedRepetitionSystemStagedObject

type SpacedRepetitionSystemStagedObject struct {
	Interval     *int    `json:"interval"`
	IntervalUnit *string `json:"interval_unit"`
	Position     int     `json:"position"`
}

SpacedRepetitionSystemStagedObject represents an spaced repetition stage.

type StudyMaterial

type StudyMaterial struct {
	Object
	Data *StudyMaterialData `json:"data"`
}

StudyMaterial is a store of user-specific notes and synonyms for a given subject. The records are created as soon as the user enters any study information.

type StudyMaterialCreateParams

type StudyMaterialCreateParams struct {
	Params
	MeaningNote     *string  `json:"meaning_note,omitempty"`
	MeaningSynonyms []string `json:"meaning_synonyms,omitempty"`
	ReadingNote     *string  `json:"reading_note,omitempty"`
	SubjectID       *WKID    `json:"subject_id,omitempty"`
}

StudyMaterialCreateParams are parameters for StudyMaterialCreate.

type StudyMaterialData

type StudyMaterialData struct {
	CreatedAt       time.Time    `json:"created_at"`
	Hidden          bool         `json:"hidden"`
	MeaningNote     *string      `json:"meaning_note"`
	MeaningSynonyms []string     `json:"meaning_synonyms"`
	ReadingNote     *string      `json:"reading_note"`
	SubjectID       WKID         `json:"subject_id"`
	SubjectType     WKObjectType `json:"subject_type"`
}

StudyMaterialData contains core data of StudyMaterial.

type StudyMaterialGetParams

type StudyMaterialGetParams struct {
	Params
	ID *WKID
}

StudyMaterialGetParams are parameters for StudyMaterialGet.

type StudyMaterialListParams

type StudyMaterialListParams struct {
	ListParams
	Params

	Hidden       *bool
	IDs          []WKID
	SubjectIDs   []WKID
	SubjectTypes []WKObjectType
	UpdatedAfter *WKTime
}

StudyMaterialListParams are parameters for StudyMaterialList.

func (*StudyMaterialListParams) EncodeToQuery

func (p *StudyMaterialListParams) EncodeToQuery() string

EncodeToQuery encodes parametes to a query string.

type StudyMaterialPage

type StudyMaterialPage struct {
	PageObject
	Data []*StudyMaterial `json:"data"`
}

StudyMaterialPage represents a single page of StudyMaterials.

type StudyMaterialUpdateParams

type StudyMaterialUpdateParams struct {
	Params
	ID              *WKID    `json:"-"`
	MeaningNote     *string  `json:"meaning_note,omitempty"`
	MeaningSynonyms []string `json:"meaning_synonyms,omitempty"`
	ReadingNote     *string  `json:"reading_note,omitempty"`
}

StudyMaterialUpdateParams are parameters for StudyMaterialUpdate.

type Subject

type Subject struct {
	Object

	// KanjiData is data on a kanji subject. Populated only if he subject is a
	// kanji.
	KanjiData *SubjectKanjiData

	// RadicalData is data on a radical subject. Populated only if he subject
	// is a radical.
	RadicalData *SubjectRadicalData

	// VocabularyData is data on a vocabulary subject. Populated only if he
	// subject is a vocabulary.
	VocabularyData *SubjectVocabularyData
}

Subject represents radicals, kanji, and vocabulary that are learned through lessons and reviews. They contain basic dictionary information, such as meanings and/or readings, and information about their relationship to other items with WaniKani, like their level.

func (*Subject) UnmarshalJSON

func (s *Subject) UnmarshalJSON(data []byte) error

UnmarshalJSON is a custom JSON unmarshaling function for Subject.

type SubjectAuxiliaryMeaningObject

type SubjectAuxiliaryMeaningObject struct {
	Meaning string                            `json:"meaning"`
	Type    SubjectAuxiliaryMeaningObjectType `json:"type"`
}

SubjectAuxiliaryMeaningObject represents an auxiliary meaning for a subject.

type SubjectAuxiliaryMeaningObjectType

type SubjectAuxiliaryMeaningObjectType string

SubjectAuxiliaryMeaningObjectType is the type of object of an auxiliary meaning.

const (
	SubjectAuxiliaryMeaningObjectTypeBlacklist SubjectAuxiliaryMeaningObjectType = "blacklist"
	SubjectAuxiliaryMeaningObjectTypeWhitelist SubjectAuxiliaryMeaningObjectType = "whitelist"
)

All possible values of auxiliary meaning object type.

type SubjectCommonData

type SubjectCommonData struct {
	AuxiliaryMeanings        []*SubjectAuxiliaryMeaningObject `json:"auxiliary_meanings"`
	CreatedAt                time.Time                        `json:"created_at"`
	DocumentURL              string                           `json:"document_url"`
	HiddenAt                 *time.Time                       `json:"hidden_at"`
	Level                    int                              `json:"level"`
	LessonPosition           int                              `json:"lesson_position"`
	Meanings                 []*SubjectMeaningObject          `json:"meanings"`
	Slug                     string                           `json:"slug"`
	SpacedRepetitionSystemID WKID                             `json:"spaced_repetition_system_id"`
}

SubjectCommonData is common data available on all subject types regardless of whether they're kanji, radical, or vocabulary.

type SubjectGetParams

type SubjectGetParams struct {
	Params
	ID *WKID
}

SubjectGetParams are parameters for SubjectGet.

type SubjectKanjiData

type SubjectKanjiData struct {
	SubjectCommonData

	AmalgamationSubjectIDs    []WKID                 `json:"amalgamation_subject_ids"`
	Characters                string                 `json:"characters"`
	ComponentSubjectIDs       []WKID                 `json:"component_subject_ids"`
	MeaningHint               *string                `json:"meaning_hint"`
	ReadingHint               *string                `json:"reading_hint"`
	ReadingMnemonic           string                 `json:"mnemonic_hint"`
	Readings                  []*SubjectKanjiReading `json:"readings"`
	VisuallySimilarSubjectIDs []WKID                 `json:"visually_similar_subject_ids"`
}

SubjectKanjiData is data on a kanji subject.

type SubjectKanjiReading

type SubjectKanjiReading struct {
	AcceptedAnswer bool                    `json:"accepted_answer"`
	Primary        bool                    `json:"primary"`
	Reading        string                  `json:"reading"`
	Type           SubjectKanjiReadingType `json:"type"`
}

SubjectKanjiReading is reading data on a kanji subject.

type SubjectKanjiReadingType

type SubjectKanjiReadingType string

SubjectKanjiReadingType is the type of a kanji reading.

const (
	SubjectKanjiReadingTypeKunyomi SubjectKanjiReadingType = "kunyomi"
	SubjectKanjiReadingTypeNanori  SubjectKanjiReadingType = "nanori"
	SubjectKanjiReadingTypeOnyomi  SubjectKanjiReadingType = "onyomi"
)

All possible types of kanji readings.

type SubjectListParams

type SubjectListParams struct {
	ListParams
	Params

	IDs          []WKID
	Hidden       *bool
	Levels       []int
	Slugs        []string
	Types        []string
	UpdatedAfter *WKTime
}

SubjectListParams are parameters for SubjectList.

func (*SubjectListParams) EncodeToQuery

func (p *SubjectListParams) EncodeToQuery() string

EncodeToQuery encodes parametes to a query string.

type SubjectMeaningObject

type SubjectMeaningObject struct {
	AcceptedAnswer bool   `json:"accepted_answer"`
	Meaning        string `json:"meaning"`
	Primary        bool   `json:"primary"`
}

SubjectMeaningObject represents a meaning for a subject.

type SubjectPage

type SubjectPage struct {
	PageObject
	Data []*Subject `json:"data"`
}

SubjectPage represents a single page of Subjects.

type SubjectRadicalCharacterImage

type SubjectRadicalCharacterImage struct {
	ContentType string                                                  `json:"content_type"`
	Metadata    map[SubjectRadicalCharacterImageMetadataKey]interface{} `json:"metadata"`
	URL         string                                                  `json:"url"`
}

SubjectRadicalCharacterImage represents an image for a radical. Unlike kanji or vocabulary, radicals cannot always be represented by a unicode glyph.

type SubjectRadicalCharacterImageMetadataKey

type SubjectRadicalCharacterImageMetadataKey string

SubjectRadicalCharacterImageMetadataKey is a key for character image metadata.

const (
	SubjectRadicalCharacterImageMetadataKeyColor        SubjectRadicalCharacterImageMetadataKey = "color"
	SubjectRadicalCharacterImageMetadataKeyDimensions   SubjectRadicalCharacterImageMetadataKey = "dimensions"
	SubjectRadicalCharacterImageMetadataKeyInlineStyles SubjectRadicalCharacterImageMetadataKey = "inline_styles"
	SubjectRadicalCharacterImageMetadataKeyStyleName    SubjectRadicalCharacterImageMetadataKey = "style_name"
)

All possible values of radical character image metadata keys.

type SubjectRadicalData

type SubjectRadicalData struct {
	SubjectCommonData

	AmalgamationSubjectIDs []WKID                          `json:"amalgamation_subject_ids"`
	CharacterImages        []*SubjectRadicalCharacterImage `json:"character_images"`
	Characters             *string                         `json:"characters"`
}

SubjectRadicalData is data on a radical subject.

type SubjectVocabularyContextSentence

type SubjectVocabularyContextSentence struct {
	// EN is the English translation of the sentence.
	EN string `json:"en"`

	// JA is a Japanese context context sentence.
	JA string `json:"ja"`
}

SubjectVocabularyContextSentence represents a vocabulary context sentence.

type SubjectVocabularyData

type SubjectVocabularyData struct {
	SubjectCommonData

	Characters           string                                  `json:"characters"`
	ComponentSubjectIDs  []WKID                                  `json:"component_subject_ids"`
	ContextSentences     []*SubjectVocabularyContextSentence     `json:"context_sentences"`
	MeaningMnemonic      string                                  `json:"meaning_mnenomic"`
	PartsOfSpeech        []string                                `json:"parts_of_speech"`
	PronounciationAudios []*SubjectVocabularyPronounciationAudio `json:"pronounciation_audios"`
	Readings             []*SubjectVocabularyReading             `json:"subject_vocabulary_reading"`
}

SubjectVocabularyData is data on a vocabulary subject.

type SubjectVocabularyPronounciationAudio

type SubjectVocabularyPronounciationAudio struct {
	ContentType string                                                          `json:"content_type"`
	Metadata    map[SubjectVocabularyPronounciationAudioMetadataKey]interface{} `json:"metadata"`
	URL         string                                                          `json:"url"`
}

SubjectVocabularyPronounciationAudio represets an audio object for vocabulary pronounciation.

type SubjectVocabularyPronounciationAudioMetadataKey

type SubjectVocabularyPronounciationAudioMetadataKey string

SubjectVocabularyPronounciationAudioMetadataKey is a key for pronounciation audio metadata.

const (
	SubjectVocabularyPronounciationAudioMetadataKeyGender           SubjectVocabularyPronounciationAudioMetadataKey = "gender"
	SubjectVocabularyPronounciationAudioMetadataKeyPronounciation   SubjectVocabularyPronounciationAudioMetadataKey = "pronounciation"
	SubjectVocabularyPronounciationAudioMetadataKeySourceID         SubjectVocabularyPronounciationAudioMetadataKey = "source_id"
	SubjectVocabularyPronounciationAudioMetadataKeyVoiceActorID     SubjectVocabularyPronounciationAudioMetadataKey = "voice_actor_id"
	SubjectVocabularyPronounciationAudioMetadataKeyVoiceActorName   SubjectVocabularyPronounciationAudioMetadataKey = "voice_actor_name"
	SubjectVocabularyPronounciationAudioMetadataKeyVoiceDescription SubjectVocabularyPronounciationAudioMetadataKey = "voice_description"
)

All possible values of vocabulary pronounciation audio metadata keys.

type SubjectVocabularyReading

type SubjectVocabularyReading struct {
	AcceptedAnswer bool   `json:"accepted_answer"`
	Primary        bool   `json:"primary"`
	Reading        string `json:"reading"`
}

SubjectVocabularyReading is reading data on a vocabulary subject.

type Summary

type Summary struct {
	Object
	Data *SummaryData `json:"data"`
}

Summary contains currently available lessons and reviews and the reviews that will become available in the next 24 hours, grouped by the hour.

type SummaryData

type SummaryData struct {
	Lessons       []*SummaryLesson `json:"lessons"`
	NextReviewsAt *time.Time       `json:"next_reviews_at"`
	Reviews       []*SummaryReview `json:"reviews"`
}

SummaryData contains core data of Summary.

type SummaryGetParams

type SummaryGetParams struct {
	Params
}

SummaryGetParams are parameters for SummaryGet.

type SummaryLesson

type SummaryLesson struct {
	AvailableAt time.Time `json:"available_at"`
	SubjectIDs  []WKID    `json:"subject_ids"`
}

SummaryLesson provides a summary about lessons.

type SummaryPage

type SummaryPage struct {
	PageObject
	Data []*Summary `json:"data"`
}

SummaryPage represents a single page of Summaries.

type SummaryReview

type SummaryReview struct {
	AvailableAt time.Time `json:"available_at"`
	SubjectIDs  []WKID    `json:"subject_ids"`
}

SummaryReview provides a summary about reviews.

type User

type User struct {
	Object
	Data *UserData `json:"data"`
}

User returns basic information for the user making the API request, identified by their API token.

type UserData

type UserData struct {
	CurrentVacationStartedAt *time.Time        `json:"current_vacation_started_at"`
	WKID                     string            `json:"id"`
	Level                    int               `json:"level"`
	Preferences              *UserPreferences  `json:"preferences"`
	ProfileURL               string            `json:"profile_url"`
	StartedAt                time.Time         `json:"started_at"`
	Subscription             *UserSubscription `json:"subscription"`
	Username                 string            `json:"username"`
}

UserData contains core data of User.

type UserGetParams

type UserGetParams struct {
	Params
}

UserGetParams are parameters for UserGet.

type UserPreferences

type UserPreferences struct {
	DefaultVoiceActorID        WKID   `json:"default_voice_actor_id"`
	LessonsAutoplayAudio       bool   `json:"lessons_autoplay_audio"`
	LessonsBatchSize           int    `json:"lessons_batch_size"`
	LessonsPresentationOrder   string `json:"lessons_presentation_order"`
	ReviewsAutoplayAudio       bool   `json:"reviews_autoplay_audio"`
	ReviewsDisplaySRSIndicator bool   `json:"reviews_display_srs_indicator"`
}

UserPreferences are preferences for a user.

type UserSubscription

type UserSubscription struct {
	Active          bool       `json:"active"`
	MaxLevelGranted int        `json:"max_level_granted"`
	PeriodEndsAt    *time.Time `json:"period_ends_at"`
	Type            string     `json:"type"`
}

UserSubscription represents a subscription for a user.

type UserUpdateParams

type UserUpdateParams struct {
	Params
	Preferences *UserUpdatePreferencesParams `json:"preferences,omitempty"`
}

UserUpdateParams are parameters for UserUpdate.

type UserUpdatePreferencesParams

type UserUpdatePreferencesParams struct {
	DefaultVoiceActorID        *WKID   `json:"default_voice_actor_id,omitempty"`
	LessonsAutoplayAudio       *bool   `json:"lessons_autoplay_audio,omitempty"`
	LessonsBatchSize           *int    `json:"lessons_batch_size,omitempty"`
	LessonsPresentationOrder   *string `json:"lessons_presentation_order,omitempty"`
	ReviewsAutoplayAudio       *bool   `json:"reviews_autoplay_audio,omitempty"`
	ReviewsDisplaySRSIndicator *bool   `json:"reviews_display_srs_indicator,omitempty"`
}

UserUpdatePreferencesParams are update parameters for user preferences.

type VoiceActor

type VoiceActor struct {
	Object
	Data *VoiceActorData `json:"data"`
}

VoiceActor represents a voice actor used for vocabulary reading pronunciation audio.

type VoiceActorData

type VoiceActorData struct {
	Description string `json:"description"`
	Gender      string `json:"gender"`
	Name        string `json:"name"`
}

VoiceActorData contains core data of VoiceActor.

type VoiceActorGetParams

type VoiceActorGetParams struct {
	Params
	ID *WKID
}

VoiceActorGetParams are parameters for VoiceActorGet.

type VoiceActorListParams

type VoiceActorListParams struct {
	ListParams
	Params

	IDs          []WKID
	UpdatedAfter *WKTime
}

VoiceActorListParams are parameters for VoiceActorList.

func (*VoiceActorListParams) EncodeToQuery

func (p *VoiceActorListParams) EncodeToQuery() string

EncodeToQuery encodes parametes to a query string.

type VoiceActorPage

type VoiceActorPage struct {
	PageObject
	Data []*VoiceActor `json:"data"`
}

VoiceActorPage represents a single page of VoiceActors.

type WKID

type WKID int64

WKID represents a WaniKani API identifier.

func ID

func ID(id WKID) *WKID

ID is a helper function that returns a pointer to the given value. This is useful for setting values in parameter structs.

type WKObjectType

type WKObjectType string

WKObjectType represents a type of object in the WaniKani API.

type WKTime

type WKTime time.Time

WKTime is a type based on time.Time that lets us precisely control the JSON marshaling for use in API parameters to endpoints.

func Time

func Time(t time.Time) *WKTime

Time is a helper function that returns a pointer to the given value. This is useful for setting values in parameter structs.

func (WKTime) Encode

func (t WKTime) Encode() string

Encode encodes the time to the RFC3339 format that WaniKani expects.

func (WKTime) MarshalJSON

func (t WKTime) MarshalJSON() ([]byte, error)

MarshalJSON overrides JSON marshaling for WKTime so that it can be put in the RFC3339 format that WaniKani expects.

Directories

Path Synopsis
samples

Jump to

Keyboard shortcuts

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