mirror of
https://github.com/jaronpate/unicord.git
synced 2026-10-18 21:47:40 +00:00
Hydrator is coming along
This commit is contained in:
+4
-3
@@ -6,7 +6,7 @@ export class API {
|
||||
constructor(private client: Client) {}
|
||||
|
||||
async request<T = any>(method: string, path: string, data?: any): Promise<T> {
|
||||
const url = new URL(path, this.base_url).toString();
|
||||
const url = `${this.base_url}${path.startsWith('/') ? '' : '/'}${path}`;
|
||||
const headers = {
|
||||
Authorization: `Bot ${this.client.token}`,
|
||||
'Accept': 'application/json',
|
||||
@@ -14,6 +14,7 @@ export class API {
|
||||
};
|
||||
|
||||
console.log(`API Request: ${method} ${url}`);
|
||||
console.log(`API Body: ${JSON.stringify(data, null, 4)}`);
|
||||
|
||||
const response = await fetch(url, {
|
||||
method,
|
||||
@@ -22,8 +23,8 @@ export class API {
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
console.error(`Failed to fetch: ${response.statusText} ${response.url} ${response.status}`);
|
||||
console.error(response.json());
|
||||
// console.error(`Failed to fetch: ${response.statusText} ${response.url} ${response.status}`);
|
||||
console.log('Failed Request Response: ', await response.text());
|
||||
throw new Error(`Failed to fetch: ${response.statusText}`);
|
||||
}
|
||||
|
||||
|
||||
@@ -3,19 +3,19 @@ import { exists } from "../utils";
|
||||
import type { API } from "./api";
|
||||
import type { Processor } from "./processor";
|
||||
|
||||
export class ObjectCache<T> {
|
||||
cache = new Map<string, Promise<T> | T>();
|
||||
export class ObjectCache<T, K extends T> {
|
||||
cache = new Map<string, Promise<K>>();
|
||||
readonly type: string;
|
||||
|
||||
constructor(protected api: API, processor: Processor, type: string, private readonly factory: (...args: any[]) => Promise<T>, events: string[]) {
|
||||
constructor(protected api: API, processor: Processor, type: string, private readonly factory: { fromDiscord: (data: any) => K } & (new (data: T) => T), events: string[]) {
|
||||
this.type = type;
|
||||
processor.events.register(events, async (_context: Context, e: Record<string, any>) => {
|
||||
this.cache.set(e.id, factory(e));
|
||||
this.cache.set(e.id, Promise.resolve(factory.fromDiscord(e)));
|
||||
});
|
||||
}
|
||||
|
||||
set(object_id: string, object: T): void {
|
||||
this.cache.set(object_id, object);
|
||||
set(object_id: string, object: K): void {
|
||||
this.cache.set(object_id, Promise.resolve(object));
|
||||
}
|
||||
|
||||
// update(object_id: string, object: Partial<T>): void {
|
||||
@@ -29,14 +29,14 @@ export class ObjectCache<T> {
|
||||
// }
|
||||
// }
|
||||
|
||||
async fetch(object_id: string, ..._args: any[]): Promise<T> {
|
||||
const req = this.api.get(`/${this.type}/${object_id}`).then((data) => this.factory(data));
|
||||
async fetch(object_id: string, ..._args: any[]): Promise<K> {
|
||||
const req = this.api.get(`/${this.type}/${object_id}`).then((data) => this.factory.fromDiscord(data));
|
||||
this.cache.set(object_id, req);
|
||||
req.catch(() => this.cache.delete(object_id));
|
||||
return await req;
|
||||
}
|
||||
|
||||
async get(object_id: string, ..._args: any[]): Promise<T> {
|
||||
async get(object_id: string, ..._args: any[]): Promise<K> {
|
||||
if (this.cache.has(object_id)) {
|
||||
return await Promise.resolve(this.cache.get(object_id)!);
|
||||
} else {
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
import { API } from './api';
|
||||
import { Gateway } from './gateway';
|
||||
import { Processor } from './processor';
|
||||
import { Intent, type ClientConfig } from '../types/common';
|
||||
import { Expectation, Intent, type ClientConfig } from '../types/common';
|
||||
import { exists, isNil } from '../utils/index';
|
||||
import type { Handler } from '../types/hander';
|
||||
import { DiscordMessage, Message } from '../types/message';
|
||||
import { Guilds } from './guilds';
|
||||
import { Users } from './users';
|
||||
import { Messages } from './messages';
|
||||
import { hydrator, type Hydrateable } from './hydrator';
|
||||
|
||||
export class Client {
|
||||
readonly token: string;
|
||||
@@ -65,12 +66,16 @@ export class Client {
|
||||
}
|
||||
}
|
||||
|
||||
hydrator = async<T extends Hydrateable, K extends Expectation[]>(data: T, expectations: K) => {
|
||||
return hydrator<T, K>(data, expectations, this, this.api);
|
||||
}
|
||||
|
||||
sendMessage = async (channel_id: string, message: Message | string) => {
|
||||
if (typeof message === 'string') {
|
||||
message = new Message().setContent(message);
|
||||
}
|
||||
|
||||
return Message.hydrate(DiscordMessage.fromAPIResponse(await this.api.post(`/channels/${channel_id}/messages`, message.toJSON())), this, this.api);
|
||||
return Message.fromDiscord(DiscordMessage.fromAPIResponse(await this.api.post(`/channels/${channel_id}/messages`, message.toJSON())));
|
||||
}
|
||||
|
||||
chatCommands = {
|
||||
|
||||
@@ -141,8 +141,7 @@ export class Gateway {
|
||||
|
||||
if (['MESSAGE_CREATE', 'MESSAGE_UPDATE'].includes(event_name)) {
|
||||
// If the event is a message event, create a message object
|
||||
const discord_message = DiscordMessage.fromAPIResponse(event_data);
|
||||
const message = await Message.hydrate(discord_message, this.client, this.api);
|
||||
const message = Message.fromDiscord(DiscordMessage.fromAPIResponse(event_data));
|
||||
// And then generate the context
|
||||
context = new Context(this.client, this.api, message);
|
||||
}
|
||||
@@ -165,7 +164,7 @@ export class Gateway {
|
||||
return;
|
||||
}
|
||||
// Extract the author
|
||||
const author = User.hydrate(DiscordUser.fromAPIResponse(payload.d.author));
|
||||
const author = User.fromDiscord(DiscordUser.fromAPIResponse(payload.d.author));
|
||||
// Store the author in the cache
|
||||
this.client.users.set(author.id, author);
|
||||
// Extract the content
|
||||
@@ -186,9 +185,8 @@ export class Gateway {
|
||||
// Extract the command name
|
||||
// TODO: Case insensitive config?
|
||||
const command = args.shift()!;
|
||||
console.log('payload.d', payload.d)
|
||||
// Create a new message object from the payload
|
||||
const message = await Message.hydrate(DiscordMessage.fromAPIResponse(payload.d), this.client, this.api);
|
||||
const message = Message.fromDiscord(DiscordMessage.fromAPIResponse(payload.d));
|
||||
// Generate context
|
||||
const context = new Context(this.client, this.api, message);
|
||||
// Check if command exists
|
||||
|
||||
@@ -3,8 +3,8 @@ import type { API } from "./api";
|
||||
import { ObjectCache } from "./cache";
|
||||
import type { Processor } from "./processor";
|
||||
|
||||
export class Guilds extends ObjectCache<Guild> {
|
||||
export class Guilds extends ObjectCache<Guild, Guild> {
|
||||
constructor (api: API, processor: Processor) {
|
||||
super(api, processor, 'guilds', Guild.factory, ['GUILD_CREATE', 'GUILD_UPDATE']);
|
||||
super(api, processor, 'guilds', Guild, ['GUILD_CREATE', 'GUILD_UPDATE']);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import { Expectation } from "../types/common";
|
||||
import { Context, type HydratedContext } from "../types/context";
|
||||
import { Message, type HydratedMessage } from "../types/message";
|
||||
import { exists } from "../utils";
|
||||
import type { API } from "./api";
|
||||
import type { Client } from "./client";
|
||||
|
||||
export type GatewayObject = Message;
|
||||
export type Hydrateable = Context | GatewayObject
|
||||
export type Hydrated<T extends Hydrateable, K extends Array<Expectation>> =
|
||||
T extends Message ? HydratedMessage<K> :
|
||||
T extends Context ? HydratedContext<K> : never;
|
||||
|
||||
export async function hydrator<T extends Hydrateable, K extends Array<Expectation>>(data: T, expectations: K, client: Client, api: API): Promise<(data: unknown) => data is Hydrated<T, K>> {
|
||||
let hydrated = true;
|
||||
|
||||
if (data instanceof Context) {
|
||||
for (const expectation of expectations) {
|
||||
if (expectation === Expectation.Guild && exists(data.guild_id)) {
|
||||
let context = data as unknown as HydratedContext<[Expectation.Guild, ...Expectation[]]>;
|
||||
context.guild = await client.guilds.get(data.guild_id);
|
||||
} else {
|
||||
hydrated = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else if (data instanceof Message) {
|
||||
for (const expectation of expectations) {
|
||||
if (expectation === Expectation.Message && exists(data.message_reference?.id)) {
|
||||
let message = data as unknown as HydratedMessage<[Expectation.Message, ...Expectation[]]>;
|
||||
message.reference = await client.messages.get(data.message_reference.channel_id, data.message_reference.id);
|
||||
} else if (expectation === Expectation.Guild && exists(data.guild_id)) {
|
||||
let message = data as unknown as HydratedMessage<[Expectation.Guild, ...Expectation[]]>;
|
||||
message.guild = await client.guilds.get(data.guild_id);
|
||||
} else {
|
||||
hydrated = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return function (data: unknown): data is Hydrated<T, K> {
|
||||
return hydrated;
|
||||
}
|
||||
}
|
||||
@@ -1,22 +1,22 @@
|
||||
import { Message } from "../types/message";
|
||||
import { Message, type MessagePayload } from "../types/message";
|
||||
import type { API } from "./api";
|
||||
import { ObjectCache } from "./cache";
|
||||
import type { Client } from "./client";
|
||||
import type { Processor } from "./processor";
|
||||
|
||||
export class Messages extends ObjectCache<Message> {
|
||||
export class Messages extends ObjectCache<Message, MessagePayload> {
|
||||
constructor (protected client: Client, api: API, processor: Processor) {
|
||||
super(api, processor, 'message', (data) => Message.factory(data, client, api), ['MESSAGE_CREATE', 'MESSAGE_UPDATE']);
|
||||
super(api, processor, 'message', Message, ['MESSAGE_CREATE', 'MESSAGE_UPDATE']);
|
||||
}
|
||||
|
||||
async fetch(channel_id: string, message_id: string, resolveReference: boolean = true): Promise<Message> {
|
||||
const req = this.api.get(`/channels/${channel_id}/messages/${message_id}`).then((data) => Message.factory(data, this.client, this.api, undefined, resolveReference));
|
||||
async fetch(channel_id: string, message_id: string, resolveReference: boolean = true): Promise<MessagePayload> {
|
||||
const req = this.api.get(`/channels/${channel_id}/messages/${message_id}`).then((data) => Message.fromDiscord(data));
|
||||
this.cache.set(message_id, req);
|
||||
req.catch(() => this.cache.delete(message_id));
|
||||
return await req;
|
||||
}
|
||||
|
||||
async get(channel_id: string, message_id: string, resolveReference: boolean = true): Promise<Message> {
|
||||
async get(channel_id: string, message_id: string, resolveReference: boolean = true): Promise<MessagePayload> {
|
||||
if (this.cache.has(message_id)) {
|
||||
return await Promise.resolve(this.cache.get(message_id)!);
|
||||
} else {
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import type { User } from "../types/user";
|
||||
import { User } from "../types/user";
|
||||
import type { API } from "./api";
|
||||
import { ObjectCache } from "./cache";
|
||||
import type { Processor } from "./processor";
|
||||
|
||||
export class Users extends ObjectCache<User> {
|
||||
export class Users extends ObjectCache<User, User> {
|
||||
constructor (api: API, processor: Processor) {
|
||||
super(api, processor, 'users', []);
|
||||
super(api, processor, 'users', User, []);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user