为node.js创建一个动态的restful api

creating a dynamically restful api for node.js

本文关键字:动态 一个 restful api js node 创建      更新时间:2023-09-26

我在node.js应用程序中几乎所有的东西都使用mongodb,现在我想创建一个restful应用程序,所以,我做到了:

我现在正尝试使用get方法:

restApi.js:

var restAPI = {
  get: function(method, model, sort, limit, options) {
    if (method !== 'get') {
      return;
    }
    model.find(options).sort(sort).limit(3).exec(function (error, result) {
      if (error) {
        return error;
      } else {
        return result;
      }
    });
  },
};

现在我可以在我的路线上要求这个:

var restApi=require('restApi');

并像这样使用:

app.get('/', function(req, res, next) {
  var result = restAPI.get('get', Event, 'date', 3, {'isActive': true});
  res.render('/', {
    result: result
  });
});

不起作用,结果未定义。为什么?

如何在带有回调的异步函数中转换它?这是可能的吗?

谢谢!:)

您不会从restApi.get返回任何内容。如果你使用猫鼬,你可以很容易地返回一个Promise:

var restAPI = {
  get: function(method, model, sort, limit, options) {
    if (method !== 'get') {
      return;
    }
    return model.find(options).sort(sort).limit(3).exec();
  },
};

然后你可以这样使用它:

app.get('/', function(req, res, next) {
  restAPI.get('get', Event, 'date', 3, {'isActive': true}).then( function ( result ) {
    res.render('/', {
      result: result
    });
  }).catch( error ) {
    // Render error page and log error      
  });
});

这是因为您的模型是异步的。你必须通过回调。

使用异步方式更好,因为它不会在等待响应时阻塞应用程序。

案例示例:

restApi.js:

var restAPI = {
  get: function(method, model, sort, limit, options, cb) {
    if (method !== 'get') {
      return cb("Method must be GET");
    }
    model.find(options).sort(sort).limit(3).exec(function (error, result) {
      if (error) {
        return cb(error);
      } else {
        return cb(null, result);
      }
    });
  },
};

现在我可以在我的路线上要求这个:

var restApi=require('restApi');

并像这样使用:

app.get('/', function(req, res, next) {
  restAPI.get('get', Event, 'date', 3, {'isActive': true}, function(err, result){
      if(err)
        return res.render("Error:" + err)
      res.render('/', {
        result: result
      });
  });
});

我已经将cb参数添加到REST API函数中,以便在完成模型异步操作时调用它。

路由器处理程序传递它的回调,并在操作完成时打印输出。