In my current work, I am looking at ways to try to enforce particular standards across multiple and larger projects.
This means standards set across different languages that are flexible, extensible and kept up to date.
A few of my upcoming posts will be looking into some of my spikes that I am doing to as investigation, starting with the
What is JSON Schema? Here is a definition from the JSON Schema Org site:
JSON Schema is a powerful tool for validating the structure of JSON data.
The hope is that I can use tooling for JSON schema and Open API to help with structuring micro-services and providing “cheap” contract testing.
Setting up the project
Compiling From Source
In my example, I will opt to generate by reading in from a particular file.
This will be all the code we need for our example.
The JSON Schema file
For this part, let’s model a basic book and a collection. We need to add some schema info the the
I won’t go too deep into the modelling itself with JSON schema, but these are the definitions I am coming up with:
The Book JSON
Let’s add some info to our basic
example.json file that we can test against:
Running Our Creation
node index.js from the root directory.
You will actually notice that I left a mistake in there! The following will log out:
Our validation (or invalidation per se) was a success! We said in the schema that it should be a string but we received the number
Head back to
book.json and convert the value to type
number. Now if we run it again
node index.js again, we will get some success! We will even see our
books.d.ts file has been written.
You might be wondering why I am writing this blog post in
jsto generate TypeScript types. Honestly, when I am doing spikes I normally just write quick scripts and keep out the fluff.
You will see the following is generated:
Great success! We now have a type for our schema that we can import in.
Resources and Further Reading
Image credit: Tony Pham
Originally posted on my blog.