2017-01-21 5 views
1

を使用するodata standardを実装しようとしています。私はPATCHリクエストで積み重ねています。各PATCHリクエストでは、ヘッダIf-None-Matchにetagを送信する必要があります。それに応答して、HTTPステータス200は変更が適用されたことを意味し、ステータス412は基底のデータが変更されたことを意味し、再度フェッチして、サーバーからのデータとアプリケーションからの現在のデータをマージする必要があります。マージはこの質問の対象外です。なしのRx-だけにこのコードをtranformする方法、:Angular2のETag実装

export const HEADER_ETAG_MATCH = 'If-None-Match'; 
export const ODATA_ETAG_PROPERTY = '@odata.etag'; 
export interface CacheRecordStructure { 
    etag: string; 
    response: Response; 
} 
export class CachingService { 
    cache: { [key: string]: CacheRecordStructure } = {}; 
    constructor(private http: Http) { } 
    patch(url: string, body: any, options?: RequestOptionsArgs): Observable<Response> { 
     let stream$ = new Subject<Response>(); 
     this.http[type](url, body, this.addEtagHeader(url, options)).subscribe(response => { 
      if (response.status === 412) { 
       delete this.cache[url]; 
       this.get(url, options).subscribe(response2 => { 
        response2.status = 412; 
        stream$.next(response2); 
       }); 
      } else { 
       this.cache[url].etag = response.json()[ODATA_ETAG_PROPERTY]; 
       this.cache[url].response = response; 
       stream$.next(response); 
      } 
     }); 
     return stream$.asObservable(); 
    } 
} 

質問1:

は、これまでのところ私は解決策多かれ少なかれ(キャッシュにデータとのETagを追加get()メソッドの実装である)働いていstream$を定義する必要はありますか?

質問2:ステータス412の代わりにエラーをスローしたいと思います。このエラーで、サーバーからフェッチされた新しいオブジェクトを返す必要があります。出来ますか?

答えて

2

最小限の侵襲ソリューションはswitchMapを使用することができ、それは次のようになります。

export const HEADER_ETAG_MATCH = 'If-None-Match'; 
export const ODATA_ETAG_PROPERTY = '@odata.etag'; 
export interface CacheRecordStructure { 
    etag: string; 
    response: Response; 
} 
export class CachingService { 
    cache: { [key: string]: CacheRecordStructure } = {}; 
    constructor(private http: Http) { } 
    patch(url: string, body: any, options?: RequestOptionsArgs): Observable<Response> { 
     return this.http[type](url, body, this.addEtagHeader(url, options)) 
      .switchMap(response => { 
       if (response.status === 412) { 
        delete this.cache[url]; 
        return this.get(url, options) 
         .switchMap(response2 => { 
          response2.status = 412; 
          return Observable.throw(response2); 
         }); 
       } else { 
        this.cache[url].etag = response.json()[ODATA_ETAG_PROPERTY]; 
        this.cache[url].response = response; 
        return Observable.of(response); 
       } 
      }); 
    } 
} 

そして、あなたは次のようにそれを使用したい:

myCachingService.patch("myurl...", someBody) 
    .subscribe(
     response => console.log(response), 
     errorWithNewObj => console.error(errorWithNewObj), 
     () => console.info("Done!") 
    ); 
関連する問題