1
0
mirror of https://git.sr.ht/~cadence/cloudtube synced 2024-11-14 12:27:28 +00:00
cloudtube/utils/validate.js

100 lines
1.7 KiB
JavaScript
Raw Normal View History

2020-08-30 13:54:59 +00:00
class V {
constructor() {
this.chain = []
this.state = {}
this.finished = false
this.endValue = null
}
with(preset) {
this.check(...preset)
return this
}
check(conditionCallback, elseCallback) {
this.chain.push(() => {
if (!conditionCallback(this.state)) this._end(elseCallback(this.state))
})
return this
}
last(callback) {
this.chain.push(() => {
this._end(callback(this.state))
})
return this
}
go() {
for (const s of this.chain) {
s()
if (this.finished) return this.endValue
}
return {
statusCode: 500,
contentType: "application/json",
content: {
error: "Reached end of V chain without response"
}
}
}
_end(value) {
this.finished = true
this.endValue = value
}
}
function presetLoad(additions) {
return [
state => {
Object.assign(state, additions)
return true
},
null
]
}
function presetURLParamsBody() {
return [
state => {
try {
state.params = new URLSearchParams(state.body.toString())
return true
} catch (e) {
console.error(e)
return false
}
},
() => {
return {
statusCode: 400,
contentType: "application/json",
content: {
error: "Could not parse body as URLSearchParams"
}
}
}
]
}
2020-12-29 03:21:48 +00:00
function presetEnsureParams(list) {
return [
state => {
return list.every(name => state.params.has(name))
},
() => ({
statusCode: 400,
contentType: "application/json",
2021-05-11 12:29:05 +00:00
content: {
error: `Some required body parameters were missing. Required parameters: ${list.join(", ")}`
}
2020-12-29 03:21:48 +00:00
})
]
}
2020-08-30 13:54:59 +00:00
module.exports.V = V
module.exports.presetLoad = presetLoad
module.exports.presetURLParamsBody = presetURLParamsBody
2020-12-29 03:21:48 +00:00
module.exports.presetEnsureParams = presetEnsureParams