convertVoiceToText.ts 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import {
  2. IMessageModel,
  3. TUIChatService,
  4. TUIStore,
  5. } from '@tencentcloud/chat-uikit-engine';
  6. import { IChatResponese } from '../../../interface';
  7. class Convertor {
  8. public isUseCache = true;
  9. private convertCache = new Map<string, string>();
  10. private static instance: Convertor | undefined = undefined;
  11. private constructor() {}
  12. static getInstance() {
  13. if (!Convertor.instance) {
  14. Convertor.instance = new Convertor();
  15. }
  16. return Convertor.instance;
  17. }
  18. async get(message: IMessageModel): Promise<string> {
  19. // step1: check in cache if convert result exist
  20. if (this.isUseCache) {
  21. const cache = this.convertCache.get(message.ID);
  22. if (cache !== undefined) {
  23. return cache;
  24. }
  25. }
  26. // step2: get message model with prototype methods
  27. const currentMessage: IMessageModel = TUIStore.getMessageModel(message.ID);
  28. if (!currentMessage) {
  29. return Promise.reject('message not found');
  30. }
  31. // step3: get response from api
  32. const response: IChatResponese<{ result: string }> = await TUIChatService.convertVoiceToText({
  33. message: currentMessage,
  34. });
  35. let { data: { result } = {} } = response;
  36. if (result) {
  37. this.convertCache.set(currentMessage.ID, result);
  38. } else {
  39. result = '';
  40. }
  41. return result;
  42. }
  43. clear() {
  44. this.convertCache.clear();
  45. }
  46. disableCache() {
  47. this.isUseCache = false;
  48. }
  49. enableCache() {
  50. this.isUseCache = true;
  51. }
  52. }
  53. export const convertor = Convertor.getInstance();