Subscribe.ts 1.3 KB

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