index.js 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. 'use strict';
  2. const methods = require('methods').map(method => {
  3. return method.toUpperCase();
  4. });
  5. module.exports = options => {
  6. options = options || {};
  7. options.allowedMethods = options.allowedMethods || [ 'POST' ];
  8. return function overrideMethod(ctx, next) {
  9. const orginalMethod = ctx.request.method;
  10. if (options.allowedMethods.indexOf(orginalMethod) === -1) return next();
  11. let method;
  12. // body support
  13. const body = ctx.request.body;
  14. if (body && body._method) {
  15. method = body._method.toUpperCase();
  16. } else {
  17. // header support
  18. const header = ctx.get('x-http-method-override');
  19. if (header) {
  20. method = header.toUpperCase();
  21. }
  22. }
  23. if (method) {
  24. // only allow supported methods
  25. // if you want to support other methods,
  26. // just create your own utility!
  27. if (methods.indexOf(method) === -1) {
  28. ctx.throw(400, `invalid overriden method: "${method}"`);
  29. }
  30. ctx.request.method = method;
  31. }
  32. return next();
  33. };
  34. };