JSON Schema Validator: HyperTrack - Trip Creation
Validate your request body to see if it complies with the strictly defined JSON schema to make successful Trips API calls
by agraebe
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/ajv/6.10.2/ajv.min.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://unpkg.com/[email protected]/min/vs/loader.js"></script>
<div id="container">
</div>
<div id="validation" class="success">Validation succesful!
</div>
CSS
html,
body {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
margin: 0;
padding: 0;
overflow: hidden;
}
#container {
height: 75%;
}
#validation {
height: 25%;
padding: 50px;
color: white;
background-color: #f3f3f3;
font-size: 14pt;
font-weight: 400;
text-align: center;
font-family: Frutiger, "Frutiger Linotype", Univers, Calibri, "Gill Sans", "Gill Sans MT", "Myriad Pro", Myriad, "DejaVu Sans Condensed", "Liberation Sans", "Nimbus Sans L", Tahoma, Geneva, "Helvetica Neue", Helvetica, Arial, sans-serif;
}
.success {
background-color: #0b850f !important;
}
.error {
background-color: #d94c29 !important;
}
JavaScript
const jsonSchemaURL = "https://gist.githubusercontent.com/agraebe/766fc8f38f42654d78ece155a792d4d0/raw/2dc4c88606538cb79cd5a5ba4664fc2e4c6d14fc/v3-create-trip.json";
let jsonSchema, validate;
let ajv = new Ajv({
allErrors: true
});
fetch(jsonSchemaURL)
.then(function(res) {
return res.json();
})
.then(function(json) {
ajv.addSchema(json, 'trip-create');
});
require.config({
paths: {
'vs': 'https://unpkg.com/[email protected]/min/vs'
}
});
window.MonacoEnvironment = {
getWorkerUrl: () => proxy
};
let proxy = URL.createObjectURL(new Blob([`
self.MonacoEnvironment = {
baseUrl: 'https://unpkg.com/[email protected]/min/'
};
importScripts('https://unpkg.com/[email protected]/min/vs/base/worker/workerMain.js');
`], {
type: 'text/javascript'
}));
require(["vs/editor/editor.main"], function() {
let editor = monaco.editor.create(document.getElementById('container'), {
value: [
'{',
'\t"device_id": "00112233-4455-6677-8899-AABBCCDDEEFF",',
'\t"destination": {',
'\t\t"geometry": {',
'\t\t\t"type": "Point",',
'\t\t\t"coordinates": [-122.3980960195712, 37.7930386903944]',
'\t\t},',
'\t\t"scheduled_at": "2019-05-03T06:25:51.238000Z"',
'\t},',
'\t"metadata": {',
'\t\t"customer_id": "ABC123"',
'\t}',
'}'
].join('\n'),
language: 'json',
theme: 'vs-dark'
});
editor.addListener('didType', () => {
try {
valid = ajv.validate('trip-create', JSON.parse(editor.getValue()));
if (!valid) {
document.getElementById("validation").innerHTML = "Validation failed: " + ajv.errorsText().replace(/ *, */g, '<br>');
document.getElementById("validation").classList.add('error');
document.getElementById("validation").classList.remove('success');
} else {
document.getElementById("validation").innerHTML = "Validation succesful!";
document.getElementById("validation").classList.remove('error');
...