Created
April 22, 2023 17:21
-
-
Save bhumit070/838749c1a0024b327e1b3e4c431b10e3 to your computer and use it in GitHub Desktop.
Typesafe Localstorage With Typescript And Zod
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
import * as z from 'zod'; | |
const LocalStorageSchema = z.object({ | |
name: z.string(), | |
age: z.number(), | |
isEmployed: z.boolean(), | |
}); | |
type LocalStorageData = z.infer<typeof LocalStorageSchema>; | |
class LocalStorageManager { | |
private static instance: LocalStorageManager; | |
private storage: Storage; | |
private constructor() { | |
this.storage = window.localStorage; | |
} | |
public static getInstance(): LocalStorageManager { | |
if (!LocalStorageManager.instance) { | |
LocalStorageManager.instance = new LocalStorageManager(); | |
} | |
return LocalStorageManager.instance; | |
} | |
public async setItem<K extends keyof LocalStorageData>( | |
key: K, | |
value: LocalStorageData[K], | |
): Promise<void> { | |
const itemSchema = LocalStorageSchema.pick({ [key]: true }); | |
await itemSchema.parseAsync({ [key]: value }); | |
this.storage.setItem(key, JSON.stringify(value)); | |
} | |
public async getItem<K extends keyof LocalStorageData>( | |
key: K, | |
): Promise<LocalStorageData[K]> { | |
const value = this.storage.getItem(key); | |
if (value === null) { | |
throw new Error(`Item with key ${key} does not exist`); | |
} | |
const itemSchema = LocalStorageSchema.pick({ [key]: true }); | |
const parsedValue = await itemSchema.parseAsync({ | |
[key]: JSON.parse(value), | |
}); | |
return parsedValue[key]; | |
} | |
public removeItem(key: keyof LocalStorageData): Promise<void> { | |
this.storage.removeItem(key); | |
return Promise.resolve(); | |
} | |
} | |
const storage = LocalStorageManager.getInstance(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment