fql-toolkit
Version:
59 lines (53 loc) • 1.43 kB
JavaScript
import FQLError from "./errors.js"
class FQLResponse {
constructor({msg, output = '', fql_token = [], error = false}){
this.message = msg
this.output = output
this.fqlToken = fql_token
this.isError = error
}
_handleCallback(callback){
callback({
message: this.message,
output: this.output,
fqlToken: this.fqlToken,
isError: this.isError
})
}
onSuccess (callback){
if (!this.isError){ this._handleCallback(callback) }
return this
}
onError (callback){
if (this.isError){ this._handleCallback(callback) }
return this
}
}
export default class FQLClient{
constructor({token, url}){
this.url = url
this.headers = {
'Content-Type': 'application/json'
}
this.token = token
}
async executeFQL(query, fqlToken = null){
return await fetch(`${this.url}/api/run_code`, {
method: "POST",
headers: this.headers,
body: JSON.stringify({ code: query, token: this.token, fql_token: fqlToken})
})
.then(async (res) => {
if (!res.ok){
throw new FQLError('FQL query execution failed')
}
return res.json()
})
.then(data => new FQLResponse(data))
.catch((err) => {
if (err instanceof FQLError)
return new FQLResponse({msg: err.message, error: true})
return new FQLResponse({msg: `FQL execution failed: ${err.message}`, error: true})
})
}
}