Koa.js - RESTful API


要创建移动应用程序、单页应用程序、使用 AJAX 调用并向客户端提供数据,您需要一个 API。关于如何构建和命名这些 API 和端点的流行架构风格称为REST(表述性传输状态)。HTTP 1.1 的设计牢记 REST 原则。REST 是由Roy Fielding于 2000 年在他的论文 Fielding Dissertations 中引入的。

RESTful URI 和方法为我们提供了处理请求所需的几乎所有信息。下表总结了各种动词的使用方式以及 URI 的命名方式。我们将在最后创建一个电影 API,所以让我们讨论一下它的结构。

方法 统一资源标识符 细节 功能
得到 /电影 安全、可缓存 获取所有电影及其详细信息的列表
得到 /电影/1234 安全、可缓存 获取电影 id 1234 的详细信息
邮政 /电影 不适用 创建一部提供详细信息的新电影。响应包含此新创建的资源的 URI。
/电影/1234 幂等 修改电影 ID 1234(如果尚不存在则创建一个)。响应包含此新创建的资源的 URI。
删除 /电影/1234 幂等 电影 ID 1234(如果存在)应删除。响应应包含请求的状态。
删除或放置 /电影 无效的 应无效。DELETE 和 PUT 应指定它们正在处理哪个资源。

现在让我们在 Koa 中创建这个 API。我们将使用 JSON 作为传输数据格式,因为它很容易在 JavaScript 中使用,并且具有许多其他优点。将您的 index.js 文件替换为以下内容 -

索引.JS

var koa = require('koa');
var router = require('koa-router');
var bodyParser = require('koa-body');

var app = koa();

//Set up body parsing middleware
app.use(bodyParser({
   formidable:{uploadDir: './uploads'},
   multipart: true,
   urlencoded: true
}));

//Require the Router we defined in movies.js
var movies = require('./movies.js');

//Use the Router on the sub route /movies
app.use(movies.routes());

app.listen(3000);

现在我们已经设置了应用程序,让我们集中精力创建 API。首先设置 movie.js 文件。我们没有使用数据库来存储电影,而是将它们存储在内存中,因此每次服务器重新启动时,我们添加的电影都会消失。这可以很容易地使用数据库或文件(使用节点 fs 模块)来模仿。

导入 koa-router,创建 Router 并使用 module.exports 导出它。

var Router = require('koa-router');
var router = Router({
  prefix: '/movies'
});  //Prefixed all routes with /movies

var movies = [
   {id: 101, name: "Fight Club", year: 1999, rating: 8.1},
   {id: 102, name: "Inception", year: 2010, rating: 8.7},
   {id: 103, name: "The Dark Knight", year: 2008, rating: 9},
   {id: 104, name: "12 Angry Men", year: 1957, rating: 8.9}
];

//Routes will go here

module.exports = router;

获取路线

定义获取所有电影的 GET 路由。

router.get('/', sendMovies);
function *sendMovies(next){
   this.body = movies;
   yield next;
}

就是这样。要测试这是否正常工作,请运行您的应用程序,然后打开终端并输入 -

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET localhost:3000/movies

您将得到以下响应 -

