Initial commit

This commit is contained in:
Sam Woodard 2015-07-05 08:59:30 -07:00
commit 0aa225cfcc
3 changed files with 131 additions and 0 deletions

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
/bin/

80
jsonapi.go Normal file
View File

@ -0,0 +1,80 @@
package jsonapi
import (
"errors"
"fmt"
"reflect"
"strings"
)
type JsonApiNodeWrapper struct {
Data *JsonApiNode `json:"data"`
}
type JsonApiNode struct {
Type string `json:"type"`
Id string `json:"id"`
Attributes map[string]interface{} `json:"attributes,omitempty"`
Relationships map[string]interface{} `json:"realtionships,omitempty"`
}
type JsonApiResponse struct {
Data *JsonApiNode `json:"data"`
Included []*JsonApiNode `json:"included"`
}
func CreateJsonApiResponse(model interface{}) (*JsonApiResponse, error) {
rootNode := new(JsonApiNode)
jsonApiResponse := &JsonApiResponse{Data: rootNode}
primaryKeyType := reflect.TypeOf(model)
var err error
primaryKeyType.FieldByNameFunc(func(name string) bool {
field, found := primaryKeyType.FieldByName(name)
if found {
fieldValue := reflect.ValueOf(model).FieldByName(name)
tag := field.Tag.Get("jsonapi")
args := strings.Split(tag, ",")
if len(args) >= 1 && args[0] != "" {
annotation := args[0]
if annotation == "primary" {
if len(args) >= 2 {
rootNode.Id = fmt.Sprintf("%v", fieldValue.Interface())
rootNode.Type = args[1]
} else {
err = errors.New("'type' as second argument required for 'primary'")
}
} else if annotation == "attr" {
if rootNode.Attributes == nil {
rootNode.Attributes = make(map[string]interface{})
}
if len(args) >= 2 {
rootNode.Attributes[args[1]] = fieldValue.Interface()
} else {
err = errors.New("'type' as second argument required for 'primary'")
}
} else {
err = errors.New("Unsupported jsonapi tag annotation")
}
}
}
return false
})
if err != nil {
return nil, err
}
return jsonApiResponse, nil
}
func handleField(field reflect.StructField) {
}

50
jsonapi_test.go Normal file
View File

@ -0,0 +1,50 @@
package jsonapi
import "testing"
type Blog struct {
Id int `json:"id" jsonapi:"primary,blogs"`
Title string `json:"title" jsonapi:"attr,title"`
}
func TestHasPrimaryAnnotation(t *testing.T) {
testModel := Blog{
Id: 5,
Title: "Title 1",
}
resp, err := CreateJsonApiResponse(testModel)
response := resp.Data
if err != nil {
t.Fatal(err)
}
if response.Type != "blogs" {
t.Fatalf("type should have been blogs")
}
if response.Id != "5" {
t.Fatalf("Id not transfered")
}
}
func TestSupportsAttributes(t *testing.T) {
testModel := Blog{
Id: 5,
Title: "Title 1",
}
resp, err := CreateJsonApiResponse(testModel)
response := resp.Data
if err != nil {
t.Fatal(err)
}
if response.Attributes == nil || len(response.Attributes) != 1 {
t.Fatalf("Expected 1 Attributes")
}
if response.Attributes["title"] != "Title 1" {
t.Fatalf("Attributes hash not populated using tags correctly")
}
}