Skip to content

Commit

Permalink
Merge pull request #10 from subspace/feat/add-dynamic-save-for-both-c…
Browse files Browse the repository at this point in the history
…lient-and-node

Add dynamic save for both client and node
  • Loading branch information
marc-aurele-besner authored Jun 4, 2024
2 parents 5207b22 + 035ec84 commit 73ec885
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 1 deletion.
6 changes: 5 additions & 1 deletion packages/auto-utils/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,16 @@
"test": "jest"
},
"dependencies": {
"@polkadot/api": "^11.2.1"
"@polkadot/api": "^11.2.1",
"fs": "^0.0.1-security"
},
"devDependencies": {
"@types/jest": "^29.5.12",
"jest": "^29.7.0",
"ts-jest": "^29.1.4",
"typescript": "^5.4.5"
},
"browser": {
"fs": false
}
}
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'
20 changes: 20 additions & 0 deletions packages/auto-utils/src/save.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
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')
}
8 changes: 8 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ __metadata:
dependencies:
"@polkadot/api": "npm:^11.2.1"
"@types/jest": "npm:^29.5.12"
fs: "npm:^0.0.1-security"
jest: "npm:^29.7.0"
ts-jest: "npm:^29.1.4"
typescript: "npm:^5.4.5"
Expand Down Expand Up @@ -2574,6 +2575,13 @@ __metadata:
languageName: node
linkType: hard

"fs@npm:^0.0.1-security":
version: 0.0.1-security
resolution: "fs@npm:0.0.1-security"
checksum: 10c0/e0c0b585ec6f7483d63d067215d9d6bb2e0dba5912060d32554c8e566a0e22ee65e4c2a2b0567476efbbfb47682554b4711d69cab49950d01f227a3dfa7d671a
languageName: node
linkType: hard

"fsevents@npm:^2.3.2":
version: 2.3.3
resolution: "fsevents@npm:2.3.3"
Expand Down

0 comments on commit 73ec885

Please sign in to comment.