Skip to content

Commit

Permalink
Merge pull request #16 from movie-web/dev
Browse files Browse the repository at this point in the history
Simple proxy v2.0.1
  • Loading branch information
binaryoverload authored Oct 16, 2023
2 parents 3e8d413 + 3780266 commit 67a7c55
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 5 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "simple-proxy",
"private": true,
"version": "2.0.0",
"version": "2.0.1",
"scripts": {
"prepare": "nitropack prepare",
"dev": "nitropack dev",
Expand Down
7 changes: 6 additions & 1 deletion src/routes/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { getBodyBuffer } from '@/utils/body';
import {
getProxyHeaders,
getAfterResponseHeaders,
Expand All @@ -11,20 +12,24 @@ export default defineEventHandler(async (event) => {
// parse destination URL
const destination = getQuery<{ destination?: string }>(event).destination;
if (!destination)
return sendJson({
return await sendJson({
event,
status: 400,
data: {
error: 'destination query parameter invalid',
},
});

// read body
const body = await getBodyBuffer(event);

// proxy
cleanupHeadersBeforeProxy(event);
await proxyRequest(event, destination, {
fetchOptions: {
redirect: 'follow',
headers: getProxyHeaders(event.headers),
body,
},
onResponse(outputEvent, response) {
const headers = getAfterResponseHeaders(response.headers, response.url);
Expand Down
13 changes: 13 additions & 0 deletions src/utils/body.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { H3Event } from 'h3';

export function hasBody(event: H3Event) {
const method = event.method.toUpperCase();
return ['PUT', 'POST', 'PATCH', 'DELETE'].includes(method);
}

export async function getBodyBuffer(
event: H3Event,
): Promise<Buffer | undefined> {
if (!hasBody(event)) return;
return await readRawBody(event, false);
}
5 changes: 2 additions & 3 deletions src/utils/sending.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
import { H3Event, EventHandlerRequest } from 'h3';

export function sendJson(ops: {
export async function sendJson(ops: {
event: H3Event<EventHandlerRequest>;
data: Record<string, any>;
status?: number;
}) {
setResponseStatus(ops.event, ops.status ?? 200);
appendResponseHeader(ops.event, 'content-type', 'application/json');
send(ops.event, JSON.stringify(ops.data, null, 2));
await send(ops.event, JSON.stringify(ops.data, null, 2), 'application/json');
}

0 comments on commit 67a7c55

Please sign in to comment.