2
0

InstallerService.ts 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import {
  2. Installation as SlackInstallation, InstallationQuery, InstallProvider,
  3. } from '@slack/oauth';
  4. import { Inject, Service } from '@tsed/di';
  5. import { Installation } from '~/entities/installation';
  6. import { InstallationRepository } from '~/repositories/installation';
  7. @Service()
  8. export class InstallerService {
  9. installer: InstallProvider;
  10. @Inject()
  11. private readonly repository: InstallationRepository;
  12. $onInit(): Promise<any> | void {
  13. const clientId = process.env.SLACK_CLIENT_ID;
  14. const clientSecret = process.env.SLACK_CLIENT_SECRET;
  15. const stateSecret = process.env.SLACK_INSTALLPROVIDER_STATE_SECRET;
  16. if (clientId === undefined) {
  17. throw new Error('The environment variable \'SLACK_CLIENT_ID\' must be defined.');
  18. }
  19. if (clientSecret === undefined) {
  20. throw new Error('The environment variable \'SLACK_CLIENT_SECRET\' must be defined.');
  21. }
  22. const { repository } = this;
  23. this.installer = new InstallProvider({
  24. clientId,
  25. clientSecret,
  26. stateSecret,
  27. legacyStateVerification: true,
  28. installationStore: {
  29. // upsert
  30. storeInstallation: async(slackInstallation: SlackInstallation<'v1' | 'v2', boolean>) => {
  31. const teamIdOrEnterpriseId = slackInstallation.team?.id || slackInstallation.enterprise?.id;
  32. if (teamIdOrEnterpriseId == null) {
  33. throw new Error('teamId or enterpriseId is required.');
  34. }
  35. const existedInstallation = await repository.findByTeamIdOrEnterpriseId(teamIdOrEnterpriseId);
  36. if (existedInstallation != null) {
  37. existedInstallation.setData(slackInstallation);
  38. await repository.save(existedInstallation);
  39. return;
  40. }
  41. const installation = new Installation();
  42. installation.setData(slackInstallation);
  43. await repository.save(installation);
  44. return;
  45. },
  46. fetchInstallation: async(installQuery: InstallationQuery<boolean>) => {
  47. const id = installQuery.enterpriseId || installQuery.teamId;
  48. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
  49. const installation = await repository.findByTeamIdOrEnterpriseId(id!);
  50. if (installation == null) {
  51. throw new Error('Failed fetching installation');
  52. }
  53. return installation.data;
  54. },
  55. },
  56. });
  57. }
  58. }