3.1 KiB
plugin
(no submodules)
Purpose
plugin.ts is the public entry point of @suaveplan/drive-plugin-cache. It exports the driveCachePlugin(options): DrivePlugin<DriveCacheHandle> factory — the only function consumers normally need. The factory validates the options synchronously (so misuse fails fast at construction, not on first read), then assembles the cache middleware, stats bag, and handle.
install(drive) registers the middleware on the supplied DriveLike via drive.useMiddleware and returns the DriveCacheHandle. If drive.useMiddleware itself throws, the failure is wrapped as DRIVE_CACHE.INSTALL_FAILED so operators can correlate the install-time error chain.
Features
- Synchronous
DRIVE_CACHE.INVALID_OPTIONSthrow whenoptions.cacheis missing or lacks function-typedget/set/deletemethods. INSTALL_FAILEDwraps any throw fromdrive.useMiddleware, preserving the original cause.- Default namespace
"drive", default invalidationtruefor both write and delete, defaultshouldCacheenforces the 16-MiB ceiling. - Returns
DriveCacheHandlewhosecachereference is identical (===) to the cache passed inoptions.
Usage: Basic
import { driveCachePlugin } from "@suaveplan/drive-plugin-cache";
import { MemoryCache } from "@suaveplan/cache";
const cache = new MemoryCache<Uint8Array>();
const handle = await drive.usePlugin(driveCachePlugin({ cache }));
const bytes1 = await drive.read("clip.mov"); // miss → next() → populate
const bytes2 = await drive.read("clip.mov"); // hit → return cached
Usage: Advanced
import { driveCachePlugin } from "@suaveplan/drive-plugin-cache";
const handleA = await driveA.usePlugin(
driveCachePlugin({
cache, // shared underlying AbstractCache
namespace: "a", // distinct namespace per drive
invalidateOnWrite: true,
invalidateOnDelete: true,
shouldCache: (path, bytes) =>
bytes.byteLength <= 8 * 1024 * 1024,
maxEntryBytes: 8 * 1024 * 1024,
logger,
})
);
const handleB = await driveB.usePlugin(
driveCachePlugin({ cache, namespace: "b" })
);
// handleA and handleB share `cache` but their entries never overlap.
API Reference
| Export | Shape | Description |
|---|---|---|
driveCachePlugin(options) |
(DriveCacheOptions) => DrivePlugin<DriveCacheHandle> |
Factory. Throws DRIVE_CACHE.INVALID_OPTIONS synchronously on misuse. |
The returned plugin object exposes name === "@suaveplan/drive-plugin-cache" and an install(drive) method that registers the middleware and returns the handle.
Implementation Notes
Option validation runs once at factory time. The factory snapshots the namespace into the middleware closure and into the handle closure separately — both stay in sync because the namespace is immutable after construction. The single mutable state shared between the middleware and the handle is the MutableStats counter bag; the handle's getStats() returns shallow snapshots, so consumers cannot reach back into the live counters.