Koajs-restful-apis
Koa.js-RESTful API
モバイルアプリケーション、シングルページアプリケーションを作成し、AJAX呼び出しを使用してクライアントにデータを提供するには、APIが必要です。 これらのAPIとエンドポイントを構造化して名前を付ける方法の一般的なアーキテクチャスタイルは、* REST(Representational Transfer State)と呼ばれます。 HTTP 1.1は、RESTの原則を念頭に置いて設計されました。 RESTは、2000年に彼の論文Fielding Dissertationsで *Roy Fielding によって紹介されました。
RESTful URIとメソッドは、リクエストの処理に必要なほぼすべての情報を提供します。 次の表は、さまざまな動詞の使用方法とURIの命名方法をまとめたものです。 最後に向けて映画APIを作成するので、どのように構成するかについて説明しましょう。
Method | URI | Details | Function |
---|---|---|---|
GET | /movies | Safe, cachable | Gets the list of all movies and their details |
GET | /movies/1234 | Safe, cachable | Gets the details of Movie id 1234 |
POST | /movies | N/A | Creates a new movie with details provided. Response contains the URI for this newly created resource. |
PUT | /movies/1234 | Idempotent | Modifies movie id 1234 (creates one if it doesn’t already exist). Response contains the URI for this newly created resource. |
DELETE | /movies/1234 | Idempotent | Movie id 1234 should be deleted, if it exists. Response should contain the status of request. |
DELETE or PUT | /movies | Invalid | Should be invalid. DELETE and PUT should specify which resource they are working on. |
次に、このAPIをKoaで作成しましょう。 JavaScriptでの操作が簡単で、他にも多くの利点があるため、トランスポートデータ形式としてJSONを使用します。 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ファイルをセットアップします。 データベースを使用して映画を保存するのではなく、メモリに保存しているため、サーバーが再起動するたびに、追加された映画は消えます。 これは、データベースまたはファイルを使用して(node fsモジュールを使用して)簡単に模倣できます。
koa-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}
無効なルートにアクセスすると、GETエラーは発生しませんが、存在しない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://localhost:3000/movies
あなたは次の応答を取得します-
{"message":"New movie created.","location":"/movies/105"}
これがムービーオブジェクトに追加されたかどうかをテストするには、/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://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."}
最後に、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を使用して、はるかに複雑なアプリケーションを作成できるようになりました。