autoInit, refresh in Base class

This commit is contained in:
yky4589 2020-10-25 03:11:27 +09:00
parent c846bd6f61
commit 251e4c482d
7 changed files with 35 additions and 135 deletions

View file

@ -1,38 +1,55 @@
import { Client } from '../models/client.ts' import { Client } from '../models/client.ts'
import * as cache from '../models/cache.ts' import * as cache from '../models/cache.ts'
import endpoint from '../types/endpoint.ts'
interface IInit {
cacheName: string
endpoint: string,
restURLfuncArgs: string[]
}
export class Base { export class Base {
client: Client client: Client
static useCache = true static useCache = true
static cacheName: string static restFunc: ((...restURLfuncArgs: any) => string)[]
static cacheArgIndex = 0
static restFunc: (...restArgs: string[]) => string
constructor (client: Client, _data?: any) { constructor (client: Client) {
this.client = client this.client = client
} }
static async autoInit (client: Client, ...restURLfuncArgs: string[]) { static async autoInit (client: Client, init: IInit) {
if (this.useCache) { if (this.useCache) {
const cached = cache.get( const cached = cache.get(
this.cacheName, init.cacheName,
restURLfuncArgs[this.cacheArgIndex] init.restURLfuncArgs[0]
) )
if (cached !== undefined && cached instanceof this) { if (cached !== undefined && cached instanceof this) {
return cached return cached
} }
} }
const resp = await fetch(this.restFunc(...restURLfuncArgs), { this.restFunc = endpoint.filter(v => v.name !== init.endpoint)
const resp = await fetch(this.restFunc[0](init.restURLfuncArgs), {
headers: { headers: {
Authorization: `Bot ${client.token}` Authorization: `Bot ${client.token}`
} }
}) })
const jsonParsed = await resp.json() const jsonParsed = await resp.json()
const initialized = new this(client, jsonParsed) cache.set(init.cacheName, this.restFunc[0](init.restURLfuncArgs), jsonParsed)
cache.set(this.cacheName, restURLfuncArgs[this.cacheArgIndex], initialized) }
return initialized 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()
return Object.assign(target, jsonParsed)
} }
} }

View file

