Last active
July 5, 2019 14:48
-
-
Save renatoargh/7f8a34bd957f323648630b987fbf5501 to your computer and use it in GitHub Desktop.
Refactoring Session #1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const validator = new Validator('http://example.com/swagger.yaml') | |
await validator.init() | |
validator.validate('UserCreated', payload) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const extRegex = '\.[^.\\/:*?"<>|\r\n]+$' | |
const httpRegex = '^(http|https):\/\/' | |
class Validator() { | |
constructor (path) { | |
this.path = path | |
} | |
async init() { | |
const [ext] = this.path.match(extRegex) | |
let schema = null | |
if (this.path.match(httpRegex)) { | |
return axios.get(this.path).then((res) => { | |
if (ext === '.json') { | |
schema = res | |
} else if (ext === '.yaml' || ext === '.yml') { | |
schema = yaml.parse(res) | |
} | |
this.schema = schema | |
}) | |
} else { | |
if (ext === '.json') { | |
return new Promise((resolve, reject) => { | |
fs.readFile(this.path, 'utf8', (err, data) => { | |
if (err) return reject(err) | |
this.schema = JSON.parse(data) | |
resolve() | |
}) | |
} | |
} else if (ext === '.yaml' || ext === '.yml') { | |
this.schema = yaml.load(this.path) | |
} | |
} | |
} | |
validate(type, payload) { | |
// Here we validate `payload` | |
// against `this.schema[type]` | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment