Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,15 +70,27 @@ export function saveAuthConfig(url: string, token: string): void {
fs.writeFileSync(configPath, JSON.stringify({ url, token }, null, 2));
}

export function extractApiErrorMessage(data: unknown): string | undefined {
const d = data as any;
const message = d?.error?.json?.message ?? d?.error?.message ?? d?.message;
return typeof message === "string" && message ? message : undefined;
}

export function createClient(): AxiosInstance {
const auth = readAuthConfig();
return axios.create({
const client = axios.create({
baseURL: `${auth.url}/api`,
headers: {
"x-api-key": auth.token,
"Content-Type": "application/json",
},
});
client.interceptors.response.use(undefined, (error) => {
const detail = extractApiErrorMessage(error?.response?.data);
if (detail) error.message = `${error.message}: ${detail}`;
return Promise.reject(error);
});
return client;
}

export async function apiPost(
Expand Down
35 changes: 35 additions & 0 deletions tests/client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,3 +54,38 @@ describe("saveAuthConfig", () => {
expect(typeof saveAuthConfig).toBe("function");
});
});

describe("extractApiErrorMessage", () => {
it("should read tRPC and plain error bodies", async () => {
const { extractApiErrorMessage } = await import("../src/client.js");

expect(
extractApiErrorMessage({ error: { json: { message: "Not found" } } }),
).toBe("Not found");
expect(extractApiErrorMessage({ message: "Unauthorized" })).toBe(
"Unauthorized",
);
expect(extractApiErrorMessage("<html>")).toBeUndefined();
expect(extractApiErrorMessage(undefined)).toBeUndefined();
});

it("should append the server message to request errors", async () => {
process.env.DOKPLOY_URL = "http://127.0.0.1:9";
process.env.DOKPLOY_API_KEY = "k";
const { createClient } = await import("../src/client.js");
const client = createClient();
client.defaults.adapter = async (config) => {
const error: any = new Error("Request failed with status code 400");
error.config = config;
error.response = {
status: 400,
data: { error: { json: { message: "Invalid input" } } },
};
throw error;
};

await expect(client.get("/x")).rejects.toThrow(
"Request failed with status code 400: Invalid input",
);
});
});