jsonapi

package module
v0.0.0-...-4775681 Latest Latest
Warning

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

Go to latest
Published: Sep 25, 2020 License: MIT Imports: 7 Imported by: 0

README

jsonapi-serializer-go

GoDoc Build Status Go Report Card Coverage Status

Installation

Install jsonapi-serializer-go with:

go get -u github.com/jsignanini/jsonapi-serializer-go

Then, import it using:

import "github.com/jsignanini/jsonapi-serializer-go"

Usage

package main

import (
	"fmt"

	"github.com/jsignanini/jsonapi-serializer-go"
)

func main() {
	// sample data
	type (
		BookBinding string
		BookSubject string
		Author      struct {
			ID        string `jsonapi:"primary,authors"`
			FirstName string `jsonapi:"attribute,first_name"`
			LastName  string `jsonapi:"attribute,last_name"`
		}
		Book struct {
			ISBN            string        `jsonapi:"primary,books"`
			Bindings        []BookBinding `jsonapi:"attribute,bindings"`
			PublicationYear int           `jsonapi:"attribute,publication_date"`
			Subject         BookSubject   `jsonapi:"attribute,subject"`
			Title           string        `jsonapi:"attribute,title"`
			Author          *Author       `jsonapi:"attribute,author"`
		}
	)
	const (
		BookBindingHardcover BookBinding = "Hardcover"
		BookBindingPaperback BookBinding = "Paperback"
	)
	cosmos := Book{
		ISBN:            "0-394-50294-9",
		Bindings:        []BookBinding{BookBindingHardcover, BookBindingPaperback},
		PublicationYear: 1980,
		Subject:         "Cosmology",
		Title:           "Cosmos",
		Author: &Author{
			ID:        "c3a6ddb6-7e5e-4264-bd03-ef6e41d76365",
			FirstName: "Carl",
			LastName:  "Sagan",
		},
	}

	// marshal
	jsonBytes, err := jsonapi.Marshal(&cosmos, nil)
	if err != nil {
		panic(err)
	}

	// print output
	fmt.Println(string(jsonBytes))
}

Outputs:

{
	"data": {
		"id": "0-394-50294-9",
		"type": "books",
		"attributes": {
			"author": {
				"ID": "c3a6ddb6-7e5e-4264-bd03-ef6e41d76365",
				"FirstName": "Carl",
				"LastName": "Sagan"
			},
			"bindings": [
				"Hardcover",
				"Paperback"
			],
			"publication_date": 1980,
			"subject": "Cosmology",
			"title": "Cosmos"
		}
	},
	"jsonapi": {
		"version": "1.0"
	}
}

TODOs

  • Optionally validate jsonapi spec
  • Optionally set jsonapi settings (e.g.: spec version, error/warning on document validation, etc.)
  • Support omitempty tag jsonapi:"attribute,name,omitempty"
  • Standardize internal errors
  • Show error or warning when parsing an unsupported builtin type (e.g.: complex128)
  • Handle top-level Links and resource-level links separatedly

Documentation

Index

Constants

View Source
const ContentType = "application/vnd.api+json"

ContentType is the required Content-Type header value for JSON:API request documents. See https://jsonapi.org/format/#content-negotiation-clients.

Variables

This section is empty.

Functions

func Marshal

func Marshal(v interface{}, p *MarshalParams) ([]byte, error)

Marshal returns the JSON:API encoding of v.

func MarshalErrors

func MarshalErrors(p *MarshalParams, errs ...Error) ([]byte, error)

MarshalErrors returns the JSON:API errors encoding of errs.

func RegisterMarshaler

func RegisterMarshaler(t reflect.Type, u marshalerFunc)

RegisterMarshaler register a custom marshaller function for a t type.

func RegisterUnmarshaler

func RegisterUnmarshaler(t reflect.Type, u unmarshalerFunc)

RegisterUnmarshaler register a new unmarshaler function for type t.

func Respond

func Respond(w http.ResponseWriter, r *http.Request, statusCode int, v interface{}, p *MarshalParams) error

Respond encodes v in to a JSON:API object and writes it to the body of response w. It also sets statusCode as the response status code.

func RespondError

func RespondError(w http.ResponseWriter, r *http.Request, statusCode int, p *MarshalParams, errs ...Error) error

RespondError encodes v in to a JSON:API error object and writes it to the body of response w. It also sets statusCode as the response status code.

func SetJSONIndent

func SetJSONIndent(indent string)

SetJSONIndent sets the indent value for json.MarshalIndent. See // See https://golang.org/pkg/encoding/json/#MarshalIndent.

func SetJSONPrefix

func SetJSONPrefix(prefix string)

SetJSONPrefix sets the prefix value for json.MarshalIndent. See https://golang.org/pkg/encoding/json/#MarshalIndent.

func SetTagKey

func SetTagKey(key string)

SetTagKey sets a custom value for the JSON:API tag key.

func Unmarshal

func Unmarshal(data []byte, v interface{}) error

