Skip to content

Instantly share code, notes, and snippets.

@simonexmachina
Last active December 13, 2019 03:18
Show Gist options
  • Save simonexmachina/95fd8dc814ab7b94088cb7512b470906 to your computer and use it in GitHub Desktop.
Save simonexmachina/95fd8dc814ab7b94088cb7512b470906 to your computer and use it in GitHub Desktop.
class UsefulSearchesService {
async init() {
this.data = await this.fetchData()
}
async get(params) {
setInterval(() => this.handleRefresh(), 0)
return this.data[params]
}
async handleRefresh() {
if (this.shouldRefresh()) {
try {
this.data = await this.fetchData()
}
catch(e) {
// log error
}
}
}
const services = {}
// called on server startup, so the server fails to start if we can't get the data we need
export async function init(languages) {
for (language in languages) {
const service = new UsefulSearchesService()
await service.init()
services[language] = service
}
}
export function getUsefulSearches(language) {
return services[language]
}
// alternative, simpler version that loads/reloads on get
class LazyUsefulSearchesService {
async get(params) {
await this.init()
return this.data[params]
}
async init() {
if (!this.data || this.shouldRefresh()) {
this.data = this.fetchData()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment