2
0
mirror of https://github.com/iconify/iconify.git synced 2024-11-10 07:11:00 +00:00
iconify/packages/browser-tests/tests/fake-api.ts
2020-04-28 12:47:35 +03:00

101 lines
2.1 KiB
TypeScript

import { RedundancyPendingItem } from '@cyberalien/redundancy';
import {
APIQueryParams,
IconifyAPIPrepareQuery,
IconifyAPISendQuery,
} from '@iconify/core/lib/api/modules';
import { IconifyJSON } from '@iconify/types';
/**
* Fake data entry
*/
export interface FakeData {
icons: string[];
host?: string; // host to respond to
delay?: number; // 0 = instant reply
data: IconifyJSON; // data to send
}
/**
* Fake data storage
*/
const fakeData: Record<string, FakeData[]> = Object.create(null);
export function setFakeData(prefix: string, item: FakeData): void {
if (fakeData[prefix] === void 0) {
fakeData[prefix] = [];
}
fakeData[prefix].push(item);
}
interface FakeAPIQueryParams extends APIQueryParams {
data: FakeData;
}
/**
* Prepare params
*/
export const prepareQuery: IconifyAPIPrepareQuery = (
prefix: string,
icons: string[]
): APIQueryParams[] => {
// Find items that have query
const items: APIQueryParams[] = [];
let missing = icons.slice(0);
if (fakeData[prefix] !== void 0) {
fakeData[prefix].forEach(item => {
const matches = item.icons.filter(
icon => missing.indexOf(icon) !== -1
);
if (!matches.length) {
// No match
return;
}
// Contains at least one matching icon
missing = missing.filter(icon => matches.indexOf(icon) === -1);
const query: FakeAPIQueryParams = {
prefix,
icons: matches,
data: item,
};
items.push(query);
});
}
return items;
};
/**
* Load icons
*/
export const sendQuery: IconifyAPISendQuery = (
host: string,
params: APIQueryParams,
status: RedundancyPendingItem
): void => {
const prefix = params.prefix;
const icons = params.icons;
const data = (params as FakeAPIQueryParams).data;
if (!data) {
throw new Error('Fake data is missing in query params');
}
if (typeof data.host === 'string' && data.host !== host) {
// Host mismatch - do nothing
return;
}
const sendResponse = () => {
console.log('Sending data for prefix "' + prefix + '", icons:', icons);
status.done(data.data);
};
if (!data.delay) {
sendResponse();
} else {
setTimeout(sendResponse, data.delay);
}
};