handler.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // src/adapter/cloudflare-pages/handler.ts
  2. import { Context } from "../../context.js";
  3. import { HTTPException } from "../../http-exception.js";
  4. var handle = (app) => (eventContext) => {
  5. return app.fetch(
  6. eventContext.request,
  7. { ...eventContext.env, eventContext },
  8. {
  9. waitUntil: eventContext.waitUntil,
  10. passThroughOnException: eventContext.passThroughOnException,
  11. props: {}
  12. }
  13. );
  14. };
  15. function handleMiddleware(middleware) {
  16. return async (executionCtx) => {
  17. const context = new Context(executionCtx.request, {
  18. env: { ...executionCtx.env, eventContext: executionCtx },
  19. executionCtx
  20. });
  21. let response = void 0;
  22. try {
  23. response = await middleware(context, async () => {
  24. try {
  25. context.res = await executionCtx.next();
  26. } catch (error) {
  27. if (error instanceof Error) {
  28. context.error = error;
  29. } else {
  30. throw error;
  31. }
  32. }
  33. });
  34. } catch (error) {
  35. if (error instanceof Error) {
  36. context.error = error;
  37. } else {
  38. throw error;
  39. }
  40. }
  41. if (response) {
  42. return response;
  43. }
  44. if (context.error instanceof HTTPException) {
  45. return context.error.getResponse();
  46. }
  47. if (context.error) {
  48. throw context.error;
  49. }
  50. return context.res;
  51. };
  52. }
  53. var serveStatic = () => {
  54. return async (c) => {
  55. const env = c.env;
  56. const res = await env.ASSETS.fetch(c.req.raw);
  57. if (res.status === 404) {
  58. return c.notFound();
  59. }
  60. return res;
  61. };
  62. };
  63. export {
  64. handle,
  65. handleMiddleware,
  66. serveStatic
  67. };