InstallerService.ts 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. installationStore: {
  28. // upsert
  29. storeInstallation: async(slackInstallation: SlackInstallation<'v1' | 'v2', boolean>) => {
  30. const teamIdOrEnterpriseId = slackInstallation.team?.id || slackInstallation.enterprise?.id;
  31. if (teamIdOrEnterpriseId == null) {
  32. throw new Error('teamId or enterpriseId is required.');
  33. }
  34. const existedInstallation = await repository.findByTeamIdOrEnterpriseId(teamIdOrEnterpriseId);
  35. if (existedInstallation != null) {
  36. existedInstallation.setData(slackInstallation);
  37. await repository.save(existedInstallation);
  38. return;
  39. }
  40. const installation = new Installation();
  41. installation.setData(slackInstallation);
  42. await repository.save(installation);
  43. return;
  44. },
  45. fetchInstallation: async(installQuery: InstallationQuery<boolean>) => {
  46. const id = installQuery.enterpriseId || installQuery.teamId;
  47. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
  48. const installation = await repository.findByTeamIdOrEnterpriseId(id!);
  49. if (installation == null) {
  50. throw new Error('Failed fetching installation');
  51. }
  52. return installation.data;
  53. },
  54. },
  55. });
  56. }
  57. }