diff --git a/src/SDKFetch.ts b/src/SDKFetch.ts index b056f07d5..b6d8db77e 100644 --- a/src/SDKFetch.ts +++ b/src/SDKFetch.ts @@ -40,6 +40,12 @@ export type SDKFetchOptions = { * response headers。默认为 false,仅返回 response body。 */ includeHeaders?: boolean + + /** + * 当设置为 false 时,将强制浏览器不缓存请求,仅对 GET 类型生效, + * 默认为 false + */ + cache?: boolean } export namespace HttpHeaders { @@ -117,8 +123,11 @@ export class SDKFetch { if (!SDKFetch.FetchStack.has(urlWithQuery)) { const tail = SDKFetch.fetchTail || Date.now() - const urlWithTail = appendQueryString(urlWithQuery, `_=${ tail }`) - dist = Observable.defer(() => http.setUrl(urlWithTail).get()['request']) + let requestUrl = urlWithQuery + if (!options.cache) { + requestUrl = appendQueryString(urlWithQuery, `_=${ tail }`) + } + dist = Observable.defer(() => http.setUrl(requestUrl).get()['request']) .shareReplay(1) .finally(() => { SDKFetch.FetchStack.delete(urlWithQuery) diff --git a/test/SDKFetch.spec.ts b/test/SDKFetch.spec.ts index 54d5049a2..9c9f2268a 100644 --- a/test/SDKFetch.spec.ts +++ b/test/SDKFetch.spec.ts @@ -142,6 +142,51 @@ describe('SDKFetch', () => { }) }) + it('`cache` should effected', function* () { + fetchMock.get(urlMatcher, {}) + + // 无 query 的 GET + yield sdkFetch.get(path, null, { cache: true }) + .subscribeOn(Scheduler.asap) + .do(() => { + expect(fetchMock.lastUrl(urlMatcher).indexOf('?_=')).to.equal(-1) + }) + + // 有 query 的 GET + const query = { value: 'A' } + yield sdkFetch.get(path, query, { cache: true }) + .subscribeOn(Scheduler.asap) + .do(() => { + expect(fetchMock.lastUrl(urlMatcher).indexOf('&_=')).to.equal(-1) + }) + }) + + it('`cache` default should be `false`', function* () { + fetchMock.get(urlMatcher, {}) + + // 无 query 的 GET + yield sdkFetch.get(path) + .subscribeOn(Scheduler.asap) + .do(() => { + const delimiter = '?_=' + const [prefix, timestamp] = fetchMock.lastUrl(urlMatcher).split(delimiter, 2) + expect(prefix).to.equal(testUrl) + expect(new Date(Number(timestamp)).valueOf()).to.closeTo(new Date().valueOf(), 100) + }) + + // 带 query 的 GET + const query = { value: 'A' } + const urlWithQuery = testUrl + '?value=A' + yield sdkFetch.get(path, query) + .subscribeOn(Scheduler.asap) + .do(() => { + const delimiter = '&_=' + const [prefix, timestamp] = fetchMock.lastUrl(urlMatcher).split(delimiter, 2) + expect(prefix).to.equal(urlWithQuery) + expect(new Date(Number(timestamp)).valueOf()).to.closeTo(new Date().valueOf(), 100) + }) + }) + it('get with empty query object should work correctly', function* () { fetchMock.get(urlMatcher, {})