V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
chogath
V2EX  ›  程序员

向各位老哥请教下如何更合理的在 nest.js 中使用全局变量

  •  
  •   chogath · 2021-02-20 19:56:28 +08:00 · 1544 次点击
    这是一个创建于 1163 天前的主题,其中的信息可能已经有所发展或是发生改变。

    以配置信息为例,nest.js 文档中提倡的是:注册 ConfigModule 并以依赖注入的方式,注入到其他模块中。

    这样的好处不言而喻,依赖关系和代码都非常清晰,但是如果我的 nest.js 项目中,需要在启动时调用配置中的信息呢?这样反而给我造成了困扰。

    我的想法是使用一个 store (实际上是一个闭包)来管理所有可能在全局需要用到的变量、客户端链接对象,在启动时注册,在需要时引入。

    以这样的方式注册好对应变量时,变量可以在任意地方引入。但是缺点是需要自行管理依赖。

    请各位老哥帮我指正,我还是个菜鸟...


    以上面理念设计的 demo: https://github.com/sophons-space/nest-server

    github issue: https://github.com/nestjs/nest/issues/6460

    stackoverflow: https://stackoverflow.com/questions/66291284/how-to-use-global-variables-in-nest-js

    第 1 条附言  ·  2021-03-16 12:34:39 +08:00
    自己已经解决,还是用的依赖注入。在启动时在 ioc 上下文中获取提供者

    ## 以下是我自己认为的最佳实践
    ##---------------------------------------------------------
    https://github.com/sophons-space/nest-server
    https://github.com/sophons-space/nest-gateway
    https://github.com/sophons-space/nest-user-center

    ## end
    ##---------------------------------------------------------
    1 条回复    2021-02-21 10:51:00 +08:00
    chogath
        1
    chogath  
    OP
       2021-02-21 10:51:00 +08:00
    -0-?
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1211 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 17:58 · PVG 01:58 · LAX 10:58 · JFK 13:58
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.