-
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.
Modify load key functions considering the dynamic read function added…
… in auto-utils
- Loading branch information
Showing
5 changed files
with
36 additions
and
19 deletions.
There are no files selected for viewing
This file was deleted.
Oops, something went wrong.
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
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,3 +1,4 @@ | ||
export * from './api' | ||
export * from './network' | ||
export * from './read' | ||
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,30 @@ | ||
export const read = async (key: string) => { | ||
// detect if we are in the browser or in node | ||
if (typeof window !== 'undefined') return readFromLocalStorage(key) | ||
else return readFromFileSystem(key) | ||
} | ||
|
||
export const readFromLocalStorage = async (key: string) => { | ||
if (typeof window !== 'undefined') { | ||
// read from local storage | ||
const value = localStorage.getItem(key) | ||
try { | ||
return value ? JSON.parse(value) : null | ||
} catch (error) { | ||
throw new Error('Failed to parse data from localStorage: ' + error) | ||
} | ||
} else throw new Error('This function can only be used in the browser') | ||
} | ||
|
||
export const readFromFileSystem = async (key: string) => { | ||
if (typeof window === 'undefined') { | ||
// read from file system | ||
const fs = await import('fs/promises') | ||
try { | ||
const data = await fs.readFile(key, { encoding: 'utf-8' }) | ||
return JSON.parse(data); | ||
} catch (error) { | ||
throw new Error('Failed to read or parse file: ' + error) | ||
} | ||
} else throw new Error('This function can only be used in node') | ||
} |
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