Subscribe.ts 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. import Job, { JobOptions } from "@/Job";
  2. import EventsModule from "@/modules/EventsModule";
  3. import Event from "@/modules/EventsModule/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. // Channel could be data.news.created, or something like data.news.updated:SOME_OBJECT_ID
  17. const { channel } = this._payload;
  18. // Path can be for example data.news.created. Scope will be anything after ":", but isn't required, so could be undefined
  19. const { path, scope } = Event.parseKey(channel);
  20. const permission = scope ? `event.${path}:${scope}` : `event.${path}`;
  21. await EventsModule.assertPermission(permission);
  22. }
  23. protected async _execute() {
  24. const socketId = this._context.getSocketId();
  25. if (!socketId) throw new Error("No socketId specified");
  26. await EventsModule.subscribeSocket(this._payload.channel, socketId);
  27. }
  28. }