function createDispatchProxy({
owner,
repo,
event_type = "event_type",
client_payload = "NOT USED",
secretName = "github_token",
beforeDispatch = (args, ctx) => {},
debug = false
} = {}) {
const ep = endpoint(
dispatchProxyName({ owner, repo, event_type }),
async (req, res, ctx) => {
if (debug) debugger;
if (req.method !== "POST")
return res.status(400).send("Use POST to trigger a dispatch");
if (!ctx.secrets[secretName])
return res
.status(500)
.send(`Cannot find a secret value under ${secretName}`);
const payload =
client_payload === null && req.body
? JSON.parse(req.body)
: client_payload;
const args = {
...arguments[0],
...(payload !== "NOT USED" && { client_payload: payload }),
event_type
};
try {
await beforeDispatch(args, ctx);
const result = await dispatch(ctx.secrets[secretName], args);
res.json(result);
} catch (err) {
res.json({
error: true,
name: err.name,
status: err.status,
message: err.message
});
}
},
{
secrets: [subdomain() + "_" + secretName]
}
);
const url = ep.href;
const view = html`<div>${ep}`;
view.value = async (user_client_payload) => {
if (user_client_payload && client_payload !== null) {
throw new Error(
"Client cannot set client_payload if proxy has a client_payload configured"
);
}
const proxyCall = await fetch(url, {
method: "POST",
body: JSON.stringify(user_client_payload)
});
const result = await proxyCall.json();
if (result.error) {
const err = new Error(result.message);
(err.name = result.name), (err.status = result.status);
throw err;
} else {
return result;
}
};
return view;
}