多环境Express Api

Muz*_*eer 5 javascript node.js express

我正在开发基于Express框架的多环境API.我想要的是保持我的配置动态,例如,这个Api将能够同时为移动应用程序和Web应用程序提供服务.如果请求来自移动源, config-app-1.json则应包括在内,否则config-app-2.json.

目前,我有config-app-1.json,config-app-2.json,config-db-1.json,config-db-2.jsonconfigManager.js这台在所需的配置类app.listen().在其他应用程序模块中,我需要configManager并使用必要的配置.然而,这导致各个功能中的代码重复问题.每个函数都必须在其本地范围内引用db和application设置.

我想知道使用Express框架进行多环境API构建的最佳实践是什么.

Bam*_*ieh 1

这些是配置文件,这是我的方法。

\n\n

文件结构

\n\n
.\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80  app.js\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 _configs\n|   \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 configManager.js\n|   \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 database.js\n|   \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 platform\n|       \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 mobile.js\n|       \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 desktop.js\n
Run Code Online (Sandbox Code Playgroud)\n\n

环境配置

\n\n

配置文件是每个设备的 js 模块,然后 configManager 根据设备处理哪个是活动的。

\n\n
//mobile.js example\nmodule.exports = {\n    device: \'mobile\',\n    configVar: 3000,\n    urls: {\n        base: \'DEVICE_SPECIFIC_BASE_URL\',\n        api: \'DEVICE_SPECIFIC_BASE_URL\'\n    },\n    mixpanelKey: \'DEVICE_SPECIFIC_BASE_URL\',\n    apiKey: "DEVICE_SPECIFIC_BASE_URL",\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

数据库配置

\n\n

数据库配置应该集中化。

\n\n

通常您可以连接到同一节点实例中的多个数据库,但不建议这样做。如果您绝对必须,只需使用两个对象(而不是“mongodb”替换为“mobileMongoDb”和“desktopMongoDb”),但我建议您使用一个数据库并将其分为两个主要文档,或者使用在您的平台中设置的某些前缀-特定配置。

\n\n
// databse.js example\nmodule.exports= {\n  mongodb: {\n  host      : \'localhost\',\n  port      : 27017,\n  user      : \'\',\n  password  : \'\',\n  database  : \'DB_NAME\'\n  },\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

configManager.js(将东西放在一起)

\n\n

这是一个简单的文件,仅供演示之用。

\n\n
var userAgent = req.headers[\'User-Agent\'];\nvar isMobile = /Mobile|Android|/i.test(userAgent);\n\n\n\n// require them all to be cached when you run node.\nvar configs = {\n   mobile: require(\'./platform/mobile\' ),\n   desktop: require(\'./platform/desktop\' )\n}\nvar activeConfig = isMobile? configs.mobile : configs.desktop;\nvar dbConfigs = require(\'./databse\');\n\n\nvar mongoose = require(\'mongoose\');\nvar express = require(\'express\');\nvar app = express();\n\napp.get(\'/\', function (req, res) {\n   var finalresp = \'Hello from \';\n   finalresp += isMobile? \'mobile\' : \'desktop;\n   finalresp += activeConfig.configVar;\n   res.send(finalresp);\n});\n\nmongoose.connect(dbConfigs.mongodb.host, function(err) {  \n   if(isMobile) { /* ... */ }\n});\n
Run Code Online (Sandbox Code Playgroud)\n\n

从标题检测手机

\n\n

在这里阅读更多信息https://gist.github.com/dalethedeveloper/1503252

\n