Skip to content

Commit 68ee3ed

Browse files
committed
Merge pull request #76 from univedo/packageSplit
Package split
2 parents 99559ca + 5a94a44 commit 68ee3ed

File tree

14 files changed

+284
-101
lines changed

14 files changed

+284
-101
lines changed

.travis.yml

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,12 @@ go:
66
- 1.4
77
- tip
88

9-
install: go get -t -d -v ./... && go build -v ./...
9+
install:
10+
- go get -t -d -v ./...
11+
- go get github.com/onsi/ginkgo/ginkgo
12+
13+
script:
14+
- ginkgo -r --randomizeAllSpecs --randomizeSuites --failOnPending --trace --race --progress
1015

1116
notifications:
1217
slack:

README.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,11 @@ import "github.com/univedo/api2go"
1111

1212
**api2go works, but we're still working on some rough edges. Things might change. Open an issue and join in!**
1313

14+
Note: if you only need the marshaling functionality, you can install the subpackage via
15+
```go
16+
go get github.com/univedo/api2go/jsonapi
17+
```
18+
1419
## Usage
1520

1621
Take the simple structs:

api.go

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import (
1010
"strings"
1111

1212
"github.com/julienschmidt/httprouter"
13+
"github.com/univedo/api2go/jsonapi"
1314
)
1415

1516
// DataSource provides methods needed for CRUD.
@@ -106,7 +107,7 @@ func (api *API) addResource(prototype interface{}, source DataSource) *resource
106107
panic("pass an empty resource struct to AddResource!")
107108
}
108109

