SubscribeMany.ts 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import { forEachIn } from "@common/utils/forEachIn";
  2. import Job, { JobOptions } from "@/Job";
  3. import EventsModule from "@/modules/EventsModule";
  4. import Event from "../Event";
  5. export default class SubscribeMany extends Job {
  6. protected static _hasPermission = true;
  7. public constructor(payload?: unknown, options?: JobOptions) {
  8. super(EventsModule, payload, options);
  9. }
  10. protected override async _validate() {
  11. if (typeof this._payload !== "object" || this._payload === null)
  12. throw new Error("Payload must be an object");
  13. if (!Array.isArray(this._payload.channels))
  14. throw new Error("Channels must be an array");
  15. this._payload.channels.forEach((channel: unknown) => {
  16. if (typeof channel !== "string")
  17. throw new Error("Channel must be a string");
  18. });
  19. }
  20. protected override async _authorize() {
  21. await forEachIn(this._payload.channels, async channel => {
  22. const { path, scope } = Event.parseKey(channel);
  23. const EventClass = EventsModule.getEvent(path);
  24. const hasPermission = await EventClass.hasPermission(
  25. await this._context.getUser().catch(() => null),
  26. scope
  27. );
  28. if (!hasPermission)
  29. throw new Error(
  30. `Insufficient permissions for event ${channel}`
  31. );
  32. });
  33. }
  34. protected async _execute() {
  35. const socketId = this._context.getSocketId();
  36. if (!socketId) throw new Error("No socketId specified");
  37. await EventsModule.subscribeManySocket(
  38. this._payload.channels,
  39. socketId
  40. );
  41. }
  42. }