Skip to content

Instantly share code, notes, and snippets.

@fael
Last active October 7, 2021 14:53
Show Gist options
  • Save fael/aa3d7b4f86279e6fc5a5e11313fea52e to your computer and use it in GitHub Desktop.
Save fael/aa3d7b4f86279e6fc5a5e11313fea52e to your computer and use it in GitHub Desktop.
If I ever need to make an exchange to let urql have a custom cache storage
/* eslint-disable no-return-assign */
import type {
StorageAdapter,
SerializedEntries,
SerializedRequest,
} from "@urql/exchange-graphStorage";
// OR redis?
let cache = {};
const Storage = {
setItem(k, v) {
console.log("item set");
// tentar hidratar
const data = v;
console.log(Object.keys(v).length);
return process.browser ? localStorage.setItem(k, data) : (cache[k] = data);
},
getItem(k) {
console.log("item get");
return process.browser ? localStorage.getItem(k) : cache?.[k];
},
};
export interface CustomStorage extends StorageAdapter {
clear(): void;
}
const makeCacheStorage = () => {
const temp = {};
return {
writeData(delta) {
console.log("writing data");
return Promise.resolve().then(() => {
Object.assign(temp, delta);
console.log("updating Storage");
const newData = JSON.stringify(temp);
if (process.browser) {
window.rafael = temp;
}
Storage.setItem("cache", newData);
});
},
readData() {
console.log("reading data");
return Promise.resolve().then(() => {
const local = Storage.getItem("cache") || null;
Object.assign(temp, JSON.parse(local));
console.log("fetching Storage");
return temp;
});
},
};
};
// const makeNodeCacheStorageFull = (): CustomStorage => {
// const CACHE_NAME = `graphStorage-v4-entries`;
// const METADATA_CACHE_NAME = `graphStorage-v4-metadata`;
// return {
// clear(): void {
// Storage.clear(CACHE_NAME);
// Storage.clear(METADATA_CACHE_NAME);
// },
// async writeData(delta: SerializedEntries): Promise<any> {
// console.log("writing data");
// Object.assign(Storage, delta);
// await Storage.setItem(CACHE_NAME, JSON.stringify(Storage));
// return Storage;
// },
// async readData(): Promise<SerializedEntries> {
// console.log("reading data");
// const local = await Storage.getItem(CACHE_NAME);
// // eslint-disable-next-line no-unused-expressions
// local && Object.assign(Storage, JSON.parse(local));
// return Storage;
// },
// writeMetadata(json: SerializedRequest[]) {
// Storage.setItem(METADATA_CACHE_NAME, JSON.stringify(json));
// },
// async readMetadata(): Promise<SerializedRequest[] | null> {
// const metadataJson = await Storage.getItem(METADATA_CACHE_NAME);
// return metadataJson ? JSON.parse(metadataJson) : null;
// },
// };
// };
export default makeCacheStorage;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment