目录

Customizing a Cache Interceptor

The cache interceptor customization function is supported since version 6.0.0(20).

Remote Communication Kit provides the interceptor capability, allowing you to customize cache interceptors based on service requirements. Through the interceptor mechanism, you can intervene in the cache handling process, including preprocessing cached data and customizing loading logic, to precisely align with the diverse caching requirements of complex service scenarios, thereby enhancing system flexibility and scalability.

Constraints

The cache interceptor customization function supports phones, 2-in-1 devices, tablets, wearables, and TVs.

Using a Custom Cache Interceptor

  1. Import the required modules.

    import { rcp } from '@kit.RemoteCommunicationKit';
  2. Implement a custom cache interceptor.

    class BlindCacheInterceptor implements rcp.Interceptor {
      private readonly cache: rcp.ResponseCache;
      constructor(cache: rcp.ResponseCache) {
        this.cache = cache;
      }
      async intercept(context: rcp.RequestContext, next: rcp.RequestHandler): Promise<rcp.Response> {
        const key: rcp.ResponseCacheKey = {
          url: context.request.url,
          method: context.request.method,
        };
        const responseInCache = await this.cache.get(key);
        if (responseInCache) {
          return rcp.createResponse(context.request, responseInCache.response, new Date());
        }
        const networkResponse = await next.handle(context);
        await this.cache.set(key, rcp.createCachedResponse(networkResponse));
        return networkResponse;
      }
    }
  3. Create a ResponseCache instance. In the following code, pathToFolder indicates the file path for storing HTTP response cache records. Replace /path/dir with the sandbox path for storing HTTP response cache records.

    const responseCache = new rcp.ResponseCache({
      persistent: {
        kind: 'file-system',
        pathToFolder: '/data/storage/el2/base/entry/temp/CustomCache' // Select an appropriate path as needed.
      }
    });
  4. Creates a session and add the Interceptors parameter.

    const session: rcp.Session = rcp.createSession({
      interceptors : [new BlindCacheInterceptor(responseCache)]
    });
  5. Initiate the first request. Replace https://www.example.com with the actual URL that supports the HTTP caching protocol. This request retrieves data from the server. You can check the cache status to determine whether the retrieved data is successfully cached. In this example, the cache record count changes to 1.

    // The URL to request is only an example. Modify it as needed.
    const responseA = await session.put('https://www.example.com');
    console.info(`Request succeeded, message is ${JSON.stringify(responseA)}`);
    let cacheState = await responseCache.getState();
    console.info(`The current number of cache entries is: ${cacheState.count}`);
  6. Initiate the second request. Replace https://www.example.com with the actual URL that supports the HTTP caching protocol. This request retrieves data from the cache based on the custom interceptor logic. At this point, you can check the cache status, and you will find that the cache hit count changes to 1.

    // The URL to request is only an example. Modify it as needed.
    const responseB = await session.put('https://www.example.com');
    console.info(`Request succeeded, message is ${JSON.stringify(responseB)}`);
    cacheState = await responseCache.getState();
    console.info(`The current cache hit count is: ${cacheState.hitCount}`);