@ -33,10 +33,6 @@ export class Channel extends Base {
return `<#${this.id}>` return `<#${this.id}>`
} }
static async autoInit (client: Client, channelID: string) {
return super.autoInit(client, channelID)
}
static from ( static from (
data: data:
| GuildChannelCategoryPayload | GuildChannelCategoryPayload

View file

@ -1,7 +1,7 @@
import { Client } from '../models/client.ts' import { Client } from '../models/client.ts'
import { ChannelPayload } from '../types/channelTypes.ts' import { ChannelPayload } from '../types/channelTypes.ts'
import { EmojiPayload } from '../types/emojiTypes.ts' import { EmojiPayload } from '../types/emojiTypes.ts'
import { GUILD } from '../types/endpoint.ts'
import { import {
GuildFeatures, GuildFeatures,
GuildPayload, GuildPayload,
@ -75,7 +75,7 @@ export class Guild extends Base {
this.afkTimeout = data.afk_timeout this.afkTimeout = data.afk_timeout
this.afkChannelID = data.afk_channel_id this.afkChannelID = data.afk_channel_id
this.widgetEnabled = data.widget_enabled this.widgetEnabled = data.widget_enabled
this.widgetChannelID = data.widge_channel_id this.widgetChannelID = data.widget_channel_id
this.verificationLevel = data.verification_level this.verificationLevel = data.verification_level
this.defaultMessageNotifications = data.default_message_notifications this.defaultMessageNotifications = data.default_message_notifications
this.explicitContentFilter = data.explicit_content_filter this.explicitContentFilter = data.explicit_content_filter
@ -108,79 +108,4 @@ export class Guild extends Base {
this.approximatePresenceCount = data.approximate_presence_count this.approximatePresenceCount = data.approximate_presence_count
} }
static async autoInit (client: Client, guildID: string) {
const cached = cache.get('guild', guildID)
if (cached === undefined || !(cached instanceof Guild)) {
const resp = await fetch(GUILD(guildID), {
headers: {
Authorization: `Bot ${client.token}`
}
})
const guildParsed: GuildPayload = await resp.json()
const newGuild = new Guild(client, guildParsed)
cache.set('guild', guildID, newGuild)
return newGuild
} else {
return cached
}
}
async refresh () {
const resp = await fetch(GUILD(this.id), {
headers: {
Authorization: `Bot ${this.client.token}`
}
})
const guildParsed: GuildPayload = await resp.json()
/*for (const rawKey of Object.keys(guildParsed)) {
const _key: string[] = rawKey.split('_').map((v, i) => i === 0 ? v : v.substr(0, 1).toUpperCase() + v.substr(1))
const key = _key.join('')
if (this.hasOwnProperty(key)) this[key] // fucking ts
}*/
this.name = guildParsed.name
this.icon = guildParsed.icon
this.iconHash = guildParsed.icon_hash
this.splash = guildParsed.splash
this.discoverySplash = guildParsed.discovery_splash
this.owner = guildParsed.owner
this.ownerID = guildParsed.owner_id
this.permissions = guildParsed.permissions
this.region = guildParsed.region
this.afkTimeout = guildParsed.afk_timeout
this.afkChannelID = guildParsed.afk_channel_id
this.widgetEnabled = guildParsed.widget_enabled
this.widgetChannelID = guildParsed.widget_channel_id
this.verificationLevel = guildParsed.verification_level
this.defaultMessageNotifications = guildParsed.default_message_notifications
this.explicitContentFilter = guildParsed.explicit_content_filter
this.roles = guildParsed.roles
this.emojis = guildParsed.emojis
this.features = guildParsed.features
this.mfaLevel = guildParsed.mfa_level
this.systemChannelID = guildParsed.system_channel_id
this.systemChannelFlags = guildParsed.system_channel_flags
this.rulesChannelID = guildParsed.rules_channel_id
this.joinedAt = guildParsed.joined_at
this.large = guildParsed.large
this.unavailable = guildParsed.unavailable
this.memberCount = guildParsed.member_count
this.voiceStates = guildParsed.voice_states
this.members = guildParsed.members
this.channels = guildParsed.channels
this.presences = guildParsed.presences
this.maxPresences = guildParsed.max_presences
this.maxMembers = guildParsed.max_members
this.vanityURLCode = guildParsed.vanity_url_code
this.description = guildParsed.description
this.banner = guildParsed.banner
this.premiumTier = guildParsed.premium_tier
this.premiumSubscriptionCount = guildParsed.premium_subscription_count
this.preferredLocale = guildParsed.preferred_locale
this.publicUpdatesChannelID = guildParsed.public_updates_channel_id
this.maxVideoChannelUsers = guildParsed.max_video_channel_users
this.approximateNumberCount = guildParsed.approximate_number_count
this.approximatePresenceCount = guildParsed.approximate_presence_count
}
} }

View file

@ -3,7 +3,6 @@ import { GuildChannelPayload, Overwrite } from '../types/channelTypes.ts'
import { Channel } from './channel.ts' import { Channel } from './channel.ts'
import * as cache from '../models/cache.ts' import * as cache from '../models/cache.ts'
import { Guild } from './guild.ts' import { Guild } from './guild.ts'
import { GUILD_CHANNEL } from '../types/endpoint.ts'
export class GuildChannel extends Channel { export class GuildChannel extends Channel {
guildID: string guildID: string
@ -23,21 +22,4 @@ export class GuildChannel extends Channel {
this.parentID = data.parent_id this.parentID = data.parent_id
} }
static async autoInit (client: Client, guildID: string) {
const cached = cache.get('guildChannel', guildID)
if (cached === undefined || !(cached instanceof GuildChannel)) {
const resp = await fetch(GUILD_CHANNEL(guildID), {
headers: {
Authorization: `Bot ${client.token}`
}
})
const guildChannelParsed: GuildChannelPayload = await resp.json()
const newGuild = new GuildChannel(client, guildChannelParsed)
cache.set('guildChannel', guildID, newGuild)
return newGuild
} else {
return cached
}
}
} }

View file

@ -13,7 +13,7 @@ import { Client } from '../models/client.ts'
import { UserPayload } from '../types/userTypes.ts' import { UserPayload } from '../types/userTypes.ts'
import { RolePayload } from '../types/roleTypes.ts' import { RolePayload } from '../types/roleTypes.ts'
class Message extends Base { export class Message extends Base {
id: string id: string
channelID: string channelID: string
guildID?: string guildID?: string

View file

@ -2,7 +2,6 @@ import { Client } from '../models/client.ts'
import { UserPayload } from '../types/userTypes.ts' import { UserPayload } from '../types/userTypes.ts'
import { Base } from './base.ts' import { Base } from './base.ts'
import * as cache from '../models/cache.ts' import * as cache from '../models/cache.ts'
import { USER } from '../types/endpoint.ts'
export class User extends Base { export class User extends Base {
id: string id: string
@ -43,23 +42,4 @@ export class User extends Base {
this.premiumType = data.premium_type this.premiumType = data.premium_type
this.publicFlags = data.public_flags this.publicFlags = data.public_flags
} }
static async autoInit (client: Client, userID: string) {
// user? users?
const cached = cache.get('user', userID)
if (cached === undefined || !(cached instanceof User)) {
const resp = await fetch(USER(userID), {
headers: {
Authorization: `Bot ${client.token}`
}
})
const userParsed: UserPayload = await resp.json()
const newUser = new User(client, userParsed)
cached.set('user', userID, newUser)
return newUser
} else {
return cached
}
}
} }

View file

@ -139,7 +139,7 @@ const GATEWAY_BOT = () =>
//CDN Endpoints //CDN Endpoints
const CUSTOM_EMOJI = (emojiID: string) => `${DISCORD_CDN_URL}/emojis/${emojiID}` const CUSTOM_EMOJI = (emojiID: string) => `${DISCORD_CDN_URL}/emojis/${emojiID}`
const GUILD_ICON = (guildID: string, iconID: number) => const GUILD_ICON = (guildID: string, iconID: string) =>
`${DISCORD_CDN_URL}/icons/${guildID}/${iconID}` `${DISCORD_CDN_URL}/icons/${guildID}/${iconID}`
const GUILD_SPLASH = (guildID: string, guildSPLASH: string) => const GUILD_SPLASH = (guildID: string, guildSPLASH: string) =>
`${DISCORD_CDN_URL}/splashes/${guildID}/${guildSPLASH}` `${DISCORD_CDN_URL}/splashes/${guildID}/${guildSPLASH}`
@ -153,7 +153,7 @@ const DEFAULT_USER_AVATAR = (iconID: string) =>
`${DISCORD_CDN_URL}/embed/avatars/${iconID}` `${DISCORD_CDN_URL}/embed/avatars/${iconID}`
const USER_AVATAR = (userID: string, iconID: string) => const USER_AVATAR = (userID: string, iconID: string) =>
`${DISCORD_CDN_URL}/avatars/${userID}/${iconID}` `${DISCORD_CDN_URL}/avatars/${userID}/${iconID}`
const APPLICATION_ASSET = (applicationID: string, assetID: number) => const APPLICATION_ASSET = (applicationID: string, assetID: string) =>
`${DISCORD_CDN_URL}/app-icons/${applicationID}/${assetID}` `${DISCORD_CDN_URL}/app-icons/${applicationID}/${assetID}`
const ACHIEVEMENT_ICON = ( const ACHIEVEMENT_ICON = (
applicationID: string, applicationID: string,
@ -182,7 +182,7 @@ const INVITE = (inviteCODE: string) =>
const VOICE_REGIONS = (guildID: string) => const VOICE_REGIONS = (guildID: string) =>
`${DISCORD_API_URL}/v${DISCORD_API_VERSION}/guilds/${guildID}/regions` `${DISCORD_API_URL}/v${DISCORD_API_VERSION}/guilds/${guildID}/regions`
export { export default [
GUILDS, GUILDS,
GUILD, GUILD,
GUILD_AUDIT_LOGS, GUILD_AUDIT_LOGS,
@ -253,4 +253,4 @@ export {
TEMPLATE, TEMPLATE,
INVITE, INVITE,
VOICE_REGIONS VOICE_REGIONS
} ]