Allow got as request backend

This commit is contained in:
Cadence Fish
2020-03-15 19:50:29 +13:00
parent a861df2662
commit 3efc4928a5
10 changed files with 439 additions and 51 deletions

View File

@@ -0,0 +1,46 @@
try {
var got = require("got").default
} catch (e) {}
class Got {
constructor(url, options, stream) {
if (!got) throw new Error("`got` is not installed, either install it or set a different request backend.")
this.url = url
this.options = options
}
stream() {
return Promise.resolve(got.stream(this.url, this.options))
}
send() {
if (!this.instance) {
this.instance = got(this.url, this.options)
}
return this
}
/**
* @returns {Promise<import("./reference").GrabResponse>}
*/
response() {
return this.send().instance.then(res => ({
status: res.statusCode
}))
}
async check(test) {
await this.send().response().then(res => test(res))
return this
}
json() {
return this.send().instance.json()
}
text() {
return this.send().instance.text()
}
}
module.exports = Got

View File

@@ -0,0 +1,30 @@
const fetch = require("node-fetch").default
class NodeFetch {
constructor(url, options) {
this.instance = fetch(url, options)
}
stream() {
return this.instance.then(res => res.body)
}
response() {
return this.instance
}
json() {
return this.instance.then(res => res.json())
}
text() {
return this.instance.then(res => res.text())
}
async check(test) {
await this.response().then(res => test(res))
return this
}
}
module.exports = NodeFetch

View File

@@ -0,0 +1,45 @@
/**
* @typedef GrabResponse
* @property {number} status
*/
// @ts-nocheck
class GrabReference {
/**
* @param {string} url
* @param {any} options
*/
constructor(url, options) {
throw new Error("This is the reference class, do not instantiate it.")
}
// Please help me type this
/**
* @returns {Promise<any>}
*/
stream() {}
/**
* @returns {Promise<GrabResponse>}
*/
response() {}
/**
* @returns {Promise<any>}
*/
json() {}
/**
* @returns {Promise<string>}
*/
text() {}
/**
* @param {(res: GrabResponse) => any}
* @returns {Promise<Reference>}
*/
check(test) {}
}
module.exports = GrabReference