-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
add a save function that both support fs and localstorage
- Loading branch information
1 parent
5207b22
commit 2dcada1
Showing
2 changed files
with
24 additions
and
0 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,2 +1,3 @@ | ||
export * from './api' | ||
export * from './network' | ||
export * from './save' |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
export const save = async (key: string, value: any) => { | ||
// detect if we are in the browser or in node | ||
if (typeof window !== 'undefined') { | ||
await saveOnLocalStorage(key, value) | ||
} else { | ||
await saveOnFileSystem(key, value) | ||
} | ||
} | ||
|
||
export const saveOnLocalStorage = async (key: string, value: any) => { | ||
if (typeof window !== 'undefined') | ||
// save on local storage | ||
localStorage.setItem(key, JSON.stringify(value)) | ||
else throw new Error('This function can only be used in the browser') | ||
} | ||
|
||
export const saveOnFileSystem = async (key: string, value: any) => { | ||
if (typeof window === 'undefined') { | ||
// save on file system | ||
const fs = await import('fs/promises') | ||
await fs.writeFile(key, JSON.stringify(value)) | ||
} else throw new Error('This function can only be used in node') | ||
} |