grammy-guard
Version:
Guard middlewares for grammY
74 lines (73 loc) • 2.28 kB
JavaScript
const getOrThrow = (registry, reason) => {
if (!registry.has(reason)) {
throw new Error(`Request with reason "${reason.toString()}" does not exist`);
}
return registry.get(reason);
};
const addOrThrow = (registry, reason, requestId) => {
if (registry.has(reason)) {
throw new Error(`Request with reason "${reason.toString()}" already exists`);
}
for (const [existingReason, existingRequestId,] of registry.entries()) {
if (existingRequestId === requestId) {
throw new Error(`Request with ID "${requestId}" already exists (${String(existingReason)})`);
}
}
registry.set(reason, requestId);
};
class UserRequestRegistry {
constructor() {
Object.defineProperty(this, "registry", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
this.registry = new Map();
}
getId(reason) {
return getOrThrow(this.registry, reason);
}
add(reason, requestId) {
addOrThrow(this.registry, reason, requestId);
return this;
}
filter(reason) {
if (!this.registry.has(reason)) {
throw new Error(`Request with reason "${String(reason)}" does not exist`);
}
return (ctx) => ctx.msg?.user_shared?.request_id ===
this.registry.get(reason);
}
}
class ChatRequestRegistry {
constructor() {
Object.defineProperty(this, "registry", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
this.registry = new Map();
}
getId(reason) {
return getOrThrow(this.registry, reason);
}
add(reason, requestId) {
addOrThrow(this.registry, reason, requestId);
return this;
}
filter(reason) {
if (!this.registry.has(reason)) {
throw new Error(`Request with reason "${String(reason)}" does not exist`);
}
return (ctx) => ctx.msg?.chat_shared?.request_id ===
this.registry.get(reason);
}
}
export function createUserRequestRegistry() {
return new UserRequestRegistry();
}
export function createChatRequestRegistry() {
return new ChatRequestRegistry();
}