mirror of
https://github.com/tompro/sattle.git
synced 2026-08-26 23:05:58 +00:00
refactor: add strict JSON parsing helpers
This commit is contained in:
@@ -0,0 +1,20 @@
|
||||
export const isJsonObject = (value: unknown): value is Record<string, unknown> =>
|
||||
typeof value === 'object' && value !== null && !Array.isArray(value)
|
||||
|
||||
export const parseJsonObject = (source: string): Record<string, unknown> => {
|
||||
const parsed: unknown = JSON.parse(source)
|
||||
if (!isJsonObject(parsed)) throw new TypeError('Expected a JSON object.')
|
||||
return parsed
|
||||
}
|
||||
|
||||
export const parseJsonArray = (source: string): unknown[] => {
|
||||
const parsed: unknown = JSON.parse(source)
|
||||
if (!Array.isArray(parsed)) throw new TypeError('Expected a JSON array.')
|
||||
return Array.from(parsed, (value: unknown) => value)
|
||||
}
|
||||
|
||||
export const parseJsonObjectArray = (source: string): Array<Record<string, unknown>> =>
|
||||
parseJsonArray(source).map((value) => {
|
||||
if (!isJsonObject(value)) throw new TypeError('Expected a JSON object array.')
|
||||
return value
|
||||
})
|
||||
@@ -2,6 +2,9 @@
|
||||
// a browser) plus the mock-mint helpers every suite uses.
|
||||
|
||||
import {vi} from 'vitest'
|
||||
import {parseJsonArray, parseJsonObject, parseJsonObjectArray} from './jsonParsing'
|
||||
|
||||
export {parseJsonArray, parseJsonObject, parseJsonObjectArray}
|
||||
|
||||
export class LocalStorageStub {
|
||||
private map = new Map<string, string>()
|
||||
@@ -26,3 +29,16 @@ export const stubLocalStorage = (): LocalStorageStub => {
|
||||
vi.stubGlobal('localStorage', stub)
|
||||
return stub
|
||||
}
|
||||
|
||||
export const requiredValue = <T>(
|
||||
value: T | null | undefined,
|
||||
message = 'Expected test value to be present',
|
||||
): T => {
|
||||
if (value === null || value === undefined) throw new TypeError(message)
|
||||
return value
|
||||
}
|
||||
|
||||
export const requiredString = (value: unknown, message = 'Expected a string value'): string => {
|
||||
if (typeof value !== 'string') throw new TypeError(message)
|
||||
return value
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user