All files storage.ts

100% Statements 11/11
100% Branches 23/23
100% Functions 5/5
100% Lines 10/10

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74                                                                      428x       308x             161x   147x 308x                 120x 112x     4x       141x         126x    
/** @internal */
export interface Metadata {
  version: string;
  etag: string | null;
  validatedAt: number;
  invalidated: boolean;
}
 
/** @internal */
export interface Entry<T> extends Metadata {
  data: T;
}
 
/** An absent body means that the caller already has this version. @internal */
export interface Stored {
  meta: Metadata;
  body?: { data: unknown };
}
 
/** @internal */
export interface CompleteStored extends Stored {
  body: { data: unknown };
}
 
/** @internal */
export interface StorageBackend {
  read(key: string, version?: string): Promise<Stored | undefined>;
  /** False means a conditional update skipped a missing or replaced response. */
  write(key: string, entry: Entry<unknown>, modified: boolean): Promise<boolean>;
  invalidate(key: string): Promise<Stored | undefined>;
  remove(key: string): Promise<void>;
  clear(allVersions: boolean): Promise<void>;
}
 
export function object(value: unknown): value is Record<string, unknown> {
  return typeof value === "object" && value !== null;
}
 
export function metadata(value: unknown): Metadata | undefined {
  if (
    !object(value) ||
    typeof value.version !== "string" ||
    !value.version ||
    !(value.etag === null || typeof value.etag === "string") ||
    typeof value.invalidated !== "boolean"
  )
    return undefined;
  const validTime =
    typeof value.validatedAt === "number" && Number.isFinite(value.validatedAt) && value.validatedAt >= 0;
  return {
    version: value.version,
    etag: value.etag,
    validatedAt: validTime ? (value.validatedAt as number) : 0,
    invalidated: !validTime || value.invalidated === true,
  };
}
 
export function stored(meta: Metadata, body: unknown): CompleteStored | undefined {
  if (!object(body) || body.version !== meta.version || !Object.hasOwn(body, "data")) return undefined;
  return { meta, body: { data: body.data } };
}
 
export const storagePrefix = "@oomol-lab/resource-cache:";
 
/** Delimit identity fields without ambiguous string concatenation. @internal */
export function scope(namespace: string): string {
  return storagePrefix + JSON.stringify(namespace);
}
 
/** @internal */
export function sessionScope(namespace: string, sessionId: string): string {
  return storagePrefix + JSON.stringify([namespace, sessionId]);
}