fix: relax content types when setting cache

This commit is contained in:
thepassle 2022-11-07 12:42:39 +01:00
parent 3cc3d2960f
commit 1565bc81ca
2 changed files with 33 additions and 2 deletions

View file

@ -31,10 +31,10 @@ const isMethodSupported = (methods, method) => methods.includes(method.toLowerCa
* @param {string[]|undefined} contentTypes
* @returns {boolean} `true` if the contentTypes property is not an array, or if the value of the Content-Type header is in the array
*/
const isResponseContentTypeSupported = (response, contentTypes) => {
export const isResponseContentTypeSupported = (response, contentTypes) => {
if (!Array.isArray(contentTypes)) return true;
return contentTypes.includes(String(response.headers.get('Content-Type')));
return !!contentTypes.find(ct => String(response.headers.get('Content-Type')).includes(ct));
};
/**

View file

@ -1,6 +1,7 @@
import { expect } from '@open-wc/testing';
import * as sinon from 'sinon';
import { Ajax, createCacheInterceptors } from '@lion/ajax';
import { isResponseContentTypeSupported } from '../../src/interceptors/cacheInterceptors.js';
// TODO: these are private API? should they be exposed? if not why do we test them?
import { extendCacheOptions, resetCacheSession, ajaxCache } from '../../src/cacheManager.js';
@ -72,6 +73,36 @@ describe('cache interceptors', () => {
sinon.restore();
});
describe('isResponseContentTypeSupported', () => {
/** @type {Response} */
let r;
beforeEach(() => {
r = new Response('');
});
it('matches default content type', () => {
r.headers.set('Content-Type', 'application/json');
expect(isResponseContentTypeSupported(r, ['application/json'])).to.equal(true);
});
it('returns false when it doesnt match', () => {
r.headers.set('Content-Type', 'text/json');
expect(isResponseContentTypeSupported(r, ['application/json'])).to.equal(false);
});
it('partially matches content type', () => {
r.headers.set('Content-Type', 'text/plain;charset=UTF-8;');
expect(isResponseContentTypeSupported(r, ['text/plain'])).to.equal(true);
});
it('returns true if `contentTypes` is not an array', () => {
r.headers.set('Content-Type', 'foo');
// @ts-ignore needed for test
expect(isResponseContentTypeSupported(r, 'string')).to.equal(true);
});
});
describe('Original ajax instance', () => {
it('allows direct ajax calls without cache interceptors configured', async () => {
await ajax.fetch('/test');