听起来您的应用程序耦合度很高;您很难将代码拆分成模块,因为应用程序之间不应该相互依赖。展望OO设计的原则可以帮助在这里。
例如,如果您要将数据删除逻辑从主应用程序中分离出来,则应该能够这样做,因为数据库逻辑不应依赖于
app或
io-它应该能够独立工作,然后将
require其分解为应用程序的其他部分以使用它。
这是一个相当基本的示例-比实际代码更多的伪代码,因为重点是通过示例演示模块化,而不是编写有效的应用程序。它也是您决定应用程序结构的众多方式中的仅一种。
// =============================// db.jsvar mongoose = require('mongoose');mongoose.connect();module.exports = { User: require('./models/user'); OtherModel: require('./models/other_model');};// =============================// models/user.js (similar for models/other_model.js)var mongoose = require('mongoose');var User = new mongoose.Schema({ });module.exports = mongoose.model('User', User);// =============================// routes.jsvar db = require('./db');var User = db.User;var OtherModel = db.OtherModel;// This module exports a function, which we call call with// our Express application and Socket.IO server as arguments// so that we can access them if we need them.module.exports = function(app, io) { app.get('/', function(req, res) { // home page logic ... }); app.post('/users/:id', function(req, res) { User.create(); });};// =============================// realtime.jsvar db = require('./db');var OtherModel = db.OtherModel;module.exports = function(io) { io.sockets.on('connection', function(socket) { socket.on('someEvent', function() { OtherModel.find(); }); });};// =============================// application.jsvar express = require('express');var sio = require('socket.io');var routes = require('./routes');var realtime = require('./realtime');var app = express();var server = http.createServer(app);var io = sio.listen(server);// all your app.use() and app.configure() here...// Load in the routes by calling the function we// exported in routes.jsroutes(app, io);// Similarly with our realtime module.realtime(io);server.listen(8080);
这一切都花在了我头上,而对各种API的文档的检查却很少,但是我希望它能为您从应用程序中提取模块的方法打下基础。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)