Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions src/core/util/ajax.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import progressbar from '../render/progressbar.js';
import { noop } from './core.js';

/** @typedef {{updatedAt: string}} CacheOpt */
/** @typedef {{content: string, opt: CacheOpt}} CacheItem */
/** @typedef {{content: string, opt: CacheOpt, response: ResponseStatus}} CacheItem */
/** @typedef {{ok: boolean, status: number, statusText: string}} ResponseStatus */
/** @type {Record<string, CacheItem>} */

Expand All @@ -30,7 +30,10 @@ export function get(url, hasBar = false, headers = {}) {
const cached = cache[url];

if (cached) {
return { then: cb => cb(cached.content, cached.opt), abort: noop };
return {
then: cb => cb(cached.content, cached.opt, cached.response),
abort: noop,
};
}

xhr.open('GET', url);
Expand Down Expand Up @@ -87,9 +90,10 @@ export function get(url, hasBar = false, headers = {}) {
opt: {
updatedAt: xhr.getResponseHeader('last-modified') ?? '',
},
response: getResponseStatus(event),
});

success(result.content, result.opt, getResponseStatus(event));
success(result.content, result.opt, result.response);
}
});
},
Expand Down
30 changes: 30 additions & 0 deletions test/unit/ajax.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import _mock from 'xhr-mock';
import { get } from '../../src/core/util/ajax.js';

const mock = _mock.default;

describe('ajax/get', () => {
beforeEach(() => mock.setup());
afterEach(() => mock.teardown());

test('preserves response status when serving cached content', async () => {
const url = '/cached-response-status.md';
mock.get(url, { status: 200, body: '# Cached page' });

const first = await new Promise(resolve => {
get(url).then((content, opt, response) => {
resolve({ content, opt, response });
});
});
const cached = await new Promise(resolve => {
get(url).then((content, opt, response) => {
resolve({ content, opt, response });
});
});

expect(first.response).toEqual(
expect.objectContaining({ ok: true, status: 200 }),
);
expect(cached).toEqual(first);
});
});
Loading