UNPKG

grammy-guard

Version:
55 lines (54 loc) 1.9 kB
import { createCallbackData } from "callback-data"; class CallbackDataRegistry { constructor() { Object.defineProperty(this, "registry", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.registry = new Map(); } add(id, schema) { if (this.registry.has(id)) { throw new Error(`Callback data with ID "${id}" already exists`); } this.registry.set(id, createCallbackData(id, schema)); return this; } create(id, data) { if (!this.registry.has(id.toString())) { throw new Error(`Callback data with ID "${id.toString()}" does not exist`); } return this.registry.get(id.toString()).pack(data); } parse(id, packedData) { if (!this.registry.has(id.toString())) { throw new Error(`Callback data with ID "${id.toString()}" does not exist`); } return this.registry.get(id.toString()).unpack(packedData); } regex(id, clause) { if (!this.registry.has(id.toString())) { throw new Error(`Callback data with ID "${id.toString()}" does not exist`); } return this.registry.get(id.toString()).filter(clause); } filter(id, clause) { if (!this.registry.has(id.toString())) { throw new Error(`Callback data with ID "${id.toString()}" does not exist`); } return (ctx) => { if (ctx.hasCallbackQuery(this.regex(id, clause))) { // @ts-expect-error declare property dynamic ctx.callbackData = this.registry.get(id.toString()) .unpack(ctx.callbackQuery.data); return true; } return false; }; } } export function createCallbackDataRegistry() { return new CallbackDataRegistry(); }