2
0
mirror of https://github.com/iconify/iconify.git synced 2024-12-13 22:18:24 +00:00
iconify/packages/core/spec/cache/fakeCache.mjs

120 lines
1.9 KiB
JavaScript
Raw Normal View History

import {
mock,
count,
config,
emptyList,
} from '@iconify/core/lib/browser-storage';
2020-04-28 09:47:35 +00:00
/**
* Get next icon set prefix for testing
*/
let prefixCounter = 0;
export function nextPrefix() {
2020-04-28 09:47:35 +00:00
return 'fake-storage-' + prefixCounter++;
}
// Cache version. Bump when structure changes
export const cacheVersion = 'iconify2';
2020-04-28 09:47:35 +00:00
// Cache keys
export const cachePrefix = 'iconify';
export const countKey = cachePrefix + '-count';
export const versionKey = cachePrefix + '-version';
/**
* Cache expiration
*/
export const hour = 3600000;
export const cacheExpiration = 168; // In hours
/**
* Storage class
*/
export class Storage {
canRead = true;
canWrite = true;
items = Object.create(null);
2020-04-28 09:47:35 +00:00
/**
* Get number of items
*/
get length() {
2020-04-28 09:47:35 +00:00
if (!this.canRead) {
throw new Error('Restricted storage');
}
return Object.keys(this.items).length;
}
/**
* Get item
*
* @param name
*/
getItem(name) {
2020-04-28 09:47:35 +00:00
if (!this.canRead) {
throw new Error('Restricted storage');
}
return this.items[name] === void 0 ? null : this.items[name];
}
/**
* Set item
*
* @param name
* @param value
*/
setItem(name, value) {
2020-04-28 09:47:35 +00:00
if (!this.canWrite) {
throw new Error('Read-only storage');
}
this.items[name] = value;
}
/**
* Remove item
*
* @param name
*/
removeItem(name) {
2020-04-28 09:47:35 +00:00
if (!this.canWrite) {
throw new Error('Read-only storage');
}
delete this.items[name];
}
/**
* Clear everything
*/
clear() {
2020-04-28 09:47:35 +00:00
if (!this.canWrite) {
throw new Error('Read-only storage');
}
this.items = Object.create(null);
}
}
/**
* Create fake storage, assign localStorage type
*/
export function createCache() {
return new Storage();
2020-04-28 09:47:35 +00:00
}
/**
* Reset test
*
* @param fakeWindow
*/
export function reset(fakeWindow) {
2020-04-28 09:47:35 +00:00
// Replace window
mock(fakeWindow);
// Reset all data
for (const key in config) {
const attr = key;
2020-04-28 09:47:35 +00:00
config[attr] = true;
count[attr] = 0;
emptyList[attr] = [];
}
}