Skip to content

Commit

Permalink
feat: Add utils to save data to JSON files
Browse files Browse the repository at this point in the history
...useful when measuring performance.
  • Loading branch information
bprusinowski committed Oct 18, 2023
1 parent 86c3e37 commit e0557a2
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
5 changes: 5 additions & 0 deletions app/next.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,11 @@ module.exports = withPreconstruct(
new IgnorePlugin({ resourceRegExp: /^(pg-native|vue)$/ })
);

config.resolve.fallback = {
...config.resolve.fallback,
fs: false,
};

return config;
},
})
Expand Down
40 changes: 40 additions & 0 deletions app/utils/getSaveJson.ts
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");
};

0 comments on commit e0557a2

Please sign in to comment.