SearcherAboutDataModel.ets 2.32 KB

import { Logger, ResourcesUtils } from 'wdKit';
import { ResponseDTO, WDHttp } from 'wdNetwork';
import HashMap from '@ohos.util.HashMap';
import { HttpUrlUtils } from '../network/HttpUrlUtils';
const TAG = "SearcherAboutDataModel"

/**
 * 我的页面 所有数据 获取封装类
 */
class SearcherAboutDataModel{
  private static instance: SearcherAboutDataModel;

  private constructor() { }

  /**
   * 单例模式
   * @returns
   */
  public static getInstance(): SearcherAboutDataModel {
    if (!SearcherAboutDataModel.instance) {
      SearcherAboutDataModel.instance = new SearcherAboutDataModel();
    }
    return SearcherAboutDataModel.instance;
  }

  /**
   * 首页 搜索提示滚动内容
   */
  getSearchHintData(context: Context): Promise<string[]> {
    return new Promise<string[]>((success, error) => {
      Logger.info(TAG, `getSearchHintData start`);
      this.fetchSearchHintData().then((navResDTO: ResponseDTO<string[]>) => {
        if (!navResDTO || navResDTO.code != 0) {
          success(this.getSearchHintDataLocal(context))
          return
        }
        Logger.info(TAG, "getSearchHintData then,SearchHintDataResDTO.timeStamp:" + navResDTO.timestamp);
        let navigationBean = navResDTO.data as string[]
        success(navigationBean);
      }).catch((err: Error) => {
        Logger.error(TAG, `fetchSearchHintData catch, error.name : ${err.name},  error.message:${err.message}`);
        success(this.getSearchHintDataLocal(context))
      })
    })
  }

  fetchSearchHintData() {
    let url = HttpUrlUtils.getSearchHintDataUrl()
    let headers: HashMap<string, string> = HttpUrlUtils.getYcgCommonHeaders();
    return WDHttp.get<ResponseDTO<string[]>>(url, headers)
  };

  async getSearchHintDataLocal(context: Context): Promise<string[]> {
    Logger.info(TAG, `getSearchHintDataLocal start`);
    let compRes: ResponseDTO<string[]> | null = await ResourcesUtils.getResourcesJson<ResponseDTO<string[]>>('search_hint_data.json' ,context);
    if (!compRes || !compRes.data) {
      Logger.info(TAG, `getSearchHintDataLocal compRes  is empty`);
      return []
    }
    Logger.info(TAG, `getSearchHintDataLocal compRes : ${JSON.stringify(compRes)}`);
    return compRes.data
  }



}

const searcherAboutDataModel = SearcherAboutDataModel.getInstance()
export default searcherAboutDataModel as SearcherAboutDataModel