Skip to content

Instantly share code, notes, and snippets.

@tungd
Last active April 8, 2022 16:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tungd/fc7a79d2389f289e8d474756ece12fe2 to your computer and use it in GitHub Desktop.
Save tungd/fc7a79d2389f289e8d474756ece12fe2 to your computer and use it in GitHub Desktop.
define PROXY_FN
export async function onRequest(context) {
const { request, params, env } = context;
const url = new URL(request.url);
url.host = env.API_HOST;
url.pathname = params.path.join('') === 'json' ? `/api/json` : params.path.join('/');
if (request.method === 'POST' && !request.headers.get('Content-Type')) {
const headers = Object.fromEntries(request.headers.entries())
return fetch(url, {
method: request.method,
headers: {
...headers,
'Content-Type': 'application/json'
},
body: '{}'
});
}
return fetch(url, request);
}
endef
export PROXY_FN
build:
mkdir -p functions/api
echo $$PROXY_FN >> functions/api/[[path]].js
npm run build
clean:
rm -rf dist functions
.PHONY: build clean
PROXY_FN = <<-JS
export async function onRequest(context) {
const { request, params, env } = context;
const url = new URL(request.url);
url.host = env.API_HOST;
url.pathname = params.path.join('') === 'json' ? `/api/json` : params.path.join('/');
if (request.method === 'POST' && !request.headers.get('Content-Type')) {
const headers = Object.fromEntries(request.headers.entries())
return fetch(url, {
method: request.method,
headers: {
...headers,
'Content-Type': 'application/json'
},
body: '{}'
});
}
return fetch(url, request);
}
JS
task :default do
FileUtils.makedirs 'functions/api'
File.write 'functions/api/[[path]].js', PROXY_FN
sh 'npm run build'
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment