KoaJS RESTful API

  • 定义和使用

    要创建移动应用程序、单页应用程序、使用 AJAX 调用并向客户机提供数据,您需要一个 API。关于如何构造和命名这些 api 和端点的一种流行的体系结构样式称为 REST(representationaltransferstate)。htp1.1 的设计考虑了 REST 原则。罗伊在 2000 年发表的论文中介绍了这一点。
    restfuluri 和方法为我们提供了处理请求所需的几乎所有信息。下表总结了应该如何使用各种动词以及如何命名 uri。我们将在最后创建一个 movies API,所以让我们来讨论它的结构。
    方法 URL Details Function
    GET /movies Safe, cachable 获取所有电影及其详细信息的列表
    GET /movies/1234 Safe, cachable 获取电影 id=1234 的详细信息
    POST /movies N/A 创建包含提供的详细信息的新电影。响应包含这个新创建的资源的 URI。
    PUT /movies/1234 Idempotent 修改电影 id=1234(如果不存在,则创建一个)。响应包含这个新创建的资源的URI。
    DELETE /movies/1234 Idempotent 如果电影 id=1234 存在,则应将其删除。响应应包含请求的状态。
    DELETE or PUT /movies Invalid 应该是无效的。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 = new koa();
    
    app.use(bodyParser({
        formidable:{uploadDir: './uploads'},
        multipart: true,
        urlencoded: true
    }));
    
    var movies = require('./movies.js');
    
    app.use(movies.routes());
    
    app.listen(3000);
    
    现在我们已经设置了应用程序,让我们集中精力创建 API。首先设置 movies.js 文件。我们没有使用数据库来存储电影,而是将它们存储在内存中,所以每次服务器重新启动时,我们添加的电影都会消失。使用数据库或文件(使用node-fs模块)可以很容易地模拟这一点。
    导入 koa 路由器,创建一个路由器并使用 module.exports.
    var Router = require('koa-router');
    var router = Router({
        prefix: '/movies'
    });  //在所有路线前面加上/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}
    ];
    
    module.exports = router;
    
  • GET Routes

    定义获取所有电影的 GET Routes。
    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; //将状态设置为 404,因为找不到电影
            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 route。现在,让我们转到 POST route。
  • POST Routes

    使用以下路由来处理POST数据。
    router.post('/', addNewMovie);
    
    function *addNewMovie(next){
        //检查是否提供了所有字段并且这些字段都有效:
        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" 
    http://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 Routes

    PUT 路由与 POST 路由几乎完全相同。我们将为将要更新/创建的对象指定ID。通过以下方式创建路由-
    router.put('/:id', updateMovieWithId);
    
    function *updateMovieWithId(next){
        //检查是否提供了所有字段并且这些字段都有效:
        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 {
            //获取具有给定id的电影的索引。
            var updateIndex = movies.map(function(movie){
                return movie.id;
            }).indexOf(parseInt(this.params.id));
            
            if(updateIndex === -1){
                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 {
                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" 
    http://localhost:3000/movies/101
    
    响应
    {"message":"Movie id 101 updated.","location":"/movies/101"}
    
  • DELETE Routes

    使用以下代码创建删除路由。
    router.delete('/:id', deleteMovieWithId);
    function *deleteMovieWithId(next){
        var removeIndex = movies.map(function(movie){
            return movie.id;
        }).indexOf(this.params.id); //获取具有给定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'
    }); 
    
    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}
    ];
    
    
    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) {
        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 {
            var updateIndex = movies.map(function(movie){
                return movie.id;
            }).indexOf(parseInt(this.params.id));
            
            if(updateIndex === -1){
                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 {
                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创建更复杂的应用程序。