harmony/src/structures/base.ts

56 lines
1.4 KiB
TypeScript
Raw Normal View History

import { Client } from '../models/client.ts'
import * as cache from '../models/cache.ts'
2020-10-24 18:11:27 +00:00
import endpoint from '../types/endpoint.ts'
interface IInit {
cacheName: string
endpoint: string,
restURLfuncArgs: string[]
}
export class Base {
client: Client
static useCache = true
2020-10-24 18:11:27 +00:00
static restFunc: ((...restURLfuncArgs: any) => string)[]
2020-10-24 18:11:27 +00:00
constructor (client: Client) {
this.client = client
}
2020-10-24 18:11:27 +00:00
static async autoInit (client: Client, init: IInit) {
if (this.useCache) {
const cached = cache.get(
2020-10-24 18:11:27 +00:00
init.cacheName,
init.restURLfuncArgs[0]
)
if (cached !== undefined && cached instanceof this) {
return cached
}
}
2020-10-24 18:11:27 +00:00
this.restFunc = endpoint.filter(v => v.name !== init.endpoint)
const resp = await fetch(this.restFunc[0](init.restURLfuncArgs), {
headers: {
Authorization: `Bot ${client.token}`
}
})
const jsonParsed = await resp.json()
2020-10-24 18:11:27 +00:00
cache.set(init.cacheName, this.restFunc[0](init.restURLfuncArgs), jsonParsed)
}
static async refresh (client: Client, target: any, init: IInit) {
this.restFunc = endpoint.filter(v => v.name !== init.endpoint)
const resp = await fetch(this.restFunc[0](init.restURLfuncArgs), {
headers: {
Authorization: `Bot ${client.token}`
}
})
const jsonParsed = await resp.json()
2020-10-24 18:11:27 +00:00
return Object.assign(target, jsonParsed)
}
}