Subscribe.ts 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import Job, { JobOptions } from "@/Job";
  2. import EventsModule from "@/modules/EventsModule";
  3. export default class Subscribe extends Job {
  4. public constructor(payload?: unknown, options?: JobOptions) {
  5. super(EventsModule, payload, options);
  6. }
  7. protected override async _validate() {
  8. if (typeof this._payload !== "object" || this._payload === null)
  9. throw new Error("Payload must be an object");
  10. if (typeof this._payload.channel !== "string")
  11. throw new Error("Channel must be a string");
  12. }
  13. protected override async _authorize() {
  14. const [, moduleName, modelName, event, modelId] =
  15. /^([a-z]+)\.([a-z]+)\.([A-z]+)\.?([A-z0-9]+)?$/.exec(
  16. this._payload.channel
  17. ) ?? [];
  18. let permission = `event.${this._payload.channel}`;
  19. if (
  20. moduleName === "model" &&
  21. modelName &&
  22. (modelId || event === "created")
  23. ) {
  24. if (event === "created")
  25. permission = `event.model.${modelName}.created`;
  26. else permission = `data.${modelName}.findById.${modelId}`;
  27. }
  28. await this._context.assertPermission(permission);
  29. }
  30. protected async _execute() {
  31. const socketId = this._context.getSocketId();
  32. if (!socketId) throw new Error("No socketId specified");
  33. await EventsModule.subscribeSocket(this._payload.channel, socketId);
  34. }
  35. }