@unikvs/writeonly
How to use @unikvs/writeonly, which rejects reads to make storage write-only.
Overview
@unikvs/writeonly Middleware rejects reads to make storage write-only.
Read-direction operations (get / has / stream / decode) are rejected as if the key did not exist, while write-direction operations (set / copy / move) pass through. When allowDelete is false, deletion is also rejected.
nameisWriteOnly.isOpenis alwaystrue.allowDeletedefaults tofalse.
Install with:
npm install @unikvs/writeonlypnpm add @unikvs/writeonlyyarn add @unikvs/writeonlybun add @unikvs/writeonlynub add @unikvs/writeonlyaube add @unikvs/writeonlyUsage
WriteOnly implements IMiddleware. Pass it to UniKvs with use().
import { WriteOnly } from "@unikvs/writeonly";
WriteOnly
Middleware that rejects reads to make storage write-only.
Constructor arguments:
allowDelete?boolean
Whether to allow delete operations. When false, delete and clear are rejected.
booleanfalseThe following stores a value:
import { Memory } from "@unikvs/memory";
import { WriteOnly } from "@unikvs/writeonly";
import * as unikvs from "unikvs";
const kvs = new unikvs.Builder<{
foo: unikvs.Value<Uint8Array>;
}>()
.use(new WriteOnly())
.persist(new Memory())
.build();
await kvs.open();
await kvs.set("foo", new Uint8Array([0, 1, 2]));
await kvs.close();
Data types
| Method | Input | Output |
|---|---|---|
encode |
write value | Write value (passed through) |
decode |
read value | Always throws KeyNotFoundError |
getEncodable |
write chunk | Write chunk (passed through) |
getDecodable |
read chunk | Always throws KeyNotFoundError |
- The write direction performs no conversion and passes values through.
copyandmoveare allowed as write-direction operations because they do not return values.- The read direction always fails, as if the key did not exist.
- Deletion is controlled by
use(): whenallowDeleteisfalse,deleteandclearare rejected.
Errors
Errors thrown by this package:
WriteOnlyDeleteNotAllowedError
Meaning
Thrown when delete is called while allowDelete is false.
How to fix
Pass allowDelete: true when deletion is needed.
WriteOnlyClearNotAllowedError
Meaning
Thrown when clear is called while allowDelete is false.
How to fix
Pass allowDelete: true when clearing everything is needed.
KeyNotFoundError
Meaning
Thrown when a read-direction operation (get / has / stream / decode) is called. This is the shared @unikvs/core error.
How to fix
Do not use this middleware when reads are needed.
Example
Catching KeyNotFoundError:
import { KeyNotFoundError } from "@unikvs/writeonly";
try {
const data = await kvs.get("foo");
} catch (ex) {
if (ex instanceof KeyNotFoundError) {
console.log("reads are not allowed");
} else {
throw ex;
}
}