From fd854ec22241453165886747d05b1510fb12345f Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Mon, 1 Mar 2021 23:35:09 +1300 Subject: [PATCH] Refactor instance list fetcher --- api/settings.js | 4 +-- background/instances.js | 56 ++++++++++++++++++++++++++++------------- 2 files changed, 41 insertions(+), 19 deletions(-) diff --git a/api/settings.js b/api/settings.js index b891886..5b2d2d9 100644 --- a/api/settings.js +++ b/api/settings.js @@ -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}) } }, diff --git a/background/instances.js b/background/instances.js index 4682b85..c4061da 100644 --- a/background/instances.js +++ b/background/instances.js @@ -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 => { - list = list.filter(i => i[1].type === "https").map(i => i[1].uri.replace(/\/+$/, "")) - globalList = list - }).catch(error => { - console.error(error) - }) + /** + * 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(/\/+$/, "")) + this.list = list + this.inflight = null + return this.list + }) + } + + /** + * 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) + } + + /** + * Return the current list, no matter whether it's been updated at all. + */ + get() { + return this.list + } } -function getInstances() { - return globalList -} +const instancesList = new InstancesList() -execute() -setInterval(() => { - execute() -}, 60*60*1000) - -module.exports.getInstances = getInstances +module.exports.instancesList = instancesList