ok.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. /**
  2. * 200 (OK) Response
  3. *
  4. * Usage:
  5. * return res.ok();
  6. * return res.ok(data);
  7. * return res.ok(data, 'auth/login');
  8. *
  9. * @param {Object} data
  10. * @param {String|Object} options
  11. * - pass string to render specified view
  12. */
  13. module.exports = function sendOK (data, options) {
  14. // Get access to `req`, `res`, & `sails`
  15. var req = this.req;
  16. var res = this.res;
  17. var sails = req._sails;
  18. sails.log.silly('res.ok() :: Sending 200 ("OK") response');
  19. // Set status code
  20. res.status(200);
  21. // If appropriate, serve data as JSON(P)
  22. if (req.wantsJSON) {
  23. return res.jsonx(data);
  24. }
  25. // If second argument is a string, we take that to mean it refers to a view.
  26. // If it was omitted, use an empty object (`{}`)
  27. options = (typeof options === 'string') ? { view: options } : options || {};
  28. // If a view was provided in options, serve it.
  29. // Otherwise try to guess an appropriate view, or if that doesn't
  30. // work, just send JSON.
  31. if (options.view) {
  32. return res.view(options.view, { data: data });
  33. }
  34. // If no second argument provided, try to serve the implied view,
  35. // but fall back to sending JSON(P) if no view can be inferred.
  36. else return res.guessView({ data: data }, function couldNotGuessView () {
  37. return res.jsonx(data);
  38. });
  39. };