jsonapi

package
v1.6.13 Latest Latest
Warning

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

Go to latest
Published: May 17, 2024 License: Apache-2.0 Imports: 11 Imported by: 0

Documentation

Overview

Package jsonapi Interface for interacting with {json:api} APIs.

Usage:

    import "github.com/transifex/cli/pkg/jsonapi"

    api := jsonapi.Connection{Host: "https://foo.com", Token: "XXX"}

    // Lets get a list of things
    query := jsonapi.Query{
		Filters: map[string]string{"age__gt": "15"},
	}.Encode()
    page, err := api.List("students", query)
    for {
        for _, student := range page.Data {
            fmt.Println(student.Attributes["full_name"])
        }
        if page.Next == "" {
            break
        } else {
            page = page.GetNext()
        }
    }

    // Lets get and manipulate a single thing
    teacher, err := api.Get("teachers", "1")
    teacher.Attributes["age"] = teacher.Attributes["age"] + 1
    err = teacher.Save([]string{"age"})

    // Lets fetch some relationships
    relationship, err := teacher.Fetch("manager")
    fmt.Println(relationship.DataSingular.Attributes["grade"])

    relationship, err = teacher.Fetch("students")
    page := relationship.DataPlural
    for {...}  // Same as before

    // Lets create something new
    student := jsonapi.Resource{
        API: api,
        Type: "students",
        Attributes: map[string]interface{}{
            "full_name": "John Doe",
        },
    }
    err = student.Save()  // Student has no ID so a POST request is sent

    TODOs:

    - Change/Reset/Add/Remove methods for relationships

Index

Constants

View Source
const (
	NULL     = iota
	SINGULAR = iota
	PLURAL   = iota
)

Variables

This section is empty.

Functions

This section is empty.

Types

type CapturedRequest

type CapturedRequest struct {
	Method      string
	Payload     []byte
	ContentType string
}

type Collection

type Collection struct {
	API      *Connection
	Data     []Resource
	Next     string
	Previous string
}

func (*Collection) GetNext

func (c *Collection) GetNext() (Collection, error)

GetNext Return the next page of the paginated collection as pointed to by the `.links.next` field in the {json:api} response

func (*Collection) GetPrevious

func (c *Collection) GetPrevious() (Collection, error)

GetPrevious Return the previous page of the paginated collection as pointed to by the `.links.previous` field in the {json:api} response

type Connection

type Connection struct {
	Host    string
	Token   string
	Client  http.Client
	Headers map[string]string

	// Used for testing
	RequestMethod func(method, path string,
		payload []byte, contentType string) ([]byte, error)
}

func GetTestConnection

func GetTestConnection(mockData MockData) Connection

func (*Connection) Get

func (c *Connection) Get(Type, Id string) (Resource, error)

Get Returns a Resource instance from the server based on its 'type' and 'id'

func (*Connection) List

func (c *Connection) List(Type, Query string) (Collection, error)

List Returns a Collection instance from the server. Query is a URL encoded set of GET variables that can be easily generated from the Query type and Query.Encode method.

type Error

type Error struct {
	StatusCode int
	Errors     []ErrorItem `json:"errors"`
}

Error type for {json:api} errors.

You can inspect the contents of the error response with type assertions. Example:

    project := jsonapi.Resource{...}
    err := project.Save() // Here the server responds with an error
    switch e := err.(type) {
    case *jsonapi.Error:
		// "Smartly" inspect the contents of the error
		for _, errorItem := range e.Errors {
			if errorItem.Status == "404" {
				fmt.Println("Something was not found")
			}
		}
    default:
        fmt.Printf("%s\n", e)
    }

func (*Error) Error

func (e *Error) Error() string

type ErrorItem

type ErrorItem struct {
	Status string `json:"status,omitempty"`
	Code   string `json:"code,omitempty"`
	Title  string `json:"title,omitempty"`
	Detail string `json:"detail,omitempty"`
	Source struct {
		Pointer   string `json:"pointer,omitempty"`
		Parameter string `json:"parameter,omitempty"`
	} `json:"source,omitempty"`
}
type Links struct {
	Self    string `json:"self,omitempty"`
	Related string `json:"related,omitempty"`
}

type MockData

type MockData map[string]*MockEndpoint

func (*MockData) Get

func (mockData *MockData) Get(path string) *MockRequest

type MockEndpoint

type MockEndpoint struct {
	Requests []MockRequest
	Count    int
}

func GetMockTextResponse added in v1.2.0

func GetMockTextResponse(text string) *MockEndpoint

type MockRequest

type MockRequest struct {
	Response MockResponse
	Request  CapturedRequest
}

type MockResponse

type MockResponse struct {
	Status   int
	Text     string
	Redirect string
}
type PaginationLinks struct {
	Previous string `json:"previous,omitempty"`
	Next     string `json:"next,omitempty"`
}

type PayloadPluralRead

