harmony/src/structures/base.ts

64 lines
1.7 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 {
useCache?: boolean
2020-10-24 18:11:27 +00:00
cacheName: string
endpoint: string,
restURLfuncArgs: string[]
}
export class Base {
client: Client
static useCache?: boolean = true
2020-10-25 08:02:24 +00:00
static restFunc?: ((...restURLfuncArgs: string[]) => string)
2020-10-25 08:02:24 +00:00
constructor (client: Client, _data?: any) {
this.client = client
}
2020-10-24 18:11:27 +00:00
static async autoInit (client: Client, init: IInit) {
this.useCache = init.useCache;
const cacheID = init.restURLfuncArgs.join(':')
if (this.useCache) {
const cached = cache.get(
2020-10-24 18:11:27 +00:00
init.cacheName,
cacheID
)
2020-10-25 00:15:33 +00:00
if (cached !== undefined) {
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-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
}
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)
}
}
}