Skip to content

Commit

Permalink
feat: handle native Response
Browse files Browse the repository at this point in the history
  • Loading branch information
Hebilicious committed Jun 12, 2023
1 parent 8786eae commit 1a635f0
Showing 1 changed file with 40 additions and 13 deletions.
53 changes: 40 additions & 13 deletions test/fixture/actions/action.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,28 +3,55 @@ import {
type EventHandler,
type H3Event,
defineEventHandler,
readBody
} from 'h3'
readBody,
} from "h3";

interface Actions {
[key: string]: EventHandler
[key: string]: EventHandler;
}

function defineFormActions (actions: Actions) {
function defineFormActions(actions: Actions) {
return (event: H3Event) => {
const action = Object.keys(getQuery(event))[0]
const handler = action ? actions[action] : Object.values(actions)[0]
return defineEventHandler(handler(event))
const action = Object.keys(getQuery(event))[0];
const handler = action ? actions[action] : Object.values(actions)[0];
return defineEventHandler(handler(event));
};
}

async function respondWithResponse(event: H3Event, response: Response) {
// @ts-expect-error
for (const [key, value] of response.headers) {
event.node.res.setHeader(key, value);
}

if (response.body) {
const contentType = response.headers.get("Content-Type") || "";
if (contentType.includes("text") || contentType.includes("json")) {
for await (const chunk of response.body as unknown as AsyncIterable<Uint8Array>) {
const stringChunk = new TextDecoder().decode(chunk); // Convert chunk to string
event.node.res.write(stringChunk);
}
} else {
// for binary data like images, videos, etc.
for await (const chunk of response.body as unknown as AsyncIterable<Uint8Array>) {
event.node.res.write(chunk);
}
}
}
return event.node.res.end();
}

function actionResponse(event: H3Event, data: any, action?: any) {
return { data, action }
// return { data, action };
return respondWithResponse(
event,
new Response(JSON.stringify({ data, action }))
);
}

export default defineFormActions({
default: async event => {
const body = await readBody(event)
return actionResponse(event, { ...body })
}
})
default: async (event) => {
const body = await readBody(event);
return actionResponse(event, { ...body });
},
});

0 comments on commit 1a635f0

Please sign in to comment.