Skip to content

Instantly share code, notes, and snippets.

@Mazuh
Created January 23, 2024 00:09
Show Gist options
  • Save Mazuh/ef9b5270b6f213d3735e555e669d5316 to your computer and use it in GitHub Desktop.
Save Mazuh/ef9b5270b6f213d3735e555e669d5316 to your computer and use it in GitHub Desktop.
Basic OPFS adapter in TS.
interface OpfsAdapter<T> {
persist: (data: T) => Promise<void>;
retrieve: () => Promise<T | null>;
}
export async function makeOpfsAdapter<T>(filename: string): Promise<OpfsAdapter<T>> {
const opfsRoot = await navigator.storage.getDirectory();
const directoryHandle = await opfsRoot.getDirectoryHandle("my_pretty_stuff", {
create: true,
});
const fileHandle = await directoryHandle.getFileHandle(filename, {
create: true,
});
const persist = async (data: T) => {
const writableFileStream = await fileHandle.createWritable();
try {
await writableFileStream.write(JSON.stringify(data));
} finally {
await writableFileStream.close();
}
};
const retrieve = async (): Promise<T> => {
const file = await fileHandle.getFile();
const text = await file.text();
return text ? JSON.parse(text) : null;
};
return { persist, retrieve };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment