Skip to content

Commit

Permalink
add a save function that both support fs and localstorage
Browse files Browse the repository at this point in the history
  • Loading branch information
marc-aurele-besner committed Jun 4, 2024
1 parent 5207b22 commit 2dcada1
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
1 change: 1 addition & 0 deletions packages/auto-utils/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export * from './api'
export * from './network'
export * from './save'
23 changes: 23 additions & 0 deletions packages/auto-utils/src/save.ts
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')
}

0 comments on commit 2dcada1

Please sign in to comment.