152 lines
5.3 KiB
TypeScript
152 lines
5.3 KiB
TypeScript
import { StorageServiceCasual } from 'common-ui'
|
|
import type { RegionSummary, ResolvedRegion } from '@packages/shared'
|
|
|
|
/**
|
|
* Only the fields the startup decision reads. The live query's serialized
|
|
* address has `createdAt` as a string, so this is deliberately not the shared
|
|
* `UserAddress` DTO (which types it as Date).
|
|
*/
|
|
export interface CachedUserAddress {
|
|
id: number
|
|
regionId: number | null
|
|
boundId: number | null
|
|
isDefault: boolean
|
|
[key: string]: unknown
|
|
}
|
|
|
|
export interface CachedUserAddressesResponse {
|
|
success: boolean
|
|
data: CachedUserAddress[]
|
|
}
|
|
|
|
/**
|
|
* The last device-coordinate -> region/bound answer. Startup renders from it
|
|
* immediately; the live `common.resolveRegionByLocation` call still runs in the
|
|
* background and replaces it when the device is somewhere else.
|
|
*
|
|
* `result` is `null` when the saved coordinates fell outside every bound.
|
|
*/
|
|
export interface CachedLocationResolution {
|
|
lat: number
|
|
lng: number
|
|
result: ResolvedRegion | null
|
|
}
|
|
|
|
/**
|
|
* Small, user-scoped snapshots of the responses that decide where the app
|
|
* starts:
|
|
* - the global region list (`common.listRegions`)
|
|
* - the signed-in user's addresses (`user.address.getUserAddresses`)
|
|
* - the last coordinate resolution (`common.resolveRegionByLocation`)
|
|
*
|
|
* They are only a startup seed. The live tRPC queries always run in the
|
|
* background and overwrite both the React Query cache and these snapshots.
|
|
*/
|
|
// SecureStore only accepts alphanumeric, ".", "-" and "_" in keys.
|
|
export const REGION_LIST_CACHE_KEY = 'region_cache.list_regions.v1'
|
|
export const LOCATION_RESOLUTION_CACHE_KEY = 'region_cache.location_resolution.v1'
|
|
export const userAddressesCacheKey = (userId: number) =>
|
|
`region_cache.user_addresses.v1.${userId}`
|
|
|
|
let lastWrittenRegions: string | null = null
|
|
let lastWrittenResolution: string | null = null
|
|
const lastWrittenAddresses = new Map<number, string>()
|
|
|
|
function parseJson(raw: string | null): unknown {
|
|
if (!raw) return null
|
|
try {
|
|
return JSON.parse(raw)
|
|
} catch {
|
|
return null
|
|
}
|
|
}
|
|
|
|
export async function readCachedRegions(): Promise<RegionSummary[] | null> {
|
|
const parsed = parseJson(await StorageServiceCasual.getItem(REGION_LIST_CACHE_KEY))
|
|
if (
|
|
!Array.isArray(parsed) ||
|
|
!parsed.every(
|
|
(region) =>
|
|
region != null &&
|
|
typeof region === 'object' &&
|
|
typeof (region as RegionSummary).id === 'number'
|
|
)
|
|
) {
|
|
return null
|
|
}
|
|
return parsed as RegionSummary[]
|
|
}
|
|
|
|
export async function writeCachedRegions(regions: RegionSummary[]): Promise<void> {
|
|
const serialized = JSON.stringify(regions)
|
|
// useRegion is consumed by several components; only the first observer needs
|
|
// to write the same response.
|
|
if (serialized === lastWrittenRegions) return
|
|
const stored = await StorageServiceCasual.setItem(REGION_LIST_CACHE_KEY, serialized)
|
|
if (stored) lastWrittenRegions = serialized
|
|
}
|
|
|
|
export async function readCachedUserAddresses(
|
|
userId: number
|
|
): Promise<CachedUserAddressesResponse | null> {
|
|
const parsed = parseJson(await StorageServiceCasual.getItem(userAddressesCacheKey(userId)))
|
|
if (parsed == null || typeof parsed !== 'object') return null
|
|
const response = parsed as Partial<CachedUserAddressesResponse>
|
|
const valid =
|
|
response.success === true &&
|
|
Array.isArray(response.data) &&
|
|
response.data.every(
|
|
(address) =>
|
|
address != null &&
|
|
typeof address === 'object' &&
|
|
typeof address.id === 'number' &&
|
|
typeof address.isDefault === 'boolean'
|
|
)
|
|
return valid ? (response as CachedUserAddressesResponse) : null
|
|
}
|
|
|
|
export async function writeCachedUserAddresses(
|
|
userId: number,
|
|
response: CachedUserAddressesResponse
|
|
): Promise<void> {
|
|
const serialized = JSON.stringify(response)
|
|
if (serialized === lastWrittenAddresses.get(userId)) return
|
|
const stored = await StorageServiceCasual.setItem(userAddressesCacheKey(userId), serialized)
|
|
if (stored) lastWrittenAddresses.set(userId, serialized)
|
|
}
|
|
|
|
function isFiniteNumber(value: unknown): value is number {
|
|
return typeof value === 'number' && Number.isFinite(value)
|
|
}
|
|
|
|
function isCachedLocationResolution(value: unknown): value is CachedLocationResolution {
|
|
if (value == null || typeof value !== 'object') return false
|
|
const candidate = value as Partial<CachedLocationResolution>
|
|
if (!isFiniteNumber(candidate.lat) || !isFiniteNumber(candidate.lng)) return false
|
|
if (candidate.result === null) return true
|
|
|
|
const result = candidate.result as Partial<ResolvedRegion> | undefined
|
|
return (
|
|
result != null &&
|
|
typeof result === 'object' &&
|
|
typeof result.region?.id === 'number' &&
|
|
typeof result.bound?.id === 'number' &&
|
|
typeof result.bound?.regionId === 'number'
|
|
)
|
|
}
|
|
|
|
export async function readCachedLocationResolution(): Promise<CachedLocationResolution | null> {
|
|
const parsed = parseJson(await StorageServiceCasual.getItem(LOCATION_RESOLUTION_CACHE_KEY))
|
|
return isCachedLocationResolution(parsed) ? parsed : null
|
|
}
|
|
|
|
export async function writeCachedLocationResolution(
|
|
resolution: CachedLocationResolution
|
|
): Promise<void> {
|
|
const serialized = JSON.stringify(resolution)
|
|
// useRegion is consumed by several components; only the first observer needs
|
|
// to write the same response.
|
|
if (serialized === lastWrittenResolution) return
|
|
const stored = await StorageServiceCasual.setItem(LOCATION_RESOLUTION_CACHE_KEY, serialized)
|
|
if (stored) lastWrittenResolution = serialized
|
|
}
|