如何在nestjs中创建redisservice?

093gszye  于 2021-06-09  发布在  Redis
关注(0)|答案(1)|浏览(503)

我正在使用nest7.1.5和ioredis4.17.3。我正在尝试创建一个redisservice,然后注入它。到目前为止,我掌握的情况如下:
redis.providers.ts

import { Provider } from '@nestjs/common';
import Redis from 'ioredis';
import { REDIS_CLIENT } from './redis.constants';

export type RedisClient = Redis.Redis;

export const redisProviders: Provider[] = [
    {
        useFactory: (): RedisClient => {
            return new Redis({
                host: 'localhost',
                port: 6379,
            });
        },
        provide: REDIS_CLIENT,
    }
]

redis.service.ts

import { Injectable, Inject } from '@nestjs/common';

import { REDIS_CLIENT } from './redis.constants';
import { RedisClient } from './redis.providers';

@Injectable()
export class RedisService {
    public constructor(
        @Inject(REDIS_CLIENT)
        private readonly redisClient: RedisClient,
    ) { }
}

redis.module.ts

import { Module } from '@nestjs/common';
import { redisProviders } from './redis.providers';
import { RedisService } from './redis.service';

@Module({
    providers: [...redisProviders, RedisService],
    exports: [...redisProviders, RedisService],
})
export class RedisModule { }

当我尝试注入此服务时,出现以下错误:

[12:25:57 PM] Found 0 errors. Watching for file changes.

/path/redis-setup/dist/shared/redis/redis.service.js:28
        __metadata("design:paramtypes", [typeof (_a = typeof redis_providers_1.RedisClient !== "undefined" && redis_providers_1.RedisClient) === "function" ? _a : Object])
                                                             ^

ReferenceError: redis_providers_1 is not defined
    at /path/redis-setup/dist/shared/redis/redis.service.js:28:62
    at Object.<anonymous> (/path/redis-setup/dist/shared/redis/redis.service.js:31:3)
    at Module._compile (internal/modules/cjs/loader.js:816:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:827:10)
    at Module.load (internal/modules/cjs/loader.js:685:32)
    at Function.Module._load (internal/modules/cjs/loader.js:620:12)
    at Module.require (internal/modules/cjs/loader.js:723:19)
    at require (internal/modules/cjs/helpers.js:14:16)
    at Object.<anonymous> (/path/redis-setup/dist/app.service.js:14:25)
    at Module._compile (internal/modules/cjs/loader.js:816:30)

我错过了什么?任何帮助或想法都将不胜感激。谢谢您。

ve7v8dk2

ve7v8dk21#

尝试添加 "esModuleInterop": true 在tsconfig.json中

相关问题