redis-om-node icon indicating copy to clipboard operation
redis-om-node copied to clipboard

[question] How to properly create a Redis-OM repository with TypeScript?

Open FrancescoDiMuro opened this issue 3 months ago • 0 comments

Hi guys. For many might be a silly question, but let me give you some context. I'm currently working with Nest.js, and I've created a RedisOmService which uses an existing RedisService through dependency injection.

import {
  Injectable,
  InternalServerErrorException,
  OnModuleInit,
  OnModuleDestroy,
} from '@nestjs/common';
import { createClient, RedisClientType } from 'redis';

@Injectable()
export class RedisService implements OnModuleInit, OnModuleDestroy {
  private redisClient: RedisClientType;

  async onModuleInit() {
    this.redisClient = createClient({
      url: process.env.REDIS_SERVER_URL,
    });

    await this.redisClient
      .on('error', (error) => {
        throw new InternalServerErrorException(`Redis client error: ${error}`);
      })
      .connect();
  }

  async onModuleDestroy() {
    // Gracefully close the connection with the client,
    // waiting for pending commands to finish their execution
    await this.redisClient.close();
  }

  get client() {
    return this.redisClient;
  }
}

Now, beside the really basic implementation of the RedisService, I use it in the RedisOmService like so:

import { Injectable, OnModuleInit } from '@nestjs/common';
import { RedisClientConnection, Repository } from 'redis-om';
import { RedisService } from 'src/redis/redis.service';
import { detailedProcessConfigurationSchema } from './schemas/detailed-process-configuration.schema';

@Injectable()
export class RedisOmService implements OnModuleInit {
  constructor(private readonly redisService: RedisService) {}

  private readonly schemas = [detailedProcessConfigurationSchema];

  private repositories: Repository[] = [];

  onModuleInit() {
    for (const schema of this.schemas) {
      this.repositories.push(
        new Repository(
          schema,
          this.redisService.client as unknown as RedisClientConnection,
        ),
      );
    }

    this.redisService.client['repositories'] = this.repositories;
  }
}

Even here, the implementation is just to see how things work. The point I'd like to focus on is this line of code:

this.redisService.client as unknown as RedisClientConnection,

Basically, from the RedisOM documentation, we can use the object returned by the createClient() function, which returns a RedisClientType object. Although this is what the documentation says, that's not compatible with what RedisOM requires, which is a Client (deprecated) or a RedisConnection object, which are not returned by the createClient() function. So, my question is: "Is there any chance to not double cast the RedisClientType returned by the createClient() function to create a Redis-OM repository? Thank you in advance.

FrancescoDiMuro avatar Sep 12 '25 22:09 FrancescoDiMuro