index.js 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. // src/middleware/method-override/index.ts
  2. import { parseBody } from "../../utils/body.js";
  3. var DEFAULT_METHOD_FORM_NAME = "_method";
  4. var methodOverride = (options) => async function methodOverride2(c, next) {
  5. if (c.req.method === "GET") {
  6. return await next();
  7. }
  8. const app = options.app;
  9. if (!(options.header || options.query)) {
  10. const contentType = c.req.header("content-type");
  11. const methodFormName = options.form || DEFAULT_METHOD_FORM_NAME;
  12. const clonedRequest = c.req.raw.clone();
  13. const newRequest = clonedRequest.clone();
  14. if (contentType?.startsWith("multipart/form-data")) {
  15. const form = await clonedRequest.formData();
  16. const method = form.get(methodFormName);
  17. if (method) {
  18. const newForm = await newRequest.formData();
  19. newForm.delete(methodFormName);
  20. const newHeaders = new Headers(clonedRequest.headers);
  21. newHeaders.delete("content-type");
  22. newHeaders.delete("content-length");
  23. const request = new Request(c.req.url, {
  24. body: newForm,
  25. headers: newHeaders,
  26. method
  27. });
  28. return app.fetch(request, c.env, getExecutionCtx(c));
  29. }
  30. }
  31. if (contentType === "application/x-www-form-urlencoded") {
  32. const params = await parseBody(clonedRequest);
  33. const method = params[methodFormName];
  34. if (method) {
  35. delete params[methodFormName];
  36. const newParams = new URLSearchParams(params);
  37. const request = new Request(newRequest, {
  38. body: newParams,
  39. method
  40. });
  41. return app.fetch(request, c.env, getExecutionCtx(c));
  42. }
  43. }
  44. } else if (options.header) {
  45. const headerName = options.header;
  46. const method = c.req.header(headerName);
  47. if (method) {
  48. const newHeaders = new Headers(c.req.raw.headers);
  49. newHeaders.delete(headerName);
  50. const request = new Request(c.req.raw, {
  51. headers: newHeaders,
  52. method
  53. });
  54. return app.fetch(request, c.env, getExecutionCtx(c));
  55. }
  56. } else if (options.query) {
  57. const queryName = options.query;
  58. const method = c.req.query(queryName);
  59. if (method) {
  60. const url = new URL(c.req.url);
  61. url.searchParams.delete(queryName);
  62. const request = new Request(url.toString(), {
  63. body: c.req.raw.body,
  64. headers: c.req.raw.headers,
  65. method
  66. });
  67. return app.fetch(request, c.env, getExecutionCtx(c));
  68. }
  69. }
  70. await next();
  71. };
  72. var getExecutionCtx = (c) => {
  73. let executionCtx;
  74. try {
  75. executionCtx = c.executionCtx;
  76. } catch {
  77. }
  78. return executionCtx;
  79. };
  80. export {
  81. methodOverride
  82. };