-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: Add utils to save data to JSON files
...useful when measuring performance.
- Loading branch information
1 parent
86c3e37
commit e0557a2
Showing
2 changed files
with
45 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
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,40 @@ | ||
import fs from "fs"; | ||
|
||
/** | ||
* Use this function to get a JSON file from the filesystem. | ||
* If the file doesn't exist, the function will return the `initialState`. | ||
*/ | ||
export const getJSON = <T extends object>( | ||
filename: string, | ||
initialState: T | ||
): T => { | ||
try { | ||
const file = fs.readFileSync(`${filename}.json`, "utf-8"); | ||
|
||
if (file) { | ||
return JSON.parse(file) as T; | ||
} | ||
} catch (e) { | ||
console.log(`No file found for ${filename}.json. Creating new one!`); | ||
} | ||
|
||
return initialState; | ||
}; | ||
|
||
/** | ||
* Use this function to save a JSON file to the filesystem. | ||
* | ||
* @example | ||
* const data = getJSON("timeResults", { | ||
constructTime: 0, | ||
selectTime: 0, | ||
queryCount: 0, | ||
}); | ||
data.constructTime += constructTime; | ||
data.selectTime += selectTime; | ||
data.queryCount++; | ||
saveJSON("timeResults", data); | ||
*/ | ||
export const saveJSON = <T extends object>(filename: string, data: T) => { | ||
fs.writeFileSync(`${filename}.json`, JSON.stringify(data, null, 2), "utf-8"); | ||
}; |