no7*_*7dw 6 mongoose mongodb node.js mongoose-schema
假设我有3个node.js项目(1个应用后端,1个应用管理员后端,1个分析api)。在每个项目中,我都有一个模型架构调用贷款。
{
attributes: {
userId: { type: String, required: true, index: true, ref: 'users', comment: '??id' },
amount: { type: Number, required: true, min: 0},
totalAmount: { type: Number, required: true, min: 0},
penaltyInterest: { type: Number, min: 0, required: true, default:
0 }
}
methods: {
getFee () {//some calculation ops
}
save() {//some db ops
}
sendTo3rdComponent() {//some network ops
}
}
Run Code Online (Sandbox Code Playgroud)
该模型具有:一些方法,它是模式设计,api实现。如何在其他两个项目中重复使用它。
对于多个项目重用设计和api是非常重要的。
通常,我们通过将其作为npm包公开来重用该组件。但是,此组件具有自己的数据库操作和网络操作。是否可以将其作为npm软件包?
另一种选择是像eggjs
那么,复制粘贴旁边的优雅解决方案是什么?
Jos*_*hin 11
我不会建议你发布一个已发布的 npm 包的原因是,作为一个优秀的 NodeJS 开发者,你不应该用对其他人没有帮助的包来污染 npm。除非你是付费 npm 用户,可以访问私有包选项。
你知道package.json支持 git urls,你可以阅读 @ Git URLs as Dependencies
git url 的几个例子 package.json
// github url
git+ssh://git@github.com:example/example-repo.git#v1.0.0
// bitbucket url
git+ssh://git@bitbucket.org/example/example-repo.git#v1.0.0
Run Code Online (Sandbox Code Playgroud)
我的建议是创建一个带有 API 的单独包来设置配置,在像您这样的场景中,这将是与数据库连接相关的东西。将其上传到私有 git repo 并在所有应用程序中使用私有 git repo url。然后在应用程序初始化阶段配置包并使用其 API。
现在,应用程序可以构建在任何可以访问私有存储库并可以重用代码的系统上。
您还可以将您的包放在公共存储库上,以防您无法访问私有存储库,这仍然比发布 npm 包以便在您的应用程序之间共享它更好。
小智 5
您可以创建另一个包含通用模型的包,然后将其推送到私有 git 存储库,或者如果您愿意的话,也可以将其推送到公共存储库。然后使用 package.json 中的 git 存储库 url 而不是将其发布到 NPM。假设您将其命名为 models-repo。
它可以是一个简单的包,包括:
??? README.md
??? index.js
??? models
? ??? carLoan.js
??? package.json
Run Code Online (Sandbox Code Playgroud)
您可以使用 git URL 将其包含在应用程序的 package.json 文件中:
{ "models-repo" : "git+ssh://git@models-repo-path.git" }
Run Code Online (Sandbox Code Playgroud)
现在你可以在任何文件中 require 它并开始使用它:
const models = require('models-repo');
const carLoanModel = models.car_loan;
//Do something
carLoanModel.find({})
Run Code Online (Sandbox Code Playgroud)
在生产中使用它时需要小心权限。
您绝对可以将它们放入包装中并重复使用。为了拥有自己的 DB Ops 和 Network Ops,您可以在启动项目时将 DB URL 作为环境变量。并在连接到数据库时使用 process.env.$variable 中的相同内容。
| 归档时间: |
|
| 查看次数: |
1052 次 |
| 最近记录: |