Created
January 23, 2024 00:09
-
-
Save Mazuh/ef9b5270b6f213d3735e555e669d5316 to your computer and use it in GitHub Desktop.
Basic OPFS adapter in TS.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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