Угловое кеширование параллельных запросов - PullRequest
0 голосов
/ 24 мая 2018

Я определил перехватчик для кэширования ответов API:

    if (req.method == 'GET') {
        // return cached object if exists
        const cachedResponse = this.cache.get(req) || null;
        if (cachedResponse) {
            return Observable.of(cachedResponse);
        }

        // call api and cache result if doesn't exist
        return next.handle(req).do(event => {
            if (event instanceof HttpResponse) {
                this.cache.put(req, event)
            }
        });
    }
    return next.handle(req);

Чего здесь не хватает, так это не обрабатывать запрос, если он находится в состоянии ожидания, а ждать, пока запрос будет готов в кеше, и вернуть его.

Как лучше всего адаптировать эту логику к этой проблеме?

Ответы [ 3 ]

0 голосов
/ 24 мая 2018

Я решил проблему с помощью кеша и очереди с помощью оператора share следующим образом:

if (req.method == 'GET') {

    // return cached object if exists
    const cachedResponse = this.cache.get(req) || null;
    if (cachedResponse) {
        return Observable.of(cachedResponse);
    }

    const pendingResponse = this.queue.get(req) || null;
    if (pendingResponse) {
        return pendingResponse;
    }
    // call api and cache result if doesn't exist
    var obs = next.handle(req).do(event => {
        if (event instanceof HttpResponse) {
            this.cache.put(req, event)
            this.queue.clear(req.urlWithParams)
        }
    }).share();
    this.queue.put(req, obs)
    return obs
}
return next.handle(req);
0 голосов
/ 30 августа 2018

Можно попытаться использовать shareReplay, если запрос в состоянии ожидания - тот же запрос будет повторно использован, если он выполнен - ​​будет отправлено последнее значение.

if (req.method == 'GET') {

  if (!this.cache.get(req)) {
      const cached = next.handle(req).shareReplay();
      this.cache.put(req, cached);
  }

  return this.cache.get(req);
}
return next.handle(req);
0 голосов
/ 24 мая 2018

Вы имеете в виду в своей функции do (), где будут некоторые проблемы для параллельных запросов?Мол, 2 запроса делают с одним и тем же URL, тогда оба запроса будут отправлены на сервер и помещены в кэш.

Как насчет этого?Не для того, чтобы поместить HttpResponse в кеш, а чтобы поместить этот наблюдаемый объект.как это:

    if (req.method == 'GET') {
    // return cached object if exists
    const cachedResponse = this.cache.get(req) || null;
    if (cachedResponse) {
        return cachedResponse); // it is Observable, even same req in the sam,e time, the second will get a Observable data.
    }

    // call api and cache result if doesn't exist
    const result = next.handle(req);
    this.cache.put(req, result)
    result.do(event => {
        if (event !instanceof HttpResponse) {
            this.cache.remove(req) // if it is error, maybe remove?
        }
    return result;
    });
}
return next.handle(req);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...