Skip to content
This repository has been archived by the owner on Jul 24, 2021. It is now read-only.

Commit

Permalink
Merge pull request #16 from joyent/perigrin/json-schema
Browse files Browse the repository at this point in the history
JSON Schemea Endpoints
  • Loading branch information
perigrin authored Sep 24, 2019
2 parents b0bbe27 + 392e979 commit f16b0e5
Show file tree
Hide file tree
Showing 3 changed files with 113 additions and 0 deletions.
17 changes: 17 additions & 0 deletions Gopkg.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

27 changes: 27 additions & 0 deletions schema.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package main

import (
"fmt"

"github.com/qri-io/jsonschema"
)

type Schema struct {
*Conch
}

func (c *Conch) Schema() *Schema {
return &Schema{c}
}

func (s *Schema) Get(name string) *jsonschema.RootSchema {
uri := fmt.Sprintf("/schema/%s", name)
rs := &jsonschema.RootSchema{}

// for now we completely skip our internal HTTP handling and just use sling directly
_, err := s.Sling().Get(uri).Receive(&rs, nil)
if err != nil {
panic(err)
}
return rs
}
69 changes: 69 additions & 0 deletions schema_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
package main

import (
"fmt"
"net/http"
"net/http/httptest"
"testing"
)

func TestJSONSchemaGet(t *testing.T) {
name := "request/Login"
valid := []byte(`{
"email":"test@example.com",
"password":"123456"
}`)

server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// output from the API's '/schema/request/Login` endpoint
fmt.Fprintf(w, `
{
"$id":"urn:request.Login.schema.json",
"$schema":"http:\/\/json-schema.org\/draft-07\/schema#",
"additionalProperties":false,
"definitions":{
"email_address":{
"allOf":[
{"format":"email","type":"string"},
{"$ref":"\/definitions\/mojo_relaxed_placeholder"}
]
},
"mojo_relaxed_placeholder":{
"description":"see https:\/\/metacpan.org\/pod\/Mojolicious::Guides::Routing#Relaxed-placeholders",
"pattern":"^[^\/]+$","type":"string"
},
"non_empty_string":{
"minLength":1,
"type":"string"
},
"uuid":{
"pattern":"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$",
"type":"string"
}
},
"oneOf":[
{"required":["user_id"]},
{"required":["email"]}
],
"properties":{
"email":{"$ref":"\/definitions\/email_address"},
"password":{"$ref":"\/definitions\/non_empty_string"},
"user_id":{"$ref":"\/definitions\/uuid"}},
"required":["password"],
"title":"Login",
"type":"object"
}
`)
}))

API.URL = server.URL
rs := API.Schema().Get(name)

if rs == nil {
t.Fatalf("Couldn't get root schema")
}

if errors, _ := rs.ValidateBytes(valid); len(errors) > 0 {
t.Errorf("Couldn't validate valid JSON: %v", errors)
}
}

0 comments on commit f16b0e5

Please sign in to comment.