Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: Change handler functions implementation and response formatting #498

Merged
merged 8 commits into from
Jun 8, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ defradb client ping
```
which should respond with `Success!`

Once you've confirmed your node is running correctly, if you're using the GraphiQL client to interact with the database, then make sure you set the `GraphQL Endpoint` to `http://localhost:9181/api/v1/graphql`.
Once you've confirmed your node is running correctly, if you're using the GraphiQL client to interact with the database, then make sure you set the `GraphQL Endpoint` to `http://localhost:9181/api/v0/graphql`.

### Add a Schema type

Expand Down
28 changes: 22 additions & 6 deletions api/http/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,18 @@ import (
var env = os.Getenv("DEFRA_ENV")

type errorResponse struct {
Status int `json:"status"`
Message string `json:"message"`
Stack string `json:"stack,omitempty"`
Errors []errorItem `json:"errors"`
}

type errorItem struct {
Message string `json:"message"`
Extensions *extensions `json:"extensions,omitempty"`
}

type extensions struct {
Status int `json:"status"`
HTTPError string `json:"httpError"`
Stack string `json:"stack,omitempty"`
}

func handleErr(ctx context.Context, rw http.ResponseWriter, err error, status int) {
Expand All @@ -35,9 +44,16 @@ func handleErr(ctx context.Context, rw http.ResponseWriter, err error, status in
ctx,
rw,
errorResponse{
Status: status,
Message: http.StatusText(status),
Stack: formatError(err),
Errors: []errorItem{
{
Message: err.Error(),
Extensions: &extensions{
Status: status,
HTTPError: http.StatusText(status),
Stack: formatError(err),
},
},
},
},
status,
)
Expand Down
45 changes: 28 additions & 17 deletions api/http/errors_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,11 +54,14 @@ func TestHandleErrOnBadRequest(t *testing.T) {
t.Fatal(err)
}

assert.Equal(t, http.StatusBadRequest, errResponse.Status)
assert.Equal(t, http.StatusText(http.StatusBadRequest), errResponse.Message)
if len(errResponse.Errors) != 1 {
t.Fatal("expecting exactly one error")
}

lines := strings.Split(errResponse.Stack, "\n")
assert.Equal(t, "[DEV] test error", lines[0])
assert.Equal(t, http.StatusBadRequest, errResponse.Errors[0].Extensions.Status)
assert.Equal(t, http.StatusText(http.StatusBadRequest), errResponse.Errors[0].Extensions.HTTPError)
assert.Equal(t, "test error", errResponse.Errors[0].Message)
assert.Contains(t, errResponse.Errors[0].Extensions.Stack, "[DEV] test error")
}

func TestHandleErrOnInternalServerError(t *testing.T) {
Expand All @@ -83,11 +86,13 @@ func TestHandleErrOnInternalServerError(t *testing.T) {
t.Fatal(err)
}

assert.Equal(t, http.StatusInternalServerError, errResponse.Status)
assert.Equal(t, http.StatusText(http.StatusInternalServerError), errResponse.Message)

lines := strings.Split(errResponse.Stack, "\n")
assert.Equal(t, "[DEV] test error", lines[0])
if len(errResponse.Errors) != 1 {
t.Fatal("expecting exactly one error")
}
assert.Equal(t, http.StatusInternalServerError, errResponse.Errors[0].Extensions.Status)
assert.Equal(t, http.StatusText(http.StatusInternalServerError), errResponse.Errors[0].Extensions.HTTPError)
assert.Equal(t, "test error", errResponse.Errors[0].Message)
assert.Contains(t, errResponse.Errors[0].Extensions.Stack, "[DEV] test error")
}

func TestHandleErrOnNotFound(t *testing.T) {
Expand All @@ -112,11 +117,14 @@ func TestHandleErrOnNotFound(t *testing.T) {
t.Fatal(err)
}

assert.Equal(t, http.StatusNotFound, errResponse.Status)
assert.Equal(t, http.StatusText(http.StatusNotFound), errResponse.Message)
if len(errResponse.Errors) != 1 {
t.Fatal("expecting exactly one error")
}

lines := strings.Split(errResponse.Stack, "\n")
assert.Equal(t, "[DEV] test error", lines[0])
assert.Equal(t, http.StatusNotFound, errResponse.Errors[0].Extensions.Status)
assert.Equal(t, http.StatusText(http.StatusNotFound), errResponse.Errors[0].Extensions.HTTPError)
assert.Equal(t, "test error", errResponse.Errors[0].Message)
assert.Contains(t, errResponse.Errors[0].Extensions.Stack, "[DEV] test error")
}

func TestHandleErrOnDefault(t *testing.T) {
Expand All @@ -141,9 +149,12 @@ func TestHandleErrOnDefault(t *testing.T) {
t.Fatal(err)
}

assert.Equal(t, http.StatusUnauthorized, errResponse.Status)
assert.Equal(t, "Unauthorized", errResponse.Message)
if len(errResponse.Errors) != 1 {
t.Fatal("expecting exactly one error")
}

lines := strings.Split(errResponse.Stack, "\n")
assert.Equal(t, "[DEV] Unauthorized", lines[0])
assert.Equal(t, http.StatusUnauthorized, errResponse.Errors[0].Extensions.Status)
assert.Equal(t, http.StatusText(http.StatusUnauthorized), errResponse.Errors[0].Extensions.HTTPError)
assert.Equal(t, "Unauthorized", errResponse.Errors[0].Message)
assert.Contains(t, errResponse.Errors[0].Extensions.Stack, "[DEV] Unauthorized")
}
29 changes: 29 additions & 0 deletions api/http/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,35 @@ type handler struct {

type ctxDB struct{}

type dataResponse struct {
Data interface{} `json:"data"`
}

// simpleDataResponse is a helper function that returns a dataResponse struct.
// Odd arguments are the keys and must be strings otherwise they are ignored.
// Even arguments are the values associated with the previous key.
// Odd arguments are also ignored if there are no following arguments.
func simpleDataResponse(args ...interface{}) dataResponse {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thought: Since this is an internal func, im not too worried about it, but just wondering in case a dev shoots themselves in the foot and have an un-even number of func args so the keys/values don't line up.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If it's an odd number of arguments, the last one is discarded as the function documentation says. They will then notice that some information is missing in the payload which will prompt them to look at the data sent to the sendJSON function.

data := make(map[string]interface{})

for i := 0; i < len(args); i += 2 {
if len(args) >= i+2 {
switch a := args[i].(type) {
case string:
data[a] = args[i+1]

default:
continue

}
}
}

return dataResponse{
Data: data,
}
}

// newHandler returns a handler with the router instantiated.
func newHandler(db client.DB, opts serverOptions) *handler {
return setRoutes(&handler{
Expand Down
57 changes: 42 additions & 15 deletions api/http/handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,35 @@ import (
"github.com/stretchr/testify/assert"
)

func TestSimpleDataResponse(t *testing.T) {
resp := simpleDataResponse("key", "value", "key2", "value2")
switch v := resp.Data.(type) {
case map[string]interface{}:
assert.Equal(t, "value", v["key"])
assert.Equal(t, "value2", v["key2"])
default:
t.Fatalf("data should be of type map[string]interface{} but got %T", resp.Data)
}

resp2 := simpleDataResponse("key", "value", "key2")
switch v := resp2.Data.(type) {
case map[string]interface{}:
assert.Equal(t, "value", v["key"])
assert.Equal(t, nil, v["key2"])
default:
t.Fatalf("data should be of type map[string]interface{} but got %T", resp.Data)
}

resp3 := simpleDataResponse("key", "value", 2, "value2")
switch v := resp3.Data.(type) {
case map[string]interface{}:
assert.Equal(t, "value", v["key"])
assert.Equal(t, nil, v["2"])
default:
t.Fatalf("data should be of type map[string]interface{} but got %T", resp.Data)
}
}

func TestNewHandlerWithLogger(t *testing.T) {
h := newHandler(nil, serverOptions{})

Expand All @@ -40,14 +69,14 @@ func TestNewHandlerWithLogger(t *testing.T) {
OutputPaths: []string{logFile},
})

req, err := http.NewRequest("GET", "/ping", nil)
req, err := http.NewRequest("GET", PingPath, nil)
if err != nil {
t.Fatal(err)
}

rec := httptest.NewRecorder()

loggerMiddleware(h.handle(pingHandler)).ServeHTTP(rec, req)
lrw := newLoggingResponseWriter(rec)
h.ServeHTTP(lrw, req)
assert.Equal(t, 200, rec.Result().StatusCode)

// inspect the log file
Expand All @@ -65,13 +94,12 @@ func TestGetJSON(t *testing.T) {
Name string
}

jsonStr := []byte(`
{
"Name": "John Doe"
}
`)
jsonStr := `
{
"Name": "John Doe"
}`

req, err := http.NewRequest("POST", "/ping", bytes.NewBuffer(jsonStr))
req, err := http.NewRequest("POST", "/ping", bytes.NewBuffer([]byte(jsonStr)))
if err != nil {
t.Fatal(err)
}
Expand All @@ -90,13 +118,12 @@ func TestGetJSONWithError(t *testing.T) {
Name string
}

jsonStr := []byte(`
{
"Name": 10
}
`)
jsonStr := `
{
"Name": 10
}`

req, err := http.NewRequest("POST", "/ping", bytes.NewBuffer(jsonStr))
req, err := http.NewRequest("POST", "/ping", bytes.NewBuffer([]byte(jsonStr)))
if err != nil {
t.Fatal(err)
}
Expand Down
Loading