在 Node.js 中如何合理的调配某些通用实例对象?(如 Redis)

2021-02-03 10:01:12 +08:00
 chogath

一、模块导入的方式:

// redis.ts

export const redis = new ioRedis(options);

// service.ts

import { redis } from './redis'

const func1 = async () => { await redis.get('demo') };

二、egg.js app 全局属性:


module.exports.login = function* (ctx) {
    const {app} = this
    const form = ctx.request.body
    let time = 3600 * 24 * 30 //token 过期时间
    let token = generateToken({_id: form._id}, time)// 生成 token
    app.redis.set(form.username, token) // 把 token 存入 redis

三、Nest.js 依赖注入

// redis.ts

export const redisProviders = {
    provide: 'redis',
    useFactory: async () => {
    redis = new ioRedis(options);
    return redis;
    },
};

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

// service.ts

@Injectable()
export class Service {
  constructor(
    @Inject('redis')
    private readonly redis
  ) {}

  async func1() {
    await this.redis.get('demo')
  }
}


个人倾向于第三种,但是在实际的开发中用的是第一种。按另一个例子 logger 实例来说,logger 有 info / error 等方法来记录日志,在全局启动的时候,也需要 logger 实例,这种情况依赖注入的方式反而成为一种限制。

Node.js 后端开发经验有限,请大家指正。

624 次点击
所在节点    问与答
3 条回复
chogath
2021-02-03 10:16:36 +08:00
现在使用的开发框架是 ts + nest.js ,分成了 lib / modules 两层

lib 用来定义一些公共组件,如 redis 、database 、logger 等。
modules 用来实现业务,其中 controller 、service 、dao 使用的是依赖注入。

如果 modules 层中需要 公共组件,则通过模块引入的方式调用具体方法(如 logger.info
optional
2021-02-03 11:01:03 +08:00
第一种其实也是依赖注入
chogath
2021-02-03 11:48:18 +08:00
@optional emm...

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/750802

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX