Typed values
Store and read application data through keys that carry a Schema codec.
Redis stores bytes. A RedisKey pairs a key name with a codec, so redis.setKey and redis.getKey encode and decode values for you. Nothing is JSON-encoded unless you choose a JSON key.
Example (Saving and Loading a Schema-Backed Key)
import { , } from "effect";
import { , RedisKey } from "@effect-kit/redis";
const = .({ : ., : . });
const = RedisKey.("user:42", );
const = .(function* () {
const = yield* ;
yield* .(, { : "Ada", : true });
const user = yield* .();
return ;
});RedisKey.json stores the value as a JSON string and decodes it with the Schema. getKey returns Option<A> for the Schema's type, and setKey accepts that same type. A decode failure is a PayloadError, which appears in the error type next to RedisError.
Prefer Schema-backed keys
A key with a Schema keeps the shape of stored data in one place. Plain get and set return and
take strings, with no check on what is inside.
Building keys
| Constructor | Value type | Stored as |
|---|---|---|
RedisKey.text(name) | string | UTF-8 text |
RedisKey.json(name, schema) | the Schema's Type | JSON string |
RedisKey.schemaText(name, schema) | the Schema's Type | the Schema's string encoding |
RedisKey.make(name, codec) | the codec's type | whatever the codec writes |
schemaText takes a Schema whose encoded side is string.
Example (Storing a Number as Text)
import { , } from "effect";
import { , RedisKey } from "@effect-kit/redis";
const = RedisKey.("jobs:retries", .);
const = .(function* () {
const = yield* ;
yield* .(, 3);
const stored = yield* .(); const raw = yield* .("jobs:retries");
return { , };
});Decoding is strict UTF-8. Bytes that are not valid UTF-8 fail with a PayloadError whose stage is "decode".
Writing a codec
A PayloadCodec<A> is a pair of functions: encode returns Uint8Array and decode takes one. PayloadCodec.text, PayloadCodec.schemaText(schema) and PayloadCodec.json(schema) cover the common cases. RedisKey.make attaches any codec to a key name.
Example (Keeping a Key's Codec Next to Its Name)
import { , } from "effect";
import { PayloadCodec, , RedisKey } from "@effect-kit/redis";
const = .({ : ., : . });
const = (: string) => RedisKey.(`session:${}`, PayloadCodec.());
const = .(function* () {
const = yield* ;
yield* .(
("a1"),
{ : "42", : 1893456000 },
{
: { : "EX", : 3600 },
},
);
return yield* .(("a1"));
});setKey takes the same options as set, except get. A Schema that needs services puts those services in the Effect requirements, so the program must provide them.
Reading bytes
redis.getBytes returns Option<Uint8Array> and does no decoding. Use it for binary values. Missing keys are None, and an empty value is Some of an empty array.
Hash, list and set members come back as Uint8Array unless a text variant exists, such as redis.hgetText.