type PayloadPluralRead struct {
	Data     []PayloadResource `json:"data"`
	Links    PaginationLinks   `json:"links,omitempty"`
	Included []PayloadResource `json:"included,omitempty"`
}

type PayloadPluralWrite

type PayloadPluralWrite struct {
	Data []PayloadResource `json:"data"`
}

type PayloadRelationshipPlural

type PayloadRelationshipPlural struct {
	Data  []ResourceIdentifier
	Links Links
}

type PayloadRelationshipSingularRead

type PayloadRelationshipSingularRead struct {
	Data  ResourceIdentifier `json:"data,omitempty"`
	Links Links              `json:"links,omitempty"`
}

type PayloadRelationshipSingularWrite

type PayloadRelationshipSingularWrite struct {
	Data ResourceIdentifier `json:"data,omitempty"`
}

type PayloadResource

type PayloadResource struct {
	Type          string                 `json:"type"`
	Id            string                 `json:"id,omitempty"`
	Attributes    map[string]interface{} `json:"attributes,omitempty"`
	Relationships map[string]interface{} `json:"relationships,omitempty"`
}

type PayloadSingular

type PayloadSingular struct {
	Data     PayloadResource   `json:"data"`
	Included []PayloadResource `json:"included,omitempty"`
}

type Query

type Query struct {
	Filters  map[string]string
	Includes []string
	Extras   map[string]string
}

func (Query) Encode

func (q Query) Encode() string

Encode Converts a Query object to a string that's ready to be used as GET variables for {json:api} requests.

type RedirectError

type RedirectError struct {
	Location string
}

func (*RedirectError) Error

func (m *RedirectError) Error() string

type Relationship

type Relationship struct {
	Type         int
	Fetched      bool
	DataSingular *Resource
	DataPlural   Collection
	Links        Links
}

type Resource

type Resource struct {
	API           *Connection
	Type          string
	Id            string
	Attributes    map[string]interface{}
	Relationships map[string]*Relationship
	Redirect      string
	Links         Links
}

func (*Resource) Add

func (r *Resource) Add(field string, items []*Resource) error

func (*Resource) Delete added in v0.0.2

func (r *Resource) Delete() error

Delete a resource from the server. Response is empty on success

func (*Resource) Fetch

func (r *Resource) Fetch(key string) (*Relationship, error)

Fetch data for a relationship and return a reference to it.

If the data was previously fetched (the 'Fetched' field is true), 'Save' returns immediately.

func (*Resource) MapAttributes

func (r *Resource) MapAttributes(result interface{}) error

MapAttributes Map a resource's attributes to a struct. Usage:

type ProjectAttributes struct {
    Name string
    ...
}

func main() {
    api := jsonapi.Connection{...}
    project, _ := api.Get("projects", "XXX")
    var projectAttributes ProjectAttributes
    project.MapAttributes(&projectAttributes)

    fmt.Println(projectAttributes.Name)
}

func (*Resource) Reload

func (r *Resource) Reload() error

func (*Resource) Remove

func (r *Resource) Remove(field string, items []*Resource) error

func (*Resource) Reset

func (r *Resource) Reset(field string, items []*Resource) error

func (*Resource) Save

func (r *Resource) Save(fields []string) error

Save the resource on the server. If there is an Id present, send a PATCH request, otherwise send a POST request. The Attributes and relationships that will be sent are the ones in the 'fields' argument. If the 'fields' argument is nil, everything will be saved.

func (*Resource) SaveAsMultipart

func (r *Resource) SaveAsMultipart(fields []string) error

func (*Resource) SetRelated

func (r *Resource) SetRelated(field string, related *Resource)

SetRelated Set a relationship to a resource. Can be used either before saving or after getting a resource from the API and wanting to "pre-fetch" a parent resource that is at hand.

For saving:

parent := ...
child := ...
child.SetRelated("parent", parent)
child.Save("parent")

For "pre-fetching":

parent := ...
query := Query{Filters: map[string][string]{"parent": parent.Id}}.Encode()
page, _ := api.List("children", query)
child := page.Data[0]
child.SetRelated("parent", parent)

func (*Resource) UnmapAttributes

func (r *Resource) UnmapAttributes(source interface{}) error

UnmapAttributes Unmap a struct to a resource's attributes (possibly before calling 'Save').

Usage:

type ProjectAttributes struct {
    Name string
    ...
}

func main() {
    api := jsonapi.Connection{...}
    project, _ := api.Get("projects", "XXX")
    var projectAttributes ProjectAttributes
    project.MapAttributes(&projectAttributes)

    projectAttributes.Name = "New name"
    project.UnmapAttributes(projectAttributes)
    project.Save([]string{"name"})
}

type ResourceIdentifier

type ResourceIdentifier struct {
	Type string `json:"type,omitempty"`
	Id   string `json:"id,omitempty"`
}

type RetryError added in v1.6.11

type RetryError struct {
	RetryAfter int
}

func (RetryError) Error added in v1.6.11

func (err RetryError) Error() string

Jump to

Keyboard shortcuts

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