widget refactoring and cleanup

This commit is contained in:
Ben Phelps 2022-09-26 02:23:02 +03:00
parent 808e79e2ac
commit 47bc073fb4
39 changed files with 92 additions and 1410 deletions

View file

@ -0,0 +1,40 @@
import useSWR from "swr";
import { useTranslation } from "next-i18next";
import Widget from "components/services/widgets/widget";
import Block from "components/services/widgets/block";
import { formatProxyUrl } from "utils/api-helpers";
export default function Component({ service }) {
const { t } = useTranslation();
const config = service.widget;
const { data: infoData, error: infoError } = useSWR(formatProxyUrl(config, "nginx/proxy-hosts"));
if (infoError) {
return <Widget error={t("widget.api_error")} />;
}
if (!infoData) {
return (
<Widget>
<Block label={t("npm.enabled")} />
<Block label={t("npm.disabled")} />
<Block label={t("npm.total")} />
</Widget>
);
}
const enabled = infoData.filter((c) => c.enabled === 1).length;
const disabled = infoData.filter((c) => c.enabled === 0).length;
const total = infoData.length;
return (
<Widget>
<Block label={t("npm.enabled")} value={enabled} />
<Block label={t("npm.disabled")} value={disabled} />
<Block label={t("npm.total")} value={total} />
</Widget>
);
}

42
src/widgets/npm/proxy.js Normal file
View file

@ -0,0 +1,42 @@
import getServiceWidget from "utils/service-helpers";
import { formatApiCall } from "utils/api-helpers";
import widgets from "widgets/widgets";
export default async function npmProxyHandler(req, res) {
const { group, service, endpoint } = req.query;
if (group && service) {
const widget = await getServiceWidget(group, service);
if (!widgets?.[widget.type]?.api) {
return res.status(403).json({ error: "Service does not support API calls" });
}
if (widget) {
const url = new URL(formatApiCall(widgets[widget.type].api, { endpoint, ...widget }));
const loginUrl = `${widget.url}/api/tokens`;
const body = { identity: widget.username, secret: widget.password };
const authResponse = await fetch(loginUrl, {
method: "POST",
body: JSON.stringify(body),
headers: {
"Content-Type": "application/json",
},
}).then((response) => response.json());
const apiResponse = await fetch(url, {
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${authResponse.token}`,
},
}).then((response) => response.json());
return res.send(apiResponse);
}
}
return res.status(400).json({ error: "Invalid proxy service type" });
}

View file

@ -0,0 +1,8 @@
import npmProxyHandler from "./proxy";
const widget = {
api: "{url}/api/{endpoint}",
proxyHandler: npmProxyHandler,
};
export default widget;