# @theorchard/dataloader-redis-zod

A wrapping DataLoader that reads & writes to Redis in bulk. Uses a Zod schema for verifying the data returned from Redis and from the internal dataloader.

## Usage

```ts
const EXPIRY = ...;
const myZodSchema = z.(...);

const myDataLoader = new RedisZodDataLoader(
    new DataLoader(...), // Any dataloader
    myZodSchema,
    redisClient,
    {
        cacheKeyFn: (key) => `prefix:${key}`,
        expiry: EXPIRY,
    }
);
```

## Basic Behaviour

Request flow when loading new values:

### 1. Fetch & Validate from Redis:

Using the cacheKeyFn to transform the key, the value is requested from Redis. This value is then verified against the Zod schema provided. In the case that the value is verified then the dataloader returns this value directly.

### 2. Fetch & Validate from the passed-in DataLoader:

Using the DataLoader passed in, the the key is requested to be loaded. The returned value is then validated against the Zod schema provided. If this fails, an error is returned. Otherwise, the value continues to step 3.

### 3. Write new value to Redis

Using the value loaded from the passed in DataLoader, the value is written to Redis with the `expiry` value passed in to the options object.

## Advanced options

### `writeOnly`

If `writeOnly` is set to `true` in the options, then step 1. is disabled, resulting in freshly requesting data. This is useful if you have some clients that want cached data and some clients that require up-to-date data at all times. The DataLoader still writes to Redis in this case which results in any outdated cached values being flushed automatically.

### `shouldWriteToRedis`

This function modifies step 3 to control when data is written to Redis. The default behavior is to write only non-nullish data to Redis. This is to avoid caching `null` results that may be because of replication delay or similar temporal issues.

If you want to override this, you can pass a function to this option that specifies the behavior. Both the key and value are passed to the function to allow you to control the behaviour depending on either.
