Каков наилучший способ обработки кэша памяти для тех же данных, но с другим шаблоном запроса (обещания) в угловом формате? - PullRequest
0 голосов
/ 24 мая 2019

Я предложил следующее решение для кэширования http-запроса с несколькими и одним обещанием, но я думаю, что его можно улучшить. Нужен более эффективный способ обработки кеша с несколькими шаблонами запросов. Нужно избавиться от cachedRequestPattern Array.

  private cachedData: StringMap<Promise<Post>> = {};
  private cachedRequestPattern: Array<string> = [];

public getPost(id: string): Promise<Post> {
    try {
      if (!this.cachedData[id]) {
        this.cachedData: [id] = this.httpClient
          .get<Post>(`${this.restUrl}/someurl/${id} `)
          .toPromise();
      }
      return this.cachedData[id];
    } catch (error) {
      console.log(error)
    }
  }


  public getMultiplePosts(ids: Array<string>): Promise<Array<Post>> {
    return new Promise<Array<Post>>(async (resolve, reject) => {
      ids = ids.filter((id, index) => ids.indexOf(id) === index);
      const postIds: string = this.getPostsIdsThatAreNotCached(uris).join(','); // this basically filters data that are not cached
      if (psotIds.length && this.cachedRequestPattern.indexOf(postIds) <= -1) {
        this.cachedRequestPattern.push(postIds);
        try {
          await this.httpClient
            .get<Array<Post>>('someurl'), {
              params: {
                ids: ids
              }
            })
            .pipe(
              tap((result: Array<Post>) => {
                result.forEach((post) => {
                  this.cachedData[post.id] = Promise.resolve(post);
                });
              })
            )
            .toPromise();
          resolve(Promise.all(this.getPostAlreadyCachedData(ids)));
        } catch (error) {
          reject(error);
        }
        return;
      }
      resolve(Promise.all(this.getPostAlreadyCachedData(ids)));
    });
  }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...