diff --git a/packages/auto-utils/src/index.ts b/packages/auto-utils/src/index.ts index 8a1d16df..5f9ea5e0 100644 --- a/packages/auto-utils/src/index.ts +++ b/packages/auto-utils/src/index.ts @@ -1,2 +1,3 @@ export * from './api' export * from './network' +export * from './save' diff --git a/packages/auto-utils/src/save.ts b/packages/auto-utils/src/save.ts new file mode 100644 index 00000000..c4598193 --- /dev/null +++ b/packages/auto-utils/src/save.ts @@ -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') +}