Refactor instance list fetcher
This commit is contained in:
parent
295fac6268
commit
fd854ec222
|
@ -2,7 +2,7 @@ const {render, redirect} = require("pinski/plugins")
|
|||
const db = require("../utils/db")
|
||||
const {getToken, getUser} = require("../utils/getuser")
|
||||
const constants = require("../utils/constants")
|
||||
const {getInstances} = require("../background/instances")
|
||||
const {instancesList} = require("../background/instances")
|
||||
const validate = require("../utils/validate")
|
||||
const V = validate.V
|
||||
|
||||
|
@ -11,7 +11,7 @@ module.exports = [
|
|||
route: "/settings", methods: ["GET"], code: async ({req}) => {
|
||||
const user = getUser(req)
|
||||
const settings = user.getSettings()
|
||||
const instances = getInstances()
|
||||
const instances = instancesList.get()
|
||||
return render(200, "pug/settings.pug", {constants, user, settings, instances})
|
||||
}
|
||||
},
|
||||
|
|
|
@ -1,23 +1,45 @@
|
|||
const {request} = require("../utils/request")
|
||||
|
||||
let globalList = []
|
||||
class InstancesList {
|
||||
constructor() {
|
||||
this.list = []
|
||||
this.inflight = null
|
||||
this.update()
|
||||
setInterval(() => {
|
||||
this.update()
|
||||
}, 60*60*1000)
|
||||
}
|
||||
|
||||
function execute() {
|
||||
return request("https://api.invidious.io/instances.json?sort_by=health").then(res => res.json()).then(list => {
|
||||
/**
|
||||
* Updates the list. Returns a promise of the new list. Called
|
||||
* automatically.
|
||||
*/
|
||||
update() {
|
||||
return this.inflight = request("https://api.invidious.io/instances.json?sort_by=health").then(res => res.json()).then(list => {
|
||||
list = list.filter(i => i[1].type === "https").map(i => i[1].uri.replace(/\/+$/, ""))
|
||||
globalList = list
|
||||
}).catch(error => {
|
||||
console.error(error)
|
||||
this.list = list
|
||||
this.inflight = null
|
||||
return this.list
|
||||
})
|
||||
}
|
||||
|
||||
function getInstances() {
|
||||
return globalList
|
||||
/**
|
||||
* Return a promise of the list. If updates are in progress, wait
|
||||
* for them.
|
||||
*/
|
||||
fetch() {
|
||||
if (this.inflight) return this.inflight
|
||||
else return Promise.resolve(this.list)
|
||||
}
|
||||
|
||||
execute()
|
||||
setInterval(() => {
|
||||
execute()
|
||||
}, 60*60*1000)
|
||||
/**
|
||||
* Return the current list, no matter whether it's been updated at all.
|
||||
*/
|
||||
get() {
|
||||
return this.list
|
||||
}
|
||||
}
|
||||
|
||||
module.exports.getInstances = getInstances
|
||||
const instancesList = new InstancesList()
|
||||
|
||||
module.exports.instancesList = instancesList
|
||||
|
|
Loading…
Reference in New Issue