没rest怎么行?

曾经rest被吹的玄之又玄,唯恐不谈rest就没有x格,其实rest理解起来还是蛮简单的

最简单的入门是理解crud方法,参考rails的scaffold即可

  1. rails g scaffold user name:string password:string

打印路由

  1. blog git:(master) rake routes
  2. Prefix Verb URI Pattern Controller#Action
  3. users GET /users(.:format) users#index
  4. POST /users(.:format) users#create
  5. new_user GET /users/new(.:format) users#new
  6. edit_user GET /users/:id/edit(.:format) users#edit
  7. user GET /users/:id(.:format) users#show
  8. PATCH /users/:id(.:format) users#update
  9. PUT /users/:id(.:format) users#update
  10. DELETE /users/:id(.:format) users#destroy

是不是代码非常清晰?

既然它是最佳实践,我们也没必要再自己搞一套,只需要因express/koa制宜即可

  • GET /locations[/] => location.list()
  • GET /locations/new => location.new()
  • GET /locations/:id => location.show()
  • GET /locations/:id/edit => location.edit()
  • POST /locations[/] => location.create()
  • PATCH /locations/:id => location.update()
  • DELETE /locations/:id => location.destroy()

在app/routes/locations.js里

  1. "use strict";
  2. var router = require('koa-router')();
  3. const co = require('co');
  4. var $middlewares = require('mount-middlewares')(__dirname);
  5. // core controller
  6. var $ = require('mount-controllers')(__dirname).locations_controller;
  7. /**
  8. * Auto generate RESTful url routes.
  9. *
  10. * URL routes:
  11. *
  12. * GET /locations[/] => location.list()
  13. * GET /locations/new => location.new()
  14. * GET /locations/:id => location.show()
  15. * GET /locations/:id/edit => location.edit()
  16. * POST /locations[/] => location.create()
  17. * PATCH /locations/:id => location.update()
  18. * DELETE /locations/:id => location.destroy()
  19. *
  20. */
  21. router.get('/new', $.new);
  22. router.get('/:id/edit', $.edit);
  23. router.get('/', $.list);
  24. router.post('/', $.create);
  25. router.get('/:id', $.show);
  26. router.patch('/:id', $.update);
  27. router.delete('/:id', $.destroy);
  28. // -- custom routes
  29. module.exports = router;

于是所有东西就都丢到controller里去。

整个世界顿时就清净了

有了Rest,格调也有了。。。。