Unmarshal parses the JSON:API-encoded data and stores the result in the value pointed to by v.

Types

type Attributes

type Attributes map[string]interface{}

Attributes is a JSON:API document resource attributes object. See https://jsonapi.org/format/#document-resource-object-attributes.

type CompoundDocument

type CompoundDocument struct {
	Data []*Resource `json:"data"`
	// contains filtered or unexported fields
}

CompoundDocument represents a compound document's top-level object. See https://jsonapi.org/format/#document-compound-documents.

func NewCompoundDocument

func NewCompoundDocument(p *NewCompoundDocumentParams) *CompoundDocument

NewCompoundDocument generates a new compound top-level document object.

type CompoundRelationship

type CompoundRelationship struct {
	Data []*Resource `json:"data"`
	// contains filtered or unexported fields
}

CompoundRelationship is a JSON:API compound relationship object. See https://jsonapi.org/format/#document-resource-object-relationships.

func NewCompoundRelationship

func NewCompoundRelationship() *CompoundRelationship

NewCompoundRelationship generates a new JSON:API compound relationship object.

type Document

type Document struct {
	Data *Resource `json:"data,omitempty"`
	// contains filtered or unexported fields
}

Document is a JSON:API document top-level object. See https://jsonapi.org/format/#document-top-level.

func NewDocument

func NewDocument(p *NewDocumentParams) *Document

NewDocument generates a new top-level document object.

type Error

type Error struct {
	ID     string            `json:"id,omitempty"`
	Links  Links             `json:"links,omitempty"`
	Status string            `json:"status,omitempty"`
	Code   string            `json:"code,omitempty"`
	Title  string            `json:"title,omitempty"`
	Detail string            `json:"detail,omitempty"`
	Source map[string]string `json:"source,omitempty"`
	Meta   Meta              `json:"meta,omitempty"`
}

Error is a JSON:API error object. See https://jsonapi.org/format/#error-objects.

func (*Error) Error

func (e *Error) Error() string

type Information

type Information struct {
	Version string `json:"version,omitempty"`
	Meta    Meta   `json:"meta,omitempty"`
}

Information is an object that holds information about the JSON:API implementation a the top-level document. See https://jsonapi.org/format/#document-jsonapi-object.

type Links map[string]interface{}

Links is a JSON:API links object. See https://jsonapi.org/format/#document-links.

func (l Links) AddLink(name, url string)

AddLink adds a url-only link.

func (Links) AddLinkWithMeta

func (l Links) AddLinkWithMeta(name, url string, meta Meta)

AddLinkWithMeta adds a link with a meta object.

type MarshalParams

type MarshalParams struct {
	Links *Links
	Meta  *Meta
}

MarshalParams are the optional parameters to add links and meta objects to a top-level document.

type Meta

type Meta map[string]interface{}

Meta is a JSON:API meta object. See https://jsonapi.org/format/#document-meta.

type NewCompoundDocumentParams

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

NewCompoundDocumentParams are the parameters describing a new compound top-level document.

type NewDocumentParams

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

NewDocumentParams are the parameters describing a top-level document.

type Relationship

type Relationship struct {
	Data *Resource `json:"data"`
	// contains filtered or unexported fields
}

Relationship struct { is a JSON:API relationship object. See https://jsonapi.org/format/#document-resource-object-relationships.

func NewRelationship

func NewRelationship() *Relationship

NewRelationship generates a new JSON:API relationship object.

func (*Relationship) AddResource

func (r *Relationship) AddResource(resource *Resource)

AddResource adds a new resource to an existing realationship.

type RelationshipLink struct {
	Self    string `json:"self,omitempty"`
	Related string `json:"related,omitempty"`
}

RelationshipLink is a JSON:API relationship links object. See https://jsonapi.org/format/#document-resource-object-related-resource-links.

type Relationships

type Relationships map[string]interface{}

Relationships is a map of JSON:API relationship objects.

type Resource

type Resource struct {
	// Exception: The id member is not required when the resource object originates at the client and represents a new resource to be created on the server.
	ID   string `json:"id,omitempty"`
	Type string `json:"type,omitempty"`

	Attributes    Attributes    `json:"attributes,omitempty"`
	Relationships Relationships `json:"relationships,omitempty"`
	Links         Links         `json:"links,omitempty"`
	Meta          Meta          `json:"meta,omitempty"`
}

Resource is a JSON:API resource object. See https://jsonapi.org/format/#document-resource-objects.

func NewResource

func NewResource() *Resource

NewResource generates a new JSON:API resource object.

func (*Resource) SetIDAndType

func (r *Resource) SetIDAndType(idValue reflect.Value, resourceType string) error

SetIDAndType sets the id and type of a JSON:API resource object. TODO warn or error out when ID isn't plural?

func (r *Resource) SetLinks(linksValue reflect.Value) error

SetLinks sets the links of a JSON:API resource object.

Jump to

Keyboard shortcuts

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