feat: modernize widget experience
This commit is contained in:
198 files changed
+4209
-2295
No files matched your search
@@ -1,22 +1,27 @@
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import superjson from "superjson";
|
||||
import { z } from "zod/v4";
|
||||
import { parse } from "superjson";
|
||||
|
||||
import { createId } from "@homarr/common";
|
||||
import { decryptSecret } from "@homarr/common/server";
|
||||
import { customWidgetDefinitions } from "@homarr/db/schema";
|
||||
import { eq } from "@homarr/db";
|
||||
import { createLogger } from "@homarr/core/infrastructure/logs";
|
||||
import { createTRPCRouter, protectedProcedure } from "../../trpc";
|
||||
import { applyAuth } from "../custom-widget/auth";
|
||||
import { assertCustomApiItemBindingAsync, customApiItemInputSchema } from "../custom-widget/custom-widget-access";
|
||||
import { extractActionButtonDisplay, extractDisplayDataWithFallback } from "../custom-widget/display-data";
|
||||
import { readBoundedJsonResponseAsync, validateCustomApiUrl } from "./custom-api-security";
|
||||
import {
|
||||
consumeBoundedResponseAsync,
|
||||
readBoundedJsonResponseAsync,
|
||||
validateCustomApiUrl,
|
||||
withCustomApiResponseAsync,
|
||||
} from "./custom-api-security";
|
||||
|
||||
const logger = createLogger({ module: "widget:customApi" });
|
||||
|
||||
const FETCH_TIMEOUT_MS = 10_000;
|
||||
|
||||
export const customApiRouter = createTRPCRouter({
|
||||
getData: protectedProcedure.input(z.object({ definitionId: z.string() })).query(async ({ ctx, input }) => {
|
||||
getData: protectedProcedure.input(customApiItemInputSchema).query(async ({ ctx, input }) => {
|
||||
await assertCustomApiItemBindingAsync(ctx, input, "view");
|
||||
const definition = await ctx.db.query.customWidgetDefinitions.findFirst({
|
||||
where: eq(customWidgetDefinitions.id, input.definitionId),
|
||||
with: { secrets: true },
|
||||
@@ -32,59 +37,52 @@ export const customApiRouter = createTRPCRouter({
|
||||
|
||||
let displayConfig: Record<string, unknown>;
|
||||
try {
|
||||
displayConfig = superjson.parse(definition.displayConfig) as Record<string, unknown>;
|
||||
displayConfig = parse(definition.displayConfig) as Record<string, unknown>;
|
||||
} catch {
|
||||
throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", message: "Widget has corrupt display configuration" });
|
||||
}
|
||||
|
||||
if (definition.displayType === "actionButton") {
|
||||
return extractActionButtonDisplay(displayConfig);
|
||||
const actionDisplay = extractActionButtonDisplay(displayConfig);
|
||||
return {
|
||||
...actionDisplay,
|
||||
canExecute: ctx.session.user.permissions.includes("admin"),
|
||||
};
|
||||
}
|
||||
|
||||
const decryptedSecrets = definition.secrets.map((s) => ({
|
||||
kind: s.kind,
|
||||
value: decryptSecret(s.value),
|
||||
}));
|
||||
|
||||
const url = validateCustomApiUrl(definition.url);
|
||||
const headers = new Headers({ Accept: "application/json" });
|
||||
|
||||
if (definition.method !== "GET" && definition.requestBody) {
|
||||
headers.set("Content-Type", "application/json");
|
||||
}
|
||||
|
||||
applyAuth(headers, url, definition.authType, decryptedSecrets, definition.headerName);
|
||||
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
|
||||
|
||||
try {
|
||||
const response = await fetch(url.toString(), {
|
||||
method: definition.method,
|
||||
headers,
|
||||
body: definition.method !== "GET" ? definition.requestBody : undefined,
|
||||
redirect: "error",
|
||||
signal: controller.signal,
|
||||
});
|
||||
const decryptedSecrets = definition.secrets.map((s) => ({
|
||||
kind: s.kind,
|
||||
value: decryptSecret(s.value),
|
||||
}));
|
||||
const url = validateCustomApiUrl(definition.url);
|
||||
const headers = new Headers({ Accept: "application/json" });
|
||||
if (definition.method !== "GET" && definition.requestBody) headers.set("Content-Type", "application/json");
|
||||
applyAuth(headers, url, definition.authType, decryptedSecrets, definition.headerName);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new TRPCError({
|
||||
code: "BAD_REQUEST",
|
||||
message: `API returned ${response.status}: ${response.statusText}`,
|
||||
});
|
||||
}
|
||||
|
||||
const json = await readBoundedJsonResponseAsync(response);
|
||||
return extractDisplayDataWithFallback(json, definition.displayType, displayConfig);
|
||||
return await withCustomApiResponseAsync(
|
||||
url,
|
||||
{
|
||||
method: definition.method,
|
||||
headers,
|
||||
body: definition.method !== "GET" ? definition.requestBody : undefined,
|
||||
},
|
||||
async (response) => {
|
||||
if (!response.ok) {
|
||||
await consumeBoundedResponseAsync(response);
|
||||
throw new Error(`Custom API returned HTTP ${response.status}`);
|
||||
}
|
||||
const json = await readBoundedJsonResponseAsync(response);
|
||||
return extractDisplayDataWithFallback(json, definition.displayType, displayConfig);
|
||||
},
|
||||
);
|
||||
} catch (error) {
|
||||
if (error instanceof TRPCError) throw error;
|
||||
logger.error("Failed to fetch custom API data", { definitionId: input.definitionId, error });
|
||||
const errorId = createId();
|
||||
logger.error("Failed to fetch custom API data", { errorId, definitionId: input.definitionId, error });
|
||||
throw new TRPCError({
|
||||
code: "INTERNAL_SERVER_ERROR",
|
||||
message: error instanceof Error ? error.message : "Failed to fetch data from external API",
|
||||
message: "Custom API request failed",
|
||||
});
|
||||
} finally {
|
||||
clearTimeout(timeout);
|
||||
}
|
||||
}),
|
||||
});
|
||||
Reference in new issue
Block a user