109-
name := jsonify(pluralize(resourceType.Name()))
110+
name := jsonapi.Jsonify(jsonapi.Pluralize(resourceType.Name()))
110111
res := resource{
111112
resourceType: resourceType,
112113
name: name,
@@ -242,11 +243,11 @@ func (res *resource) handleLinked(api *API, w http.ResponseWriter, r *http.Reque
242243
// Iterate over all struct fields and determine the type of linked
243244
for i := 0; i < res.resourceType.NumField(); i++ {
244245
field := res.resourceType.Field(i)
245-
fieldName := jsonify(field.Name)
246+
fieldName := jsonapi.Jsonify(field.Name)
246247
kind := field.Type.Kind()
247248
if (kind == reflect.Ptr || kind == reflect.Slice) && fieldName == linked {
248249
// Check if there is a resource for this type
249-
fieldType := pluralize(jsonify(field.Type.Elem().Name()))
250+
fieldType := jsonapi.Pluralize(jsonapi.Jsonify(field.Type.Elem().Name()))
250251
for _, resource := range api.resources {
251252
if resource.name == fieldType {
252253
request := Request{
@@ -279,7 +280,9 @@ func (res *resource) handleCreate(w http.ResponseWriter, r *http.Request, prefix
279280
return err
280281
}
281282
newObjs := reflect.MakeSlice(reflect.SliceOf(res.resourceType), 0, 0)
282-
err = unmarshalInto(ctx, res.resourceType, &newObjs)
283+
284+
//TODO remove necessecity to call unmarshal into
285+
err = jsonapi.UnmarshalInto(ctx, res.resourceType, &newObjs)
283286
if err != nil {
284287
return err
285288
}
@@ -320,7 +323,9 @@ func (res *resource) handleUpdate(w http.ResponseWriter, r *http.Request, ps htt
320323
}
321324
updatingObjs := reflect.MakeSlice(reflect.SliceOf(res.resourceType), 1, 1)
322325
updatingObjs.Index(0).Set(reflect.ValueOf(obj))
323-
err = unmarshalInto(ctx, res.resourceType, &updatingObjs)
326+
327+
//TODO remove call to unmarshalInto
328+
err = jsonapi.UnmarshalInto(ctx, res.resourceType, &updatingObjs)
324329
if err != nil {
325330
return err
326331
}
@@ -359,7 +364,7 @@ func (res *resource) handleDelete(w http.ResponseWriter, r *http.Request, ps htt
359364
}
360365

361366
func respondWith(obj interface{}, prefix string, status int, w http.ResponseWriter) error {
362-
data, err := MarshalToJSONPrefix(obj, prefix)
367+
data, err := jsonapi.MarshalToJSONPrefix(obj, prefix)
363368
if err != nil {
364369
return err
365370
}

error.go

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,11 @@
11
package api2go
22

3-
import "fmt"
3+
import (
4+
"encoding/json"
5+
"fmt"
6+
"log"
7+
"strconv"
8+
)
49

510
//HTTPError is used for errors
611
type HTTPError struct {
@@ -24,6 +29,34 @@ type Error struct {
2429
Path string `json:"path,omitempty"`
2530
}
2631

32+
//marshalError marshals all error types
33+
func marshalError(err error) string {
34+
httpErr, ok := err.(HTTPError)
35+
if ok {
36+
return marshalHTTPError(httpErr)
37+
}
38+
39+
httpErr = NewHTTPError(err, err.Error(), 500)
40+
41+
return marshalHTTPError(httpErr)
42+
}
43+
44+
//marshalHTTPError marshals an internal httpError
45+
func marshalHTTPError(input HTTPError) string {
46+
if len(input.Errors) == 0 {
47+
input.Errors = []Error{Error{Title: input.msg, Status: strconv.Itoa(input.status)}}
48+
}
49+
50+
data, err := json.Marshal(input)
51+
52+
if err != nil {
53+
log.Println(err)
54+
return "{}"
55+
}
56+
57+
return string(data)
58+
}
59+
2760
// NewHTTPError creates a new error with message and status code.
2861
// `err` will be logged (but never sent to a client), `msg` will be sent and `status` is the http status code.
2962
// `err` can be nil.

helpers_test.go

Lines changed: 0 additions & 34 deletions
This file was deleted.

jsonapi/Readme.md

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
# api2go JSONAPI package
2+
3+
This package contains [JSON API](http://jsonapi.org) compatible
4+
marshal und unmarshal functionality.
5+
6+
```
7+
go get github.com/univedo/api2go/jsonapi
8+
```
9+
10+
## Usage
11+
12+
For information on how to use this package, please refer to the
13+
documentation on the [api2go](https://github.com/univedo/api2go) main project,
14+
the integration_test.go or the [godoc](http://godoc.org/github.com/univedo/api2go/jsonapi).

helpers.go renamed to jsonapi/helpers.go

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
package api2go
1+
package jsonapi
22

33
import (
44
"database/sql"
@@ -49,8 +49,8 @@ var commonInitialisms = map[string]bool{
4949
"JWT": true,
5050
}
5151

52-
// dejsonify returns a go struct key name from a JSON key name
53-
func dejsonify(s string) string {
52+
// Dejsonify returns a go struct key name from a JSON key name
53+
func Dejsonify(s string) string {
5454
if s == "" {
5555
return ""
5656
}
@@ -62,8 +62,8 @@ func dejsonify(s string) string {
6262
return string(rs)
6363
}
6464

65-
// jsonify returns a JSON formatted key name from a go struct field name
66-
func jsonify(s string) string {
65+
// Jsonify returns a JSON formatted key name from a go struct field name
66+
func Jsonify(s string) string {
6767
if s == "" {
6868
return ""
6969
}
@@ -75,13 +75,13 @@ func jsonify(s string) string {
7575
return string(rs)
7676
}
7777

78-
// pluralize a noun
79-
func pluralize(word string) string {
78+
// Pluralize a noun
79+
func Pluralize(word string) string {
8080
return inflector.Pluralize(word)
8181
}
8282

83-
// singularize a noun
84-
func singularize(word string) string {
83+
// Singularize a noun
84+
func Singularize(word string) string {
8585
return inflector.Singularize(word)
8686
}
8787

@@ -207,6 +207,11 @@ func setIDValue(val reflect.Value, idInterface interface{}) error {
207207

208208
val.SetUint(intID)
209209

210+
case reflect.Invalid:
211+
{
212+
return fmt.Errorf("Invalid type given for %#v.", idInterface)
213+
}
214+
210215
default:
211216
return errors.New("expected ID to be of type int or string in struct")
212217
}

jsonapi/helpers_test.go

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package jsonapi
2+
3+
import (
4+
. "github.com/onsi/ginkgo"
5+
. "github.com/onsi/gomega"
6+
)
7+
8+
var _ = Describe("StringHelpers", func() {
9+
It("dejsonifies", func() {
10+
Expect(Dejsonify("Post")).To(Equal("Post"))
11+
Expect(Dejsonify("post")).To(Equal("Post"))
12+
Expect(Dejsonify("id")).To(Equal("ID"))
13+
Expect(Dejsonify("")).To(Equal(""))
14+
})
15+
16+
It("jsonifies", func() {
17+
Expect(Jsonify("Post")).To(Equal("post"))
18+
Expect(Jsonify("post")).To(Equal("post"))
19+
Expect(Jsonify("ID")).To(Equal("id"))
20+
Expect(Jsonify("")).To(Equal(""))
21+
})
22+
23+
It("Pluralizes", func() {
24+
Expect(Pluralize("post")).To(Equal("posts"))
25+
Expect(Pluralize("posts")).To(Equal("posts"))
26+
Expect(Pluralize("category")).To(Equal("categories"))
27+
})
28+
29+
It("singularizes", func() {
30+
Expect(Singularize("posts")).To(Equal("post"))
31+
Expect(Singularize("post")).To(Equal("post"))
32+
Expect(Singularize("categories")).To(Equal("category"))
33+
})
34+
})

0 commit comments

Comments
 (0)