SubscribeMany.ts 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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 SubscribeMany extends Job {
  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 (!Array.isArray(this._payload.channels))
  13. throw new Error("Channels must be an array");
  14. this._payload.channels.forEach((channel: unknown) => {
  15. if (typeof channel !== "string")
  16. throw new Error("Channel must be a string");
  17. });
  18. }
  19. protected override async _authorize() {
  20. const permissions = this._payload.channels.map((channel: string) => {
  21. const { moduleName, modelName, event, modelId } =
  22. channelRegex.exec(channel)?.groups ?? {};
  23. let permission = `event.${channel}`;
  24. if (
  25. moduleName === "model" &&
  26. modelName &&
  27. (modelId || event === "created")
  28. ) {
  29. if (event === "created")
  30. permission = `event.model.${modelName}.created`;
  31. else permission = `data.${modelName}.findById.${modelId}`;
  32. }
  33. return permission;
  34. });
  35. await this._context.assertPermissions(permissions);
  36. }
  37. protected async _execute() {
  38. const socketId = this._context.getSocketId();
  39. if (!socketId) throw new Error("No socketId specified");
  40. await EventsModule.subscribeManySocket(
  41. this._payload.channels,
  42. socketId
  43. );
  44. }
  45. }