Koa.js - RESTful API



要建立移動應用程式、單頁應用程式、使用 AJAX 呼叫並向客戶端提供資料,您需要一個 API。一種關於如何構建和命名這些 API 和端點的流行架構風格稱為REST(表述性狀態轉移)。HTTP 1.1 在設計時就考慮了 REST 原則。REST 由Roy Fielding於 2000 年在其論文 Fielding Dissertations 中提出。

RESTful URI 和方法為我們提供了處理請求所需的大部分資訊。下表總結了如何使用各種動詞以及如何命名 URI。我們將在最後建立一個電影 API,因此讓我們討論一下它的結構。

方法 URI 詳情 功能
GET /movies 安全,可快取 獲取所有電影及其詳細資訊的列表
GET /movies/1234 安全,可快取 獲取電影 ID 1234 的詳細資訊
POST /movies N/A 建立一部包含所提供詳細資訊的新電影。響應包含此新建立資源的 URI。
PUT /movies/1234 冪等 修改電影 ID 1234(如果不存在則建立一個)。響應包含此新建立資源的 URI。
DELETE /movies/1234 冪等 如果存在,應刪除電影 ID 1234。響應應包含請求的狀態。
DELETE 或 PUT /movies 無效 應無效。DELETE 和 PUT 應指定它們正在處理哪個資源。

現在讓我們在 Koa 中建立這個 API。我們將使用 JSON 作為我們的傳輸資料格式,因為它易於在 JavaScript 中使用並且具有許多其他好處。將您的 index.js 檔案替換為以下內容 -

INDEX.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。首先設定 movies.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 路由

定義獲取所有電影的 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}

如果您訪問無效路由,它將產生無法獲取錯誤,而如果您訪問具有不存在 ID 的有效路由,它將產生 404 錯誤。

我們完成了 GET 路由。現在,讓我們繼續 POST 路由。

POST 路由

使用以下路由來處理 POST 資料。

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;
}

這將建立一個新的電影並將其儲存在 movies 變數中。要測試此路由,請在您的終端中輸入以下內容 -

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

您將獲得以下響應 -

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

要測試這是否已新增到 movies 物件中,請再次對 /movies/105 執行 get 請求。您將獲得以下響應 -

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

讓我們繼續建立 PUT 和 DELETE 路由。

PUT 路由

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://:3000/movies/101

響應

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

DELETE 路由

使用以下程式碼建立刪除路由。

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."}

最後,我們的 movies.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 建立更復雜的應用程式。

廣告