mirror of
https://github.com/jaronpate/unicord.git
synced 2026-10-18 21:47:40 +00:00
regorganizing and attempting to allow rehydration
This commit is contained in:
@@ -1,50 +0,0 @@
|
||||
import type { Context } from "../types/context";
|
||||
import { exists } from "../utils";
|
||||
import type { API } from "./api";
|
||||
import type { Processor } from "./processor";
|
||||
|
||||
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: { 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, Promise.resolve(factory.fromDiscord(e)));
|
||||
});
|
||||
}
|
||||
|
||||
set(object_id: string, object: K): void {
|
||||
this.cache.set(object_id, Promise.resolve(object));
|
||||
}
|
||||
|
||||
// update(object_id: string, object: Partial<T>): void {
|
||||
// const existing = this.cache.get(object_id);
|
||||
|
||||
// if (exists(existing)) {
|
||||
// // TODO: Idk wtf happens if this is called on two classes
|
||||
// this.cache.set(object_id, { ...existing, ...object });
|
||||
// } else {
|
||||
// this.cache.set(object_id, object as T);
|
||||
// }
|
||||
// }
|
||||
|
||||
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<K> {
|
||||
if (this.cache.has(object_id)) {
|
||||
return await Promise.resolve(this.cache.get(object_id)!);
|
||||
} else {
|
||||
return this.fetch(object_id);
|
||||
}
|
||||
}
|
||||
|
||||
list(): Map<string, Promise<T> | T> {
|
||||
return this.cache;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import { fromDiscord } from "../../types/common";
|
||||
import type { Context } from "../../types/context";
|
||||
import type { API } from "../api";
|
||||
import type { Processor } from "../processor";
|
||||
|
||||
|
||||
export class ObjectCache<T, K extends T> {
|
||||
cache = new Map<string, K>();
|
||||
requests = new Map<string, Promise<K>>();
|
||||
readonly type: 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[fromDiscord](e));
|
||||
});
|
||||
}
|
||||
|
||||
set(object_id: string, object: K): void {
|
||||
this.cache.set(object_id, object);
|
||||
}
|
||||
|
||||
// update(object_id: string, object: Partial<T>): void {
|
||||
// const existing = this.cache.get(object_id);
|
||||
|
||||
// if (exists(existing)) {
|
||||
// // TODO: Idk wtf happens if this is called on two classes
|
||||
// this.cache.set(object_id, { ...existing, ...object });
|
||||
// } else {
|
||||
// this.cache.set(object_id, object as T);
|
||||
// }
|
||||
// }
|
||||
|
||||
async fetch(object_id: string, ..._args: any[]): Promise<K> {
|
||||
if (this.requests.has(object_id)) {
|
||||
return this.requests.get(object_id)!;
|
||||
// } else if (this.cache.has(object_id)) {
|
||||
// return Promise.resolve(this.cache.get(object_id)!);
|
||||
} else {
|
||||
// Dispatch the request
|
||||
const req = this.api.get(`/${this.type}/${object_id}`).then((data) => {
|
||||
// Create the object
|
||||
const object = this.factory[fromDiscord](data);
|
||||
// Save the object
|
||||
this.cache.set(object_id, object);
|
||||
// Return the object
|
||||
return object;
|
||||
});
|
||||
// Save the request
|
||||
this.requests.set(object_id, req);
|
||||
// Remove the request from the cache if it succeeds
|
||||
req.then(() => this.requests.delete(object_id));
|
||||
// Remove the request from the cache if it fails
|
||||
req.catch(() => this.requests.delete(object_id));
|
||||
// Return the request
|
||||
return req;
|
||||
}
|
||||
}
|
||||
|
||||
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 {
|
||||
return this.fetch(object_id);
|
||||
}
|
||||
}
|
||||
|
||||
list(): Map<string, Promise<T> | T> {
|
||||
return this.cache;
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Guild } from "../types/guild";
|
||||
import type { API } from "./api";
|
||||
import { Guild } from "../../types/guild";
|
||||
import type { API } from "../api";
|
||||
import type { Processor } from "../processor";
|
||||
import { ObjectCache } from "./cache";
|
||||
import type { Processor } from "./processor";
|
||||
|
||||
export class Guilds extends ObjectCache<Guild, Guild> {
|
||||
constructor (api: API, processor: Processor) {
|
||||
@@ -0,0 +1,42 @@
|
||||
import { fromDiscord } from "../../types/common";
|
||||
import { Message, type MessagePayload } from "../../types/message";
|
||||
import type { API } from "../api";
|
||||
import type { Client } from "../client";
|
||||
import type { Processor } from "../processor";
|
||||
import { ObjectCache } from "./cache";
|
||||
|
||||
|
||||
export class Messages extends ObjectCache<Message, MessagePayload> {
|
||||
constructor (protected client: Client, api: API, processor: Processor) {
|
||||
super(api, processor, 'message', Message, ['MESSAGE_CREATE', 'MESSAGE_UPDATE']);
|
||||
}
|
||||
|
||||
async fetch(channel_id: string, message_id: string): Promise<MessagePayload> {
|
||||
if (this.requests.has(message_id)) {
|
||||
return this.requests.get(message_id)!;
|
||||
} else {
|
||||
// Dispatch the request
|
||||
const req = this.api.get(`/channels/${channel_id}/messages/${message_id}`).then((data) => {
|
||||
const message = Message[fromDiscord](data);
|
||||
this.cache.set(message_id, message);
|
||||
return message;
|
||||
});
|
||||
// Save the request
|
||||
this.requests.set(message_id, req);
|
||||
// Remove the request from the cache if it succeeds
|
||||
req.then(() => this.requests.delete(message_id));
|
||||
// Remove the request from the cache if it fails
|
||||
req.catch(() => this.requests.delete(message_id));
|
||||
// Return the request
|
||||
return req;
|
||||
}
|
||||
}
|
||||
|
||||
async get(channel_id: string, message_id: string): Promise<MessagePayload> {
|
||||
if (this.cache.has(message_id)) {
|
||||
return await Promise.resolve(this.cache.get(message_id)!);
|
||||
} else {
|
||||
return this.fetch(channel_id, message_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
import { User } from "../types/user";
|
||||
import type { API } from "./api";
|
||||
import { User } from "../../types/user";
|
||||
import type { API } from "../api";
|
||||
import type { Processor } from "../processor";
|
||||
import { ObjectCache } from "./cache";
|
||||
import type { Processor } from "./processor";
|
||||
|
||||
|
||||
export class Users extends ObjectCache<User, User> {
|
||||
constructor (api: API, processor: Processor) {
|
||||
+35
-7
@@ -1,14 +1,14 @@
|
||||
import { API } from './api';
|
||||
import { Gateway } from './gateway';
|
||||
import { Gateway } from './connectors/gateway';
|
||||
import { Processor } from './processor';
|
||||
import { Expectation, Intent, type ClientConfig } from '../types/common';
|
||||
import { Expectation, fromDiscord, 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';
|
||||
import { Guilds } from './caches/guilds';
|
||||
import { Messages } from './caches/messages';
|
||||
import { Users } from './caches/users';
|
||||
import { hydrate, hydrator, type Hydrateable, type Hydrated } from './hydrator';
|
||||
|
||||
export class Client {
|
||||
readonly token: string;
|
||||
@@ -66,6 +66,34 @@ export class Client {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Hydrates a given data object based on the provided expectations.
|
||||
*
|
||||
* @template T - The type of the data object to be hydrated. Must extend `Hydrateable`.
|
||||
* @template K - An array of `Expectation` types that specify what properties should be hydrated.
|
||||
*
|
||||
* @param data - The data object to be hydrated. Can be of type `Context` or `Message`.
|
||||
* @param expectations - An array of expectations that specify what properties should be hydrated.
|
||||
*
|
||||
* @returns A promise that resolves to the hydrated data object.
|
||||
*
|
||||
* @throws Will throw an error if an expectation cannot be resolved.
|
||||
*/
|
||||
hydrate = async <T extends Hydrateable | Hydrated<Hydrateable, Array<Expectation>>, K extends Array<Expectation>>(data: T, expectations: K) => {
|
||||
return hydrate<T, K>(data, expectations, this, this.api);
|
||||
}
|
||||
|
||||
/**
|
||||
* A wrapper function that attempts to hydrate a given data object and returns a type guard function.
|
||||
*
|
||||
* @template T - The type of the data object to be hydrated. Must extend `Hydrateable`.
|
||||
* @template K - An array of `Expectation` types that specify what properties should be hydrated.
|
||||
*
|
||||
* @param data - The data object to be hydrated. Can be of type `Context` or `Message`.
|
||||
* @param expectations - An array of expectations that specify what properties should be hydrated.
|
||||
*
|
||||
* @returns A promise that resolves to a type guard function. The type guard function returns `true` if the data object was successfully hydrated, otherwise `false`.
|
||||
*/
|
||||
hydrator = async<T extends Hydrateable, K extends Expectation[]>(data: T, expectations: K) => {
|
||||
return hydrator<T, K>(data, expectations, this, this.api);
|
||||
}
|
||||
@@ -75,7 +103,7 @@ export class Client {
|
||||
message = new Message().setContent(message);
|
||||
}
|
||||
|
||||
return Message.fromDiscord(DiscordMessage.fromAPIResponse(await this.api.post(`/channels/${channel_id}/messages`, message.toJSON())));
|
||||
return Message[fromDiscord](DiscordMessage.fromAPIResponse(await this.api.post(`/channels/${channel_id}/messages`, message.toJSON())));
|
||||
}
|
||||
|
||||
chatCommands = {
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { WebSocket, type Data } from 'ws';
|
||||
import type { Client } from "./client";
|
||||
import type { Payload } from "../types/common";
|
||||
import { exists, isNil, isObject, log } from "../utils";
|
||||
import type { API } from "./api";
|
||||
import type { Processor } from './processor';
|
||||
import { Context } from '../types/context';
|
||||
import { DiscordMessage, Message } from '../types/message';
|
||||
import { DiscordUser, User } from '../types/user';
|
||||
import type { Client } from "../client";
|
||||
import { fromDiscord, type Payload } from "../../types/common";
|
||||
import { exists, isNil, isObject, log } from "../../utils";
|
||||
import type { API } from "../api";
|
||||
import type { Processor } from '../processor';
|
||||
import { Context } from '../../types/context';
|
||||
import { type DiscordMessage, Message } from '../../types/message';
|
||||
import { DiscordUser, User } from '../../types/user';
|
||||
|
||||
export class Gateway {
|
||||
private socket: WebSocket | null = null;
|
||||
@@ -141,7 +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 message = Message.fromDiscord(DiscordMessage.fromAPIResponse(event_data));
|
||||
const message = Message[fromDiscord](event_data as DiscordMessage);
|
||||
// And then generate the context
|
||||
context = new Context(this.client, this.api, message);
|
||||
}
|
||||
@@ -164,7 +164,7 @@ export class Gateway {
|
||||
return;
|
||||
}
|
||||
// Extract the author
|
||||
const author = User.fromDiscord(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,7 +186,7 @@ export class Gateway {
|
||||
// TODO: Case insensitive config?
|
||||
const command = args.shift()!;
|
||||
// Create a new message object from the payload
|
||||
const message = Message.fromDiscord(DiscordMessage.fromAPIResponse(payload.d));
|
||||
const message = Message[fromDiscord](payload.d as DiscordMessage);
|
||||
// Generate context
|
||||
const context = new Context(this.client, this.api, message);
|
||||
// Check if command exists
|
||||
@@ -7,12 +7,34 @@ import type { Client } from "./client";
|
||||
|
||||
export type GatewayObject = Message;
|
||||
export type Hydrateable = Context | GatewayObject
|
||||
export type Hydrated<T extends Hydrateable, K extends Array<Expectation>> =
|
||||
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;
|
||||
/**
|
||||
* Hydrates a given data object based on the provided expectations.
|
||||
*
|
||||
* @template T - The type of the data object to be hydrated. Must extend `Hydrateable`.
|
||||
* @template K - An array of `Expectation` types that specify what properties should be hydrated.
|
||||
*
|
||||
* @param data - The data object to be hydrated. Can be of type `Context` or `Message`.
|
||||
* @param expectations - An array of expectations that specify what properties should be hydrated.
|
||||
* @param client - The client instance used to fetch additional data required for hydration.
|
||||
* @param api - The API instance used to fetch additional data required for hydration.
|
||||
*
|
||||
* @returns A promise that resolves to the hydrated data object.
|
||||
*
|
||||
* @throws Will throw an error if an expectation cannot be resolved.
|
||||
*/
|
||||
export async function hydrate<T extends Hydrateable | Hydrated<any, any>, K extends Array<Expectation>>(
|
||||
data: T,
|
||||
expectations: K,
|
||||
client: Client,
|
||||
api: API
|
||||
): Promise<T extends Hydrated<infer U, infer H> ? Hydrated<T & U, [...H, ...K]> : Hydrated<T, K>> {
|
||||
// TODO: add clone trait. Make it a requirement for hydrateable objects.
|
||||
// Then clone the object and return the hydrated object.
|
||||
let hydrated: Hydrated<T, K>;
|
||||
|
||||
if (data instanceof Context) {
|
||||
for (const expectation of expectations) {
|
||||
@@ -20,8 +42,7 @@ export async function hydrator<T extends Hydrateable, K extends Array<Expectatio
|
||||
let context = data as unknown as HydratedContext<[Expectation.Guild, ...Expectation[]]>;
|
||||
context.guild = await client.guilds.get(data.guild_id);
|
||||
} else {
|
||||
hydrated = false;
|
||||
break;
|
||||
throw new Error(`Could not resolve expectation: ${expectation}`);
|
||||
}
|
||||
}
|
||||
} else if (data instanceof Message) {
|
||||
@@ -33,13 +54,45 @@ export async function hydrator<T extends Hydrateable, K extends Array<Expectatio
|
||||
let message = data as unknown as HydratedMessage<[Expectation.Guild, ...Expectation[]]>;
|
||||
message.guild = await client.guilds.get(data.guild_id);
|
||||
} else {
|
||||
hydrated = false;
|
||||
break;
|
||||
throw new Error(`Could not resolve expectation: ${expectation}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return function (data: unknown): data is Hydrated<T, K> {
|
||||
return data as unknown as (T extends Hydrated<infer U, infer H> ? Hydrated<T & U, [...H, ...K]> : Hydrated<T, K>);
|
||||
}
|
||||
|
||||
/**
|
||||
* A wrapper function that attempts to hydrate a given data object and returns a type guard function.
|
||||
*
|
||||
* @template T - The type of the data object to be hydrated. Must extend `Hydrateable`.
|
||||
* @template K - An array of `Expectation` types that specify what properties should be hydrated.
|
||||
*
|
||||
* @param data - The data object to be hydrated. Can be of type `Context` or `Message`.
|
||||
* @param expectations - An array of expectations that specify what properties should be hydrated.
|
||||
* @param client - The client instance used to fetch additional data required for hydration.
|
||||
* @param api - The API instance used to fetch additional data required for hydration.
|
||||
*
|
||||
* @returns A promise that resolves to a type guard function. The type guard function returns `true` if the data object was successfully hydrated, otherwise `false`.
|
||||
*/
|
||||
export async function hydrator<T extends Hydrateable | Hydrated<any, any>, K extends Array<Expectation>>(
|
||||
data: T,
|
||||
expectations: K,
|
||||
client: Client,
|
||||
api: API
|
||||
): Promise<(data: unknown) => data is T extends Hydrated<infer U, infer H> ? Hydrated<T & U, [...H, ...K]> : Hydrated<T, K>> {
|
||||
let hydrated = true;
|
||||
|
||||
try {
|
||||
// TODO: When clone is implemented we will receive a clone of the object here
|
||||
// So in hydrator we will need to copy the properties from the clone to the original object
|
||||
await hydrate(data, expectations, client, api);
|
||||
} catch (error) {
|
||||
hydrated = false;
|
||||
}
|
||||
|
||||
// BUG: Resolves to never after hydrations on an already hydrated object
|
||||
return function (data: unknown): data is T extends Hydrated<infer U, infer H> ? Hydrated<T & U, [...H, ...K]> : Hydrated<T, K> {
|
||||
return hydrated;
|
||||
}
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
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, MessagePayload> {
|
||||
constructor (protected client: Client, api: API, processor: Processor) {
|
||||
super(api, processor, 'message', Message, ['MESSAGE_CREATE', 'MESSAGE_UPDATE']);
|
||||
}
|
||||
|
||||
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<MessagePayload> {
|
||||
if (this.cache.has(message_id)) {
|
||||
return await Promise.resolve(this.cache.get(message_id)!);
|
||||
} else {
|
||||
return this.fetch(channel_id, message_id, resolveReference);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { Client } from "./client";
|
||||
import type { Context } from "../types/context";
|
||||
import { HandlerType, type EventPayload, type Payload } from "../types/common";
|
||||
import { HandlerType, type EventPayload } from "../types/common";
|
||||
import { BaseHandler, type Handler } from "../types/hander";
|
||||
import type { API } from "./api";
|
||||
|
||||
|
||||
Reference in New Issue
Block a user