Subscribe.ts 1.2 KB

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