NodeJS 服务器回调

发布于 2025-01-06 07:31:52 字数 2710 浏览 3 评论 0原文

我正在编写一个nodeJS REST api 服务器,其中包含用于转发部分的express。现在,服务器要做的一部分就是备份不同类型的数据,并且会有备份我将支持的某些类型数据的请求以及我支持的所有请求。为了节省代码重复,我正在考虑从处理备份所有内容的请求中调用所有备份单个数据类型的函数。

个性化数据备份功能。

function verifyUserId(req, res, functionToGoTo) {

    req.mongoClient.collection('syncServiceAccounts', checkForAccount = function (err, collection) {
        collection.find({_id:req.objectID.createFromHexString(req.params.syncServiceUser)}).toArray(function (err, results) {
            if (results.length != 0) {
                functionToGoTo(req, res, results[0].share_key);
            } else {
                res.send(404);
            }
        });
    });
};
    //Set all server contacts as on device
exports.syncServiceContactsSync = function (req, res) {
    console.log('syncServiceContactsSync');
    verifyUserId(req, res, syncServiceContactsSync, sendContactsSyncResponse);
    //verifyUserId(req, res, syncServiceContactsSync);
};
function syncServiceContactsSync(req, res, shareKey, callback) {
//function syncServiceContactsSync(req, res, shareKey) {
    jsonObject = (req.body);
    var jsonResponse = new Array();

    req.mongoClient.collection('syncService_Contacts', insertSyncServiceUser = function (err, collection) {
        collection.remove({share_key:shareKey});

        for (var i = 0; i < jsonObject.length; i++) {
            jsonObject[i].share_key = shareKey;
            collection.insert(jsonObject[i]);
        }

        collection.find({share_key:shareKey}).toArray(function (err, results) {
            for (var i = 0; i < results.length; i++) {
                jsonResponse.push({contactID:results[i]._id});
            }
            //res.json(jsonResponse, 200);
            callback();
        });
    });
};
function sendContactsSyncResponse() {
    res.json(jsonResponse, 200);
}

在下面的函数中,我希望能够调用所有单独的备份类型。

   //Set all server items as on the device
exports.syncServiceSync = function (req, res) {
    console.log('syncServiceSync');
    contactsObj = new Contacts();
    contactsObj.syncService

};

我可以只调用导出的syncServiceContacsSync,它是每种类型数据的等效项,但是当我可以从syncServiceSync 中执行一次时,我会验证每种新数据类型的用户ID。有没有办法做到这一点,并告诉syncServiceContactsSync 在插入数据后要做什么?最好它会与 jsonResponse 一起进入一个函数,在那里我将它级联到下一个数据类型。

另请注意,这两个文件块位于同一文件夹中的不同文件中。

编辑:为了更容易理解。我有一个系统,可以将数据类型 A、B、C 备份到它们自己的 mongo 集合中。我为我的应用程序的注册用户提供了另一个集合。就请求而言,我有一些处理单独备份 A、B、C 的请求,还有一个处理特定用户帐户的所有请求。在处理所有这些的函数中,我认为使用备份 A、B、C 的函数是一个好主意,这样我就不会出现代码重复。因此,我想要的(但最终可能会以不同的方式实现)是,当我想要备份所有数据类型时,我只需调用处理 A 的数据类型,然后级联到处理 A 的数据类型除了简单地级联到每个函数之外,我还想级联一些数据(资源 ID,即 As 的 ID)到处理 B 的函数,然后是处理 B 的 ID A和B进入处理的一个C,然后进入返回所有这些 ID 的最终函数)。我遇到的问题是,现在编写代码的方式,每次级联时,我都会重新检查是否可以在用户集合中找到用户,这有点愚蠢。

I'm writing a nodeJS REST api server with express for the forwarding part. Now part of what the server will do is backup different kinds of data, and there will be requests for backing up certain types of data I'll support and all of the requests that I support. To save on code duplication I was thinking of just calling all of the backup-individual-types-of-data functions from the request that deals with backing up everything.

Individual type of data backup functions.

