session-service.ts 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. import type { Request } from "express";
  2. import { TokenPayload } from "#modules/users/auth/types/token-playload-type.js";
  3. import { ApiError } from "#exceptions/api-error.js";
  4. import { z } from "zod";
  5. import { selPool } from "#db/db.js";
  6. import { sql } from "slonik";
  7. import { DbSchema } from "#db/db-schema.js";
  8. class SessionService {
  9. // getUserFromCookies(cookies: {
  10. // userData: {
  11. // username: string;
  12. // userId: string;
  13. // };
  14. // }) {
  15. // const userData = cookies.userData;
  16. // if (!userData) {
  17. // throw ApiError.UnauthorizedError();
  18. // }
  19. // return userData;
  20. // }
  21. //
  22. getUserFromReq(req: Request) {
  23. const userData = TokenPayload.safeParse(req.user);
  24. if (!userData.success) {
  25. throw ApiError.UnauthorizedError();
  26. }
  27. return userData.data;
  28. }
  29. getEventFromCookies(cookies: {
  30. userData: {
  31. username: string;
  32. userId: string;
  33. };
  34. }) {
  35. const userData = cookies.userData;
  36. if (!userData) {
  37. throw ApiError.UnauthorizedError();
  38. }
  39. return userData;
  40. }
  41. // TODO: Добавить ограничение в БД что только один ивент может быть актуальным
  42. async getCurrentEventFromReq(req: Request) {
  43. const eventCodeSafe = z.string().safeParse(req.eventCode);
  44. if (!eventCodeSafe.success) {
  45. throw ApiError.UnauthorizedError();
  46. }
  47. const eventData = await selPool.maybeOne(
  48. sql.type(
  49. z.object({
  50. eventInstId: DbSchema.ev.eventInst.eventInstId,
  51. eventId: DbSchema.ev.eventInst.eventId,
  52. code: DbSchema.ev.events.code,
  53. eventTypeCode: DbSchema.ev.eventTypes.code,
  54. privateName: DbSchema.ev.eventInst.privateName,
  55. publicName: DbSchema.ev.eventInst.publicName,
  56. timezone: DbSchema.ev.eventInst.timezone,
  57. }),
  58. )`
  59. select
  60. ei.event_inst_id as "eventInstId",
  61. ei.event_id as "eventId",
  62. e.code as "code",
  63. et.code as "eventTypeCode",
  64. ei.private_name as "privateName",
  65. ei.public_name as "publicName",
  66. ei.timezone as "timezone"
  67. from
  68. ev.events e
  69. join ev.event_inst ei on
  70. e.event_id = ei.event_id
  71. and ei.is_current = true
  72. join ev.event_types et on
  73. et.event_type_id = e.event_type_id
  74. where
  75. e.code = ${eventCodeSafe.data}
  76. `,
  77. );
  78. if (!eventData) {
  79. throw ApiError.BadRequest("noEvent", "Ивент не найден");
  80. }
  81. return eventData;
  82. }
  83. }
  84. export default new SessionService();