respond-util-factory.ts 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import axios from 'axios';
  2. import urljoin from 'url-join';
  3. import { RespondBodyForResponseUrl } from '../interfaces/response-url';
  4. import { IRespondUtil } from '../interfaces/respond-util';
  5. type AxiosOptions = {
  6. headers?: {
  7. [header:string]: string,
  8. }
  9. }
  10. function getResponseUrlForProxy(proxyUri: string, responseUrl: string): string {
  11. return urljoin(proxyUri, `/g2s/respond?response_url=${responseUrl}`);
  12. }
  13. function getUrl(responseUrl: string, proxyUri: string | null): string {
  14. return proxyUri == null ? responseUrl : getResponseUrlForProxy(proxyUri, responseUrl);
  15. }
  16. export class RespondUtil implements IRespondUtil {
  17. url!: string;
  18. options!: AxiosOptions;
  19. constructor(responseUrl: string, proxyUri: string | null, appSiteUrl: string) {
  20. this.url = getUrl(responseUrl, proxyUri);
  21. this.options = {
  22. headers: {
  23. 'x-growi-app-site-url': appSiteUrl,
  24. },
  25. };
  26. }
  27. async respond(body: RespondBodyForResponseUrl): Promise<void> {
  28. return axios.post(this.url, {
  29. replace_original: false,
  30. text: body.text,
  31. blocks: body.blocks,
  32. }, this.options);
  33. }
  34. async respondInChannel(body: RespondBodyForResponseUrl): Promise<void> {
  35. return axios.post(this.url, {
  36. response_type: 'in_channel',
  37. replace_original: false,
  38. text: body.text,
  39. blocks: body.blocks,
  40. }, this.options);
  41. }
  42. async replaceOriginal(body: RespondBodyForResponseUrl): Promise<void> {
  43. return axios.post(this.url, {
  44. replace_original: true,
  45. text: body.text,
  46. blocks: body.blocks,
  47. }, this.options);
  48. }
  49. async deleteOriginal(): Promise<void> {
  50. return axios.post(this.url, {
  51. delete_original: true,
  52. }, this.options);
  53. }
  54. }
  55. export function generateRespondUtil(responseUrl: string, proxyUri: string | null, appSiteUrl: string): RespondUtil {
  56. return new RespondUtil(responseUrl, proxyUri, appSiteUrl);
  57. }