没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制宜即可

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

在app/routes/order.js里

  1. var express = require('express');
  2. var router = express.Router();
  3. // mount all middlewares in app/middlewares, examples:
  4. //
  5. // router.route('/')
  6. // .get($middlewares.check_session_is_expired, $.list)
  7. // .post($.create);
  8. //
  9. var $middlewares = require('mount-middlewares')(__dirname);
  10. // core controller
  11. var $ = require('mount-controllers')(__dirname).orders_controller;
  12. /**
  13. * Auto generate RESTful url routes.
  14. *
  15. * URL routes:
  16. *
  17. * GET /orders[/] => order.list()
  18. * GET /orders/new => order.new()
  19. * GET /orders/:id => order.show()
  20. * GET /orders/:id/edit => order.edit()
  21. * POST /orders[/] => order.create()
  22. * PATCH /orders/:id => order.update()
  23. * DELETE /orders/:id => order.destroy()
  24. *
  25. */
  26. router.get('/new', $.new);
  27. router.get('/:id/edit', $.edit);
  28. router.route('/')
  29. .get($.list)
  30. .post($.create);
  31. router.route('/:id')
  32. .patch($.update)
  33. .get($.show)
  34. .delete($.destroy);
  35. module.exports = router;

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

整个世界顿时就清净了

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