Skip to content

Instantly share code, notes, and snippets.

@renatoargh
Last active July 5, 2019 14:48
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 renatoargh/7f8a34bd957f323648630b987fbf5501 to your computer and use it in GitHub Desktop.
Save renatoargh/7f8a34bd957f323648630b987fbf5501 to your computer and use it in GitHub Desktop.
Refactoring Session #1
const validator = new Validator('http://example.com/swagger.yaml')
await validator.init()
validator.validate('UserCreated', payload)
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