2.2 KiB
2.2 KiB
memory.ts
Purpose
In-memory UploadStorage adapter. Stores raw bytes in a process-local Map<string, Uint8Array> for fast unit tests and local development. Documented as test-only because every byte vanishes when the process exits; production code MUST swap in FileSystemUploadStorage (or a sibling S3/blob adapter).
Features
- Implements the full
UploadStoragecontract (put/get/delete/exists). - Defensive copy on
putso the caller mutating the input buffer does not affect stored bytes. snapshot()test helper returns the current key set without forcing tests throughget().- Throws
FileUploadError(UPLOAD.STORAGE_FAILURE)for missing keys so error-handling paths look identical between memory and fs adapters.
Usage: Basic
import { MemoryUploadStorage } from "@suaveplan/api-plugin-file-upload/storage/memory";
const storage = new MemoryUploadStorage();
await storage.put("upload-001", new Uint8Array([0xff]));
const bytes = await storage.get("upload-001");
Usage: Advanced
import { MemoryUploadStorage } from "@suaveplan/api-plugin-file-upload";
const storage = new MemoryUploadStorage();
await storage.put("a", new Uint8Array([1]));
await storage.put("b", new Uint8Array([2]));
const keys = storage.snapshot();
expect(keys).toContain("a");
await storage.delete("a");
expect(await storage.exists("a")).toBe(false);
API Reference
class MemoryUploadStorage implements UploadStorage— constructor takes no arguments.put(key: string, bytes: Uint8Array): Promise<void>— rejects emptykey.get(key: string): Promise<Uint8Array>— throws on missing key.delete(key: string): Promise<void>— idempotent.exists(key: string): Promise<boolean>.snapshot(): readonly string[]— test-only key listing.
Implementation Notes
- The defensive copy in
putisnew Uint8Array(bytes)so the stored buffer is independent of the caller's reference. Callers expecting structural sharing should layer a custom adapter. deleteis intentionally idempotent (no error on missing key) to match the abort-route's contract: aborting twice is a no-op.- The class is exported as the default test storage and is what
createFileUploadPluginfalls back to when nostorageoption is provided.