Skip to content

Instantly share code, notes, and snippets.

@rwilcox
Created November 26, 2018 03:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rwilcox/41f1e226bc5628c4f9393fc79a07e14e to your computer and use it in GitHub Desktop.
Save rwilcox/41f1e226bc5628c4f9393fc79a07e14e to your computer and use it in GitHub Desktop.
const process = require("process")
const superagent = require('superagent')
const Ajv = require("ajv")
// This example is inspired by the idea of https://riposte.in/
// although that package has a way better DSL by not being written in Javascript
// Normally a playground script like this would serve two purposes:
// 1. All developers to pass around scripts of things that Should Work
// 2. Give developer a way to validate the JSON that is coming back
// ... this may or may not be relevent
async function schema() {
const res = await superagent.get("http://swapi.co/api/people/schema")
return res.body
}
async function callIt() {
const res = await superagent.get('https://swapi.co/api/people/1')
//console.log(res.body.name)
return res.body
}
function validateFunction(schema) {
let ajv = new Ajv({schemaId: 'id'})
ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-04.json'));
// console.log(schema)
return ajv.compile(schema) // higher order function!!
}
Promise.all( [schema(), callIt()] ).then( ([schema, data] ) => {
console.log( validateFunction(schema)(data) )
console.log(data.name)
process.exit()
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment