-
Notifications
You must be signed in to change notification settings - Fork 106
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
refactor(libraries): type safe local storage json (#6455)
- Loading branch information
1 parent
f6d2aee
commit 6924a1a
Showing
16 changed files
with
160 additions
and
66 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
--- | ||
'hive': patch | ||
--- | ||
|
||
A minor defect in Laboratory has been fixed that previously caused the application to crash when local storage was in a particular state. |
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
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 |
---|---|---|
@@ -1,23 +1,75 @@ | ||
import { useCallback, useState } from 'react'; | ||
import { z } from 'zod'; | ||
import { Kit } from '../kit'; | ||
|
||
export function useLocalStorageJson<T>(key: string, defaultValue: T) { | ||
const [value, setValue] = useState<T>(() => { | ||
const json = localStorage.getItem(key); | ||
export function useLocalStorageJson<$Schema extends z.ZodType>(...args: ArgsInput<$Schema>) { | ||
const [key, schema, manualDefaultValue] = args as any as Args<$Schema>; | ||
// The parameter types will force the user to give a manual default | ||
// if their given Zod schema does not have default. | ||
// | ||
// We resolve that here because in the event of a Zod parse failure, we fallback | ||
// to the default value, meaning we are needing a reference to the Zod default outside | ||
// of the regular parse process. | ||
// | ||
const defaultValue = | ||
manualDefaultValue !== undefined | ||
? manualDefaultValue | ||
: Kit.ZodHelpers.isDefaultType(schema) | ||
? (schema._def.defaultValue() as z.infer<$Schema>) | ||
: Kit.never(); | ||
|
||
const [value, setValue] = useState<z.infer<$Schema>>(() => { | ||
// Note: `null` is returned for missing values. However Zod only kicks in | ||
// default values for `undefined`, not `null`. However-however, this is ok, | ||
// because we manually pre-compute+return the default value, thus we don't | ||
// rely on Zod's behaviour. If that changes this should have `?? undefined` | ||
// added. | ||
const storedValue = localStorage.getItem(key); | ||
|
||
if (!storedValue) { | ||
return defaultValue; | ||
} | ||
|
||
// todo: Some possible improvements: | ||
// - Monitor json/schema parse failures. | ||
// - Let caller choose an error strategy: 'return' / 'default' / 'throw' | ||
try { | ||
const result = json ? JSON.parse(json) : defaultValue; | ||
return result; | ||
} catch (_) { | ||
return schema.parse(JSON.parse(storedValue)); | ||
} catch (error) { | ||
if (error instanceof SyntaxError) { | ||
console.warn(`useLocalStorageJson: JSON parsing failed for key "${key}"`, error); | ||
} else if (error instanceof z.ZodError) { | ||
console.warn(`useLocalStorageJson: Schema validation failed for key "${key}"`, error); | ||
} else { | ||
Kit.neverCatch(error); | ||
} | ||
return defaultValue; | ||
} | ||
}); | ||
|
||
const set = useCallback( | ||
(value: T) => { | ||
(value: z.infer<$Schema>) => { | ||
localStorage.setItem(key, JSON.stringify(value)); | ||
setValue(value); | ||
}, | ||
[setValue], | ||
[key], | ||
); | ||
|
||
return [value, set] as const; | ||
} | ||
|
||
type ArgsInput<$Schema extends z.ZodType> = | ||
$Schema extends z.ZodDefault<z.ZodType> | ||
? [key: string, schema: ArgsInputGuardZodJsonSchema<$Schema>] | ||
: [key: string, schema: ArgsInputGuardZodJsonSchema<$Schema>, defaultValue: z.infer<$Schema>]; | ||
|
||
type ArgsInputGuardZodJsonSchema<$Schema extends z.ZodType> = | ||
z.infer<$Schema> extends Kit.Json.Value | ||
? $Schema | ||
: 'Error: Your Zod schema is or contains a type that is not valid JSON.'; | ||
|
||
type Args<$Schema extends z.ZodType> = [ | ||
key: string, | ||
schema: $Schema, | ||
defaultValue?: z.infer<$Schema>, | ||
]; |
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 |
---|---|---|
@@ -1,6 +1,14 @@ | ||
// eslint-disable-next-line import/no-self-import | ||
export * as Kit from './index'; | ||
// Storybook (or the version we are using) | ||
// is using a version of Babel that does not | ||
// support re-exporting as namespaces: | ||
// | ||
// export * as Kit from './index'; | ||
// | ||
// So we have to re-export everything manually | ||
// and incur an additional index_ file for it | ||
// too: | ||
|
||
export * from './never'; | ||
export * from './types/headers'; | ||
export * from './helpers'; | ||
import * as Kit from './index_'; | ||
|
||
// eslint-disable-next-line unicorn/prefer-export-from | ||
export { Kit }; |
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,5 @@ | ||
export * from './never'; | ||
export * from './types/headers'; | ||
export * from './helpers'; | ||
export * from './json'; | ||
export * from './zod-helpers'; |
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,19 @@ | ||
import { z } from 'zod'; | ||
import { ZodHelpers } from './zod-helpers'; | ||
|
||
// eslint-disable-next-line @typescript-eslint/no-namespace | ||
export namespace Json { | ||
export const Primitive = z.union([z.string(), z.number(), z.boolean(), z.null()]); | ||
export type Primitive = z.infer<typeof Primitive>; | ||
export const isPrimitive = ZodHelpers.createTypeGuard(Primitive); | ||
|
||
export const Value: z.ZodType<Value> = z.lazy(() => | ||
z.union([Primitive, z.array(Value), z.record(Value)]), | ||
); | ||
export type Value = Primitive | { [key: string]: Value } | Value[]; | ||
export const isValue = ZodHelpers.createTypeGuard(Value); | ||
|
||
export const Object: z.ZodType<Object> = z.record(Value); | ||
export type Object = { [key: string]: Value }; | ||
export const isObject = ZodHelpers.createTypeGuard(Object); | ||
} |
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,15 @@ | ||
import { z } from 'zod'; | ||
|
||
// eslint-disable-next-line @typescript-eslint/no-namespace | ||
export namespace ZodHelpers { | ||
export const isDefaultType = (zodType: z.ZodType): zodType is z.ZodDefault<z.ZodType> => { | ||
return 'defaultValue' in zodType._def; | ||
}; | ||
|
||
export const createTypeGuard = | ||
<$Schema extends z.ZodType, $Value = z.infer<$Schema>>(schema: $Schema) => | ||
(value: unknown): value is $Value => { | ||
const result = schema.safeParse(value); | ||
return result.success; | ||
}; | ||
} |
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 was deleted.
Oops, something went wrong.
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
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
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.