2020-10-22 15:50:47 +00:00
|
|
|
import { Client } from '../models/client.ts'
|
2020-10-24 15:00:42 +00:00
|
|
|
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[]
|
|
|
|
}
|
2020-10-21 16:30:42 +00:00
|
|
|
|
2020-10-22 15:50:47 +00:00
|
|
|
export class Base {
|
|
|
|
client: Client
|
2020-10-24 15:00:42 +00:00
|
|
|
static useCache = true
|
2020-10-24 18:11:27 +00:00
|
|
|
static restFunc: ((...restURLfuncArgs: any) => string)[]
|
2020-10-24 15:00:42 +00:00
|
|
|
|
2020-10-24 18:11:27 +00:00
|
|
|
constructor (client: Client) {
|
2020-10-22 15:50:47 +00:00
|
|
|
this.client = client
|
2020-10-21 16:30:42 +00:00
|
|
|
}
|
2020-10-24 15:00:42 +00:00
|
|
|
|
2020-10-24 18:11:27 +00:00
|
|
|
static async autoInit (client: Client, init: IInit) {
|
2020-10-24 15:00:42 +00:00
|
|
|
if (this.useCache) {
|
|
|
|
const cached = cache.get(
|
2020-10-24 18:11:27 +00:00
|
|
|
init.cacheName,
|
|
|
|
init.restURLfuncArgs[0]
|
2020-10-24 15:00:42 +00:00
|
|
|
)
|
|
|
|
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), {
|
2020-10-24 15:00:42 +00:00
|
|
|
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 15:00:42 +00:00
|
|
|
|
2020-10-24 18:11:27 +00:00
|
|
|
return Object.assign(target, jsonParsed)
|
2020-10-24 15:00:42 +00:00
|
|
|
}
|
2020-10-21 16:30:42 +00:00
|
|
|
}
|