[{"id":101,"name":"Fight 
Club","year":1999,"rating":8.1},{"id":102,"name":"Inception","year":2010,"rating":8.7},
{"id":103,"name":"The Dark Knight","year":2008,"rating":9},{"id":104,"name":"12 Angry 
Men","year":1957,"rating":8.9}]

我们有一条获取所有电影的路线。现在让我们创建一个通过 id 获取特定电影的路由。

router.get('/:id([0-9]{3,})', sendMovieWithId);

function *sendMovieWithId(next){
   var ctx = this;
   var currMovie = movies.filter(function(movie){
      if(movie.id == ctx.params.id){
         return true;
      }
   });
   if(currMovie.length == 1){
      this.body = currMovie[0];
   } else {
      this.response.status = 404;//Set status to 404 as movie was not found
      this.body = {message: "Not Found"};
   }
   yield next;
}

这将根据我们提供的 id 为我们获取电影。要对此进行测试,请在终端中使用以下命令。

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET localhost:3000/movies/101

您将得到如下响应:

{"id":101,"name":"Fight Club","year":1999,"rating":8.1}

如果你访问一个无效的路由,它会产生一个cannot GET错误,而如果你访问一个id不存在的有效路由,它会产生一个404错误。

我们已经完成了 GET 路由。现在,让我们继续讨论 POST 路由。

邮政路线

使用以下路由来处理 POSTed 数据。

router.post('/', addNewMovie);

function *addNewMovie(next){
   //Check if all fields are provided and are valid:
   if(!this.request.body.name || 
      !this.request.body.year.toString().match(/^[0-9]{4}$/g) || 
      !this.request.body.rating.toString().match(/^[0-9]\.[0-9]$/g)){
      
      this.response.status = 400;
      this.body = {message: "Bad Request"};
   } else {
      var newId = movies[movies.length-1].id+1;
      
      movies.push({
         id: newId,
         name: this.request.body.name,
         year: this.request.body.year,
         rating: this.request.body.rating
      });
      this.body = {message: "New movie created.", location: "/movies/" + newId};
   }
   yield next;
}

这将创建一部新电影并将其存储在电影变量中。要测试此路线,请在终端中输入以下内容 -

curl -X POST --data "name = Toy%20story&year = 1995&rating = 8.5" 
https://localhost:3000/movies

您将得到以下响应 -

{"message":"New movie created.","location":"/movies/105"}

要测试是否已将其添加到 movie 对象,请再次运行 /movies/105 的 get 请求。您将得到以下响应 -

{"id":105,"name":"Toy story","year":"1995","rating":"8.5"}

让我们继续创建 PUT 和 DELETE 路由。

放置路线

PUT 路由与 POST 路由几乎完全相同。我们将为要更新/创建的对象指定 id。按以下方式创建路线 -

router.put('/:id', updateMovieWithId);

function *updateMovieWithId(next){
   //Check if all fields are provided and are valid:
   if(!this.request.body.name || 
      !this.request.body.year.toString().match(/^[0-9]{4}$/g) || 
      !this.request.body.rating.toString().match(/^[0-9]\.[0-9]$/g) ||
      !this.params.id.toString().match(/^[0-9]{3,}$/g)){
      
      this.response.status = 400;
      this.body = {message: "Bad Request"};
   } else {
      //Gets us the index of movie with given id.
      var updateIndex = movies.map(function(movie){
         return movie.id;
      }).indexOf(parseInt(this.params.id));
      
      if(updateIndex === -1){
         //Movie not found, create new movies.push({
            id: this.params.id,
            name: this.request.body.name,
            year: this.request.body.year,
            rating: this.request.body.rating
         });
         this.body = {message: "New movie created.", location: "/movies/" + this.params.id};    
      } else {
         //Update existing movie
         movies[updateIndex] = {
            id: this.params.id,
            name: this.request.body.name,
            year: this.request.body.year,
            rating: this.request.body.rating
         };
         this.body = {message: "Movie id " + this.params.id + " updated.", location: "/movies/" + this.params.id};
      }
   }
}

该路由将执行我们在上表中指定的功能。如果对象存在,它将使用新详细信息更新该对象。如果它不存在,它将创建一个新对象。要测试此路由,请使用以下curl命令。这将更新现有的电影。要创建新电影,只需将 id 更改为不存在的 id 即可。

curl -X PUT --data "name = Toy%20story&year = 1995&rating = 8.5" 
https://localhost:3000/movies/101

回复

{"message":"Movie id 101 updated.","location":"/movies/101"}

删除路线

使用以下代码创建删除路由。

router.delete('/:id', deleteMovieWithId);

function *deleteMovieWithId(next){
   var removeIndex = movies.map(function(movie){
      return movie.id;
   }).indexOf(this.params.id); //Gets us the index of movie with given id.
   
   if(removeIndex === -1){
      this.body = {message: "Not found"};
   } else {
      movies.splice(removeIndex, 1);
      this.body = {message: "Movie id " + this.params.id + " removed."};
   }
}

按照我们对其他路线所做的相同方式测试该路线。成功删除后(例如 id 105),您将得到 -

{message: "Movie id 105 removed."}

最后,我们的 movie.js 文件如下所示 -

var Router = require('koa-router');
var router = Router({
   prefix: '/movies'
});  //Prefixed all routes with /movies
var movies = [
   {id: 101, name: "Fight Club", year: 1999, rating: 8.1},
   {id: 102, name: "Inception", year: 2010, rating: 8.7},
   {id: 103, name: "The Dark Knight", year: 2008, rating: 9},
   {id: 104, name: "12 Angry Men", year: 1957, rating: 8.9}
];

//Routes will go here
router.get('/', sendMovies);
router.get('/:id([0-9]{3,})', sendMovieWithId);
router.post('/', addNewMovie);
router.put('/:id', updateMovieWithId);
router.delete('/:id', deleteMovieWithId);

function *deleteMovieWithId(next){
   var removeIndex = movies.map(function(movie){
      return movie.id;
   }).indexOf(this.params.id); //Gets us the index of movie with given id.
   
   if(removeIndex === -1){
      this.body = {message: "Not found"};
   } else {
      movies.splice(removeIndex, 1);
      this.body = {message: "Movie id " + this.params.id + " removed."};
   }
}

function *updateMovieWithId(next) {
   //Check if all fields are provided and are valid:
   if(!this.request.body.name ||
      !this.request.body.year.toString().match(/^[0-9]{4}$/g) ||
      !this.request.body.rating.toString().match(/^[0-9]\.[0-9]$/g) ||
      !this.params.id.toString().match(/^[0-9]{3,}$/g)){
      
      this.response.status = 400;
      this.body = {message: "Bad Request"};
   } else {
      //Gets us the index of movie with given id.
      var updateIndex = movies.map(function(movie){
         return movie.id;
      }).indexOf(parseInt(this.params.id));
      
      if(updateIndex === -1){
         //Movie not found, create new
         movies.push({
            id: this.params.id,
            name: this.request.body.name,
            year: this.request.body.year,
            rating: this.request.body.rating
         });
         this.body = {message: "New movie created.", location: "/movies/" + this.params.id};
      } else {
         //Update existing movie
            movies[updateIndex] = {
            id: this.params.id,
            name: this.request.body.name,
            year: this.request.body.year,
            rating: this.request.body.rating
         };
         this.body = {message: "Movie id " + this.params.id + " updated.", 
            location: "/movies/" + this.params.id};
      }
   }
}

function *addNewMovie(next){
   //Check if all fields are provided and are valid:
   if(!this.request.body.name ||
      !this.request.body.year.toString().match(/^[0-9]{4}$/g) ||
      !this.request.body.rating.toString().match(/^[0-9]\.[0-9]$/g)){
      
      this.response.status = 400;
      this.body = {message: "Bad Request"};
   } else {
      var newId = movies[movies.length-1].id+1;
      
      movies.push({
         id: newId,
         name: this.request.body.name,
         year: this.request.body.year,
         rating: this.request.body.rating
      });
      this.body = {message: "New movie created.", location: "/movies/" + newId};
   }
   yield next;
}
function *sendMovies(next){
   this.body = movies;
   yield next;
}
function *sendMovieWithId(next){
   var ctx = this
   
   var currMovie = movies.filter(function(movie){
      if(movie.id == ctx.params.id){
         return true;
      }
   });
   if(currMovie.length == 1){
      this.body = currMovie[0];
   } else {
      this.response.status = 404;//Set status to 404 as movie was not found
      this.body = {message: "Not Found"};
   }
   yield next;
}
module.exports = router;

这样就完成了我们的 REST API。现在,您可以使用这种简单的架构风格和 Koa 创建更复杂的应用程序。