function verifyUserId(req, res, functionToGoTo) {

    req.mongoClient.collection('syncServiceAccounts', checkForAccount = function (err, collection) {
        collection.find({_id:req.objectID.createFromHexString(req.params.syncServiceUser)}).toArray(function (err, results) {
            if (results.length != 0) {
                functionToGoTo(req, res, results[0].share_key);
            } else {
                res.send(404);
            }
        });
    });
};
    //Set all server contacts as on device
exports.syncServiceContactsSync = function (req, res) {
    console.log('syncServiceContactsSync');
    verifyUserId(req, res, syncServiceContactsSync, sendContactsSyncResponse);
    //verifyUserId(req, res, syncServiceContactsSync);
};
function syncServiceContactsSync(req, res, shareKey, callback) {
//function syncServiceContactsSync(req, res, shareKey) {
    jsonObject = (req.body);
    var jsonResponse = new Array();

    req.mongoClient.collection('syncService_Contacts', insertSyncServiceUser = function (err, collection) {
        collection.remove({share_key:shareKey});

        for (var i = 0; i < jsonObject.length; i++) {
            jsonObject[i].share_key = shareKey;
            collection.insert(jsonObject[i]);
        }

        collection.find({share_key:shareKey}).toArray(function (err, results) {
            for (var i = 0; i < results.length; i++) {
                jsonResponse.push({contactID:results[i]._id});
            }
            //res.json(jsonResponse, 200);
            callback();
        });
    });
};
function sendContactsSyncResponse() {
    res.json(jsonResponse, 200);
}

And in the following function i'd like to be able to just call all the individual backup type.

   //Set all server items as on the device
exports.syncServiceSync = function (req, res) {
    console.log('syncServiceSync');
    contactsObj = new Contacts();
    contactsObj.syncService

};

I could just call the exported syncServiceContacsSync and it's equivalents for each type of data, but then i'd verify the userID for each new type of data, when I could do it once from the syncServiceSync. Is there a way to do that, and tell the syncServiceContactsSync what to do once it has inserted the data? Preferably it would go to a function together with the jsonResponse where I'd cascade it into the next data type.

Also to note that the two blocks of files are in different files in the same folder.

EDIT: To make it easier to understand. I have a system that backs up data type A, B, C, into their own mongo collections. I have another collection for the registered users for my app. In terms of requests, I have some that deal with backing up A, B, C individually and one that deals with all of them for a particular user account. In the one that deals with all of them, I thought it would be a good idea to use the functions that back up A, B, C so I don't have code duplication. As a result, what I'd kind want (but it might end up implemented differently) is that when I want to backup all of the data types, then I'd simply call the one that deals with A, then cascade into the one that deals with B, then the one with C. Besides simply cascading into each function, I'd also like to cascade some data (resource ID, so the IDs of the As, into the function that deals with Bs, then the IDs of A and B into the one that deals with C, and then into a final function that returns all of these IDs). The problem that I have is that the way the code is written now, every time I'd cascade, I'd recheck to see if I can find the user in the user collection, and that's just kinda stupid.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

小…楫夜泊 2025-01-13 07:31:52

我不太确定我完全理解您的问题,但是您是否研究过可用于 Express 路由的 Route Middleware ?更多信息请访问http://expressjs.com/guide.html#route-middleware

它基本上允许您将逻辑插入到请求管道中,以便您可以在一处定义逻辑并将其与多个路由一起使用。

function loadUser(req, res, next) {
  // You would fetch your user from the db
  var user = users[req.params.id];
  if (user) {
    req.user = user;
    next();
  } else {
    next(new Error('Failed to load user ' + req.params.id));
  }
}

app.get('/user/:id', loadUser, function(req, res){
  res.send('Viewing user ' + req.user.name);
});

I'm not quite sure I fully understand your question, but have you looked into Route Middleware that's available with Express routes? More info is available at http://expressjs.com/guide.html#route-middleware.

It basically allows you to insert logic into the request pipeline so that you can define the logic in one place and use it with multiple routes.

function loadUser(req, res, next) {
  // You would fetch your user from the db
  var user = users[req.params.id];
  if (user) {
    req.user = user;
    next();
  } else {
    next(new Error('Failed to load user ' + req.params.id));
  }
}

app.get('/user/:id', loadUser, function(req, res){
  res.send('Viewing user ' + req.user.name);
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文