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 {
|
2020-10-25 06:50:32 +00:00
|
|
|
useCache?: boolean
|
2020-10-24 18:11:27 +00:00
|
|
|
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-25 06:50:32 +00:00
|
|
|
static useCache?: boolean = true
|
2020-10-25 08:02:24 +00:00
|
|
|
static restFunc?: ((...restURLfuncArgs: string[]) => string)
|
2020-10-24 15:00:42 +00:00
|
|
|
|
2020-10-25 08:02:24 +00:00
|
|
|
constructor (client: Client, _data?: any) {
|
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-25 06:50:32 +00:00
|
|
|
this.useCache = init.useCache;
|
|
|
|
const cacheID = init.restURLfuncArgs.join(':')
|
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,
|
2020-10-25 06:50:32 +00:00
|
|
|
cacheID
|
2020-10-24 15:00:42 +00:00
|
|
|
)
|
2020-10-25 00:15:33 +00:00
|
|
|
if (cached !== undefined) {
|
2020-10-24 15:00:42 +00:00
|
|
|
return cached
|
|
|
|
}
|
|
|
|
}
|
2020-10-25 08:18:32 +00:00
|
|
|
this.restFunc = endpoint.find(v => v.name === init.endpoint)
|
2020-10-25 08:02:24 +00:00
|
|
|
// TODO: Make error for this
|
|
|
|
if(this.restFunc) {
|
|
|
|
const resp = await fetch(this.restFunc(...init.restURLfuncArgs), {
|
|
|
|
headers: {
|
|
|
|
Authorization: `Bot ${client.token}`
|
|
|
|
}
|
|
|
|
})
|
|
|
|
const jsonParsed = await resp.json()
|
2020-10-24 15:00:42 +00:00
|
|
|
|
2020-10-25 08:02:24 +00:00
|
|
|
cache.set(init.cacheName, cacheID, new this(client, jsonParsed))
|
|
|
|
|
|
|
|
return new this(client, jsonParsed)
|
|
|
|
}
|
2020-10-24 18:11:27 +00:00
|
|
|
}
|
|
|
|
|
2020-10-25 06:50:32 +00:00
|
|
|
async refresh (client: Client, init: IInit) {
|
2020-10-25 08:02:24 +00:00
|
|
|
const restFunc: ((...restURLfuncArgs: string[]) => string) | undefined = endpoint.find(v => v.name === init.endpoint)
|
|
|
|
// TODO: Make error for this
|
|
|
|
if(restFunc) {
|
|
|
|
const resp = await fetch(restFunc(...init.restURLfuncArgs), {
|
|
|
|
headers: {
|
|
|
|
Authorization: `Bot ${client.token}`
|
|
|
|
}
|
|
|
|
})
|
|
|
|
const jsonParsed = await resp.json()
|
|
|
|
|
|
|
|
Object.assign(this, jsonParsed)
|
|
|
|
}
|
2020-10-24 15:00:42 +00:00
|
|
|
}
|
2020-10-21 16:30:42 +00:00
|
|
|
}
|