check-communicable.ts 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import axios, { AxiosError } from 'axios';
  2. import { WebClient } from '@slack/web-api';
  3. import { generateWebClient } from './webclient-factory';
  4. import { ConnectionStatus } from '../interfaces/connection-status';
  5. /**
  6. * Check whether the HTTP server responds or not.
  7. *
  8. * @param serverUri Server URI to connect
  9. * @returns AxiosError when error is occured
  10. */
  11. export const connectToHttpServer = async(serverUri: string): Promise<void|AxiosError> => {
  12. try {
  13. await axios.get(serverUri, { maxRedirects: 0, timeout: 3000 });
  14. }
  15. catch (err) {
  16. return err as AxiosError;
  17. }
  18. };
  19. /**
  20. * Check whether the Slack API server responds or not.
  21. *
  22. * @returns AxiosError when error is occured
  23. */
  24. export const connectToSlackApiServer = async(): Promise<void|AxiosError> => {
  25. return connectToHttpServer('https://slack.com/api/');
  26. };
  27. /**
  28. * Test Slack API
  29. * @param client
  30. */
  31. const testSlackApiServer = async(client: WebClient): Promise<void> => {
  32. const result = await client.api.test();
  33. if (!result.ok) {
  34. throw new Error(result.error);
  35. }
  36. };
  37. /**
  38. * Retrieve Slack workspace name
  39. * @param client
  40. */
  41. const retrieveWorkspaceName = async(client: WebClient): Promise<string> => {
  42. const result = await client.team.info();
  43. if (!result.ok) {
  44. throw new Error(result.error);
  45. }
  46. return (result as any).team?.name;
  47. };
  48. /**
  49. * Get token string to ConnectionStatus map
  50. * @param tokens Array of bot OAuth token
  51. * @returns
  52. */
  53. export const getConnectionStatuses = async(tokens: string[]): Promise<{[key: string]: ConnectionStatus}> => {
  54. const map = tokens
  55. .reduce<Promise<Map<string, ConnectionStatus>>>(
  56. async(acc, token) => {
  57. const client = generateWebClient(token);
  58. const status: ConnectionStatus = {};
  59. try {
  60. // try to connect
  61. await testSlackApiServer(client);
  62. // retrieve workspace name
  63. status.workspaceName = await retrieveWorkspaceName(client);
  64. }
  65. catch (err) {
  66. status.error = err;
  67. }
  68. (await acc).set(token, status);
  69. return acc;
  70. },
  71. // define initial accumulator
  72. Promise.resolve(new Map<string, ConnectionStatus>()),
  73. );
  74. // convert to object
  75. return Object.fromEntries(await map);
  76. };