HarmonyOS rcp.createSession全局封装demo?

如题:HarmonyOS rcp.createSession全局封装demo?

阅读 586
1 个回答

建议将rcp相关配置和方法封装进一个class中,使用时直接new一个实例对象,并调用其中相关的方法。

class ResponseCache {
  private readonly cache: Record<string, rcp.Response> = {};
  getResponse(url: string): rcp.Response {
    return this.cache[url];
  }
  setResponse(url: string, response: rcp.Response): void {
    this.cache[url] = response;
  }
}
class ResponseCachingInterceptor implements rcp.Interceptor {
  private readonly cache: ResponseCache;
  constructor(cache: ResponseCache) {
    this.cache = cache;
  }
  async intercept(context: rcp.RequestContext, next: rcp.RequestHandler): Promise<rcp.Response> {
    const url = context.request.url.href;
    const responseFromCache = this.cache.getResponse(url);
    if (responseFromCache) {
      return Promise.resolve(responseFromCache);
    }
    const promise = next.handle(context);
    promise.then((resp) => {
      resp.statusCode;
      this.cache.setResponse(url, resp);
    });
    return promise;
  }
}
class RcpClass {
  cache:ResponseCache  = new ResponseCache();
  session = rcp.createSession({
    interceptors: [new ResponseCachingInterceptor(this.cache)]
  });
  url?: string
  content?: rcp.RequestContent
  constructor(url:string,content: rcp.RequestContent) {
    this.url = url;
    this.content = content
  }
  post(){
    this.session.post(this.url, this.content).then((response) => {
      console.info(`Response succeeded: ${response}`);
      return
    }).catch((err: BusinessError) => {
      console.error(`Err: Code is ${err.code}, message is ${err.message}`);
      return
    });
  }
  // 继续封装其他方法 get、fetch、put等
}

也可以参考一下文档中的testInterceptor方法,直接封装成函数(需要自己添加url等参数)。https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/remote-communication-interceptor-V5

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进