Subscribe.ts 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import Job, { JobOptions } from "@/Job";
  2. import EventsModule from "@/modules/EventsModule";
  3. const channelRegex =
  4. /^(?<moduleName>[a-z]+)\.(?<modelName>[A-z]+)\.(?<event>[A-z]+):?(?<modelId>[A-z0-9]+)?$/;
  5. export default class Subscribe 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 (typeof this._payload.channel !== "string")
  14. throw new Error("Channel must be a string");
  15. }
  16. protected override async _authorize() {
  17. const { channel } = this._payload;
  18. const { moduleName, modelName, event, modelId } =
  19. channelRegex.exec(channel)?.groups ?? {};
  20. let permission = `event.${channel}`;
  21. if (
  22. moduleName === "data" &&
  23. modelName &&
  24. (modelId || event === "created")
  25. ) {
  26. if (event === "created")
  27. permission = `event.model.${modelName}.created`;
  28. else permission = `data.${modelName}.findById.${modelId}`;
  29. }
  30. await this._context.assertPermission(permission);
  31. }
  32. protected async _execute() {
  33. const socketId = this._context.getSocketId();
  34. if (!socketId) throw new Error("No socketId specified");
  35. await EventsModule.subscribeSocket(this._payload.channel, socketId);
  36. }
  37. }