Last active
May 11, 2024 02:47
-
-
Save mattfysh/60945a919558b51070e6ad5c2fb3ee2a to your computer and use it in GitHub Desktop.
Express as miniflare wrapper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const express = require('express') | |
const { text } = require('node:stream/consumers') | |
const { Writable } = require('node:stream') | |
const { Miniflare, Log } = require('miniflare') | |
const app = express() | |
const mf = new Miniflare({ | |
script: `addEventListener("fetch", (event) => { | |
event.respondWith(new Response("Hello Miniflare!")); | |
})`, | |
log: new Log(), | |
}) | |
async function forward(worker, req, res) { | |
const url = new URL(req.originalUrl, `http://${req.headers['host']}`) | |
const body = (await text(req)) || undefined | |
const query = await worker.dispatchFetch(url, { | |
method: req.method, | |
headers: req.headers, | |
body, | |
}) | |
const headers = {} | |
for (const [key, value] of query.headers) { | |
headers[key.toLowerCase()] = value | |
} | |
res.writeHead(query.status, query.statusText, headers) | |
if (query.body) { | |
await query.body.pipeTo(Writable.toWeb(res)) | |
} else { | |
res.end() | |
} | |
} | |
app.get('/hello', async (req, res, next) => { | |
try { | |
await forward(mf, req, res) | |
} catch (e) { | |
next(e) | |
} | |
}) | |
app.listen(3456) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { serve } = require('@hono/node-server') | |
const { Hono } = require('hono') | |
const { Miniflare, Log } = require('miniflare') | |
const mf = new Miniflare({ | |
script: `addEventListener("fetch", (event) => { | |
event.respondWith(new Response("Hello Miniflare!")); | |
})`, | |
log: new Log(), | |
}) | |
const app = new Hono() | |
app.get('/hello', async c => | |
mf.dispatchFetch(c.req.url, { | |
method: c.req.method, | |
}) | |
) | |
serve(app, info => { | |
console.log(`Listening on http://localhost:${info.port}`) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment