|
| 1 | +import type { |
| 2 | + GetChannelMessagesParams, |
| 3 | + MessagePayload, |
| 4 | +} from "../../../types/mod.ts"; |
| 5 | +import type { Client } from "../client/mod.ts"; |
| 6 | +import { Message } from "../structures/messages/mod.ts"; |
| 7 | +import { BaseManager } from "./base.ts"; |
| 8 | + |
| 9 | +export class MessagesManager extends BaseManager<MessagePayload, Message> { |
| 10 | + constructor(client: Client) { |
| 11 | + super(client); |
| 12 | + } |
| 13 | + |
| 14 | + _fill(messages: MessagePayload[]) { |
| 15 | + for (const message of messages) { |
| 16 | + this.set(message.id!, message); |
| 17 | + } |
| 18 | + } |
| 19 | + |
| 20 | + async _fetch( |
| 21 | + channelID: string, |
| 22 | + id: string, |
| 23 | + ): Promise<MessagePayload | undefined> { |
| 24 | + try { |
| 25 | + const resp: MessagePayload | undefined = await this.client.rest.get( |
| 26 | + `/channels/${channelID}/messages/${id}`, |
| 27 | + ); |
| 28 | + if (!resp) return; |
| 29 | + this.set(id, resp); |
| 30 | + return resp; |
| 31 | + } catch (_err) { |
| 32 | + return; |
| 33 | + } |
| 34 | + } |
| 35 | + async _fetchBulk( |
| 36 | + channelID: string, |
| 37 | + options: GetChannelMessagesParams, |
| 38 | + ): Promise<MessagePayload[] | undefined> { |
| 39 | + try { |
| 40 | + const query: Record<string, string> = { |
| 41 | + ...options, |
| 42 | + limit: "", |
| 43 | + }; |
| 44 | + if (options.limit) { |
| 45 | + if (options.limit > 100 || options.limit < 1) { |
| 46 | + throw new Error("Limit must be in range 1-100"); |
| 47 | + } |
| 48 | + query.limit = options.limit.toString(); |
| 49 | + } else { |
| 50 | + delete query.limit; |
| 51 | + } |
| 52 | + const resp: MessagePayload[] | undefined = await this.client.rest.get( |
| 53 | + `/channels/${channelID}/messages`, |
| 54 | + { |
| 55 | + query, |
| 56 | + }, |
| 57 | + ); |
| 58 | + if (!resp) return; |
| 59 | + return resp.map((message) => { |
| 60 | + this.set(message.id!, message); |
| 61 | + return message; |
| 62 | + }); |
| 63 | + } catch (_err) { |
| 64 | + return; |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + get( |
| 69 | + id: string, |
| 70 | + ) { |
| 71 | + const cached = this._get(id); |
| 72 | + if (!cached) return; |
| 73 | + return new Message(this.client, cached); |
| 74 | + } |
| 75 | + async fetch( |
| 76 | + channelID: string, |
| 77 | + id: string, |
| 78 | + ) { |
| 79 | + try { |
| 80 | + const payload = await this._fetch(channelID, id); |
| 81 | + if (!payload) return; |
| 82 | + return new Message(this.client, payload); |
| 83 | + } catch (_err) { |
| 84 | + return; |
| 85 | + } |
| 86 | + } |
| 87 | +} |
0 commit comments