feat: Enhance HaloClient with retry logic and improve error handling
- Added retry options to HaloClient for handling transient errors. - Refactored request methods in HaloClient to utilize retry logic. - Updated HaloService to include logging for error handling. - Introduced ApiPaths utility for managing API endpoints. - Implemented logger utility for consistent logging across services. - Added tests for ContentService, Error handling, and TaxonomyService. - Created retry utility for managing retry logic with exponential backoff. - Updated types to include additional properties for better API response handling.
This commit is contained in:
@@ -0,0 +1,179 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { ContentService } from "../content-service";
|
||||
|
||||
describe("ContentService", () => {
|
||||
const service = new ContentService();
|
||||
|
||||
describe("renderMarkdown", () => {
|
||||
it("should render markdown to HTML", () => {
|
||||
const result = service.renderMarkdown("# Hello World");
|
||||
|
||||
expect(result).toContain("<h1");
|
||||
expect(result).toContain("Hello World");
|
||||
});
|
||||
|
||||
it("should render bold text", () => {
|
||||
const result = service.renderMarkdown("**bold**");
|
||||
|
||||
expect(result).toContain("<strong>bold</strong>");
|
||||
});
|
||||
|
||||
it("should render links", () => {
|
||||
const result = service.renderMarkdown("[link](https://example.com)");
|
||||
|
||||
expect(result).toContain('<a href="https://example.com">link</a>');
|
||||
});
|
||||
|
||||
it("should render code blocks", () => {
|
||||
const result = service.renderMarkdown("```js\nconst x = 1;\n```");
|
||||
|
||||
expect(result).toContain("<pre><code");
|
||||
});
|
||||
});
|
||||
|
||||
describe("extractFrontmatter", () => {
|
||||
it("should extract frontmatter from markdown", () => {
|
||||
const md = `---
|
||||
title: Test Title
|
||||
slug: test-slug
|
||||
tags:
|
||||
- tag1
|
||||
- tag2
|
||||
---
|
||||
|
||||
# Content`;
|
||||
|
||||
const { frontmatter, rawContent } = service.extractFrontmatter(md);
|
||||
|
||||
expect(frontmatter.title).toBe("Test Title");
|
||||
expect(frontmatter.slug).toBe("test-slug");
|
||||
expect(frontmatter.tags).toEqual(["tag1", "tag2"]);
|
||||
expect(rawContent.trim()).toBe("# Content");
|
||||
});
|
||||
|
||||
it("should handle markdown without frontmatter", () => {
|
||||
const md = "# Just Content";
|
||||
|
||||
const { frontmatter, rawContent } = service.extractFrontmatter(md);
|
||||
|
||||
expect(frontmatter).toEqual({});
|
||||
expect(rawContent).toBe("# Just Content");
|
||||
});
|
||||
|
||||
it("should handle frontmatter with categories", () => {
|
||||
const md = `---
|
||||
title: Categories Test
|
||||
categories:
|
||||
- 技术
|
||||
- 编程
|
||||
---
|
||||
|
||||
Content here`;
|
||||
|
||||
const { frontmatter, rawContent } = service.extractFrontmatter(md);
|
||||
|
||||
expect(frontmatter.categories).toEqual(["技术", "编程"]);
|
||||
expect(rawContent.trim()).toBe("Content here");
|
||||
});
|
||||
|
||||
it("should handle frontmatter with halo metadata", () => {
|
||||
const md = `---
|
||||
title: Halo Post
|
||||
halo:
|
||||
site: https://example.com
|
||||
name: abc-123
|
||||
publish: true
|
||||
---
|
||||
|
||||
Content`;
|
||||
|
||||
const { frontmatter } = service.extractFrontmatter(md);
|
||||
|
||||
expect(frontmatter.halo?.site).toBe("https://example.com");
|
||||
expect(frontmatter.halo?.name).toBe("abc-123");
|
||||
expect(frontmatter.halo?.publish).toBe(true);
|
||||
});
|
||||
|
||||
it("should handle empty frontmatter", () => {
|
||||
const md = `---
|
||||
---
|
||||
|
||||
Content`;
|
||||
|
||||
const { frontmatter, rawContent } = service.extractFrontmatter(md);
|
||||
|
||||
expect(frontmatter).toEqual({});
|
||||
expect(rawContent.trim()).toBe("Content");
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildPostSpec", () => {
|
||||
it("should build post spec with default values", () => {
|
||||
const spec = service.buildPostSpec(
|
||||
"Test Title",
|
||||
"test-slug",
|
||||
"# Content",
|
||||
{},
|
||||
{ rawType: "markdown", raw: "# Content", content: "<h1>Content</h1>" }
|
||||
);
|
||||
|
||||
expect(spec.title).toBe("Test Title");
|
||||
expect(spec.slug).toBe("test-slug");
|
||||
expect(spec.allowComment).toBe(true);
|
||||
expect(spec.visible).toBe("PUBLIC");
|
||||
expect(spec.publish).toBe(false);
|
||||
expect(spec.excerpt.autoGenerate).toBe(true);
|
||||
});
|
||||
|
||||
it("should use provided slug", () => {
|
||||
const spec = service.buildPostSpec(
|
||||
"Title",
|
||||
"custom-slug",
|
||||
"# Content",
|
||||
{},
|
||||
{ rawType: "markdown", raw: "# Content", content: "<h1>Content</h1>" }
|
||||
);
|
||||
|
||||
expect(spec.slug).toBe("custom-slug");
|
||||
});
|
||||
|
||||
it("should auto-generate slug from title if not provided", () => {
|
||||
const spec = service.buildPostSpec(
|
||||
"Test Title",
|
||||
"",
|
||||
"# Content",
|
||||
{},
|
||||
{ rawType: "markdown", raw: "# Content", content: "<h1>Content</h1>" }
|
||||
);
|
||||
|
||||
// slugify should convert "Test Title" to "test-title"
|
||||
expect(spec.slug).toBeTruthy();
|
||||
expect(spec.slug).toContain("test");
|
||||
});
|
||||
|
||||
it("should use excerpt from frontmatter", () => {
|
||||
const spec = service.buildPostSpec(
|
||||
"Title",
|
||||
"slug",
|
||||
"# Content",
|
||||
{ excerpt: "Custom excerpt" },
|
||||
{ rawType: "markdown", raw: "# Content", content: "<h1>Content</h1>" }
|
||||
);
|
||||
|
||||
expect(spec.excerpt.autoGenerate).toBe(false);
|
||||
expect(spec.excerpt.raw).toBe("Custom excerpt");
|
||||
});
|
||||
|
||||
it("should use cover from frontmatter", () => {
|
||||
const spec = service.buildPostSpec(
|
||||
"Title",
|
||||
"slug",
|
||||
"# Content",
|
||||
{ cover: "https://example.com/cover.jpg" },
|
||||
{ rawType: "markdown", raw: "# Content", content: "<h1>Content</h1>" }
|
||||
);
|
||||
|
||||
expect(spec.cover).toBe("https://example.com/cover.jpg");
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,115 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { HaloError, HttpError } from "../error";
|
||||
|
||||
describe("HaloError", () => {
|
||||
it("should create error with all properties", () => {
|
||||
const error = new HaloError("Test message", "TEST_CODE", 400, new Error("original"));
|
||||
|
||||
expect(error.message).toBe("Test message");
|
||||
expect(error.code).toBe("TEST_CODE");
|
||||
expect(error.statusCode).toBe(400);
|
||||
expect(error.originalError).toBeInstanceOf(Error);
|
||||
expect(error.name).toBe("HaloError");
|
||||
});
|
||||
|
||||
it("should create network error", () => {
|
||||
const error = HaloError.network(new Error("fetch failed"));
|
||||
|
||||
expect(error.code).toBe("NETWORK_ERROR");
|
||||
expect(error.message).toBe("网络请求失败,请检查网络连接");
|
||||
expect(error.isNetworkError()).toBe(true);
|
||||
expect(error.isAuthError()).toBe(false);
|
||||
});
|
||||
|
||||
it("should create unauthorized error", () => {
|
||||
const error = HaloError.unauthorized();
|
||||
|
||||
expect(error.code).toBe("UNAUTHORIZED");
|
||||
expect(error.statusCode).toBe(401);
|
||||
expect(error.isAuthError()).toBe(true);
|
||||
});
|
||||
|
||||
it("should create forbidden error", () => {
|
||||
const error = HaloError.forbidden();
|
||||
|
||||
expect(error.code).toBe("FORBIDDEN");
|
||||
expect(error.statusCode).toBe(403);
|
||||
expect(error.isAuthError()).toBe(true);
|
||||
});
|
||||
|
||||
it("should create notFound error", () => {
|
||||
const error = HaloError.notFound("Post");
|
||||
|
||||
expect(error.code).toBe("NOT_FOUND");
|
||||
expect(error.statusCode).toBe(404);
|
||||
expect(error.message).toBe("Post 未找到");
|
||||
expect(error.isNotFound()).toBe(true);
|
||||
});
|
||||
|
||||
it("should create server error", () => {
|
||||
const error = HaloError.serverError();
|
||||
|
||||
expect(error.code).toBe("SERVER_ERROR");
|
||||
expect(error.statusCode).toBe(500);
|
||||
});
|
||||
|
||||
it("should create validation error", () => {
|
||||
const error = HaloError.validationError("Invalid slug");
|
||||
|
||||
expect(error.code).toBe("VALIDATION_ERROR");
|
||||
expect(error.message).toBe("Invalid slug");
|
||||
});
|
||||
|
||||
it("should create unknown error from Error", () => {
|
||||
const original = new Error("Something went wrong");
|
||||
const error = HaloError.unknown(original);
|
||||
|
||||
expect(error.code).toBe("UNKNOWN");
|
||||
expect(error.message).toBe("Something went wrong");
|
||||
});
|
||||
|
||||
it("should create unknown error from non-Error", () => {
|
||||
const error = HaloError.unknown("string error");
|
||||
|
||||
expect(error.code).toBe("UNKNOWN");
|
||||
expect(error.message).toBe("未知错误");
|
||||
});
|
||||
});
|
||||
|
||||
describe("HttpError", () => {
|
||||
it("should create from status code 400", () => {
|
||||
const error = HttpError.fromStatus(400, { message: "bad request" });
|
||||
|
||||
expect(error.statusCode).toBe(400);
|
||||
expect(error.message).toBe("请求参数错误");
|
||||
expect(error.name).toBe("HttpError");
|
||||
});
|
||||
|
||||
it("should create from status code 401", () => {
|
||||
const error = HttpError.fromStatus(401);
|
||||
|
||||
expect(error.statusCode).toBe(401);
|
||||
expect(error.message).toBe("认证失败");
|
||||
});
|
||||
|
||||
it("should create from status code 404", () => {
|
||||
const error = HttpError.fromStatus(404);
|
||||
|
||||
expect(error.statusCode).toBe(404);
|
||||
expect(error.message).toBe("资源不存在");
|
||||
});
|
||||
|
||||
it("should create from status code 500", () => {
|
||||
const error = HttpError.fromStatus(500);
|
||||
|
||||
expect(error.statusCode).toBe(500);
|
||||
expect(error.message).toBe("服务器内部错误");
|
||||
});
|
||||
|
||||
it("should create from unknown status code", () => {
|
||||
const error = HttpError.fromStatus(418);
|
||||
|
||||
expect(error.statusCode).toBe(418);
|
||||
expect(error.message).toBe("HTTP 错误 (418)");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,242 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { TaxonomyService } from "../taxonomy-service";
|
||||
import type { HaloClient } from "../client";
|
||||
import type { Category, Tag } from "../types";
|
||||
|
||||
describe("TaxonomyService", () => {
|
||||
let service: TaxonomyService;
|
||||
let mockClient: HaloClient;
|
||||
|
||||
beforeEach(() => {
|
||||
mockClient = {
|
||||
get: vi.fn(),
|
||||
post: vi.fn(),
|
||||
put: vi.fn(),
|
||||
delete: vi.fn(),
|
||||
} as unknown as HaloClient;
|
||||
service = new TaxonomyService(mockClient);
|
||||
});
|
||||
|
||||
describe("getCategories", () => {
|
||||
it("should return categories from API", async () => {
|
||||
const mockCategories: Category[] = [
|
||||
{
|
||||
metadata: { name: "cat-1" },
|
||||
spec: { displayName: "技术", slug: "tech", description: "", cover: "", template: "", priority: 0, children: [] },
|
||||
},
|
||||
{
|
||||
metadata: { name: "cat-2" },
|
||||
spec: { displayName: "生活", slug: "life", description: "", cover: "", template: "", priority: 1, children: [] },
|
||||
},
|
||||
];
|
||||
|
||||
vi.mocked(mockClient.get).mockResolvedValue({ items: mockCategories });
|
||||
|
||||
const result = await service.getCategories();
|
||||
|
||||
expect(result).toEqual(mockCategories);
|
||||
expect(mockClient.get).toHaveBeenCalledWith("/apis/content.halo.run/v1alpha1/categories");
|
||||
});
|
||||
});
|
||||
|
||||
describe("getTags", () => {
|
||||
it("should return tags from API", async () => {
|
||||
const mockTags: Tag[] = [
|
||||
{
|
||||
metadata: { name: "tag-1" },
|
||||
spec: { displayName: "Python", slug: "python", color: "#3776AB", cover: "" },
|
||||
},
|
||||
];
|
||||
|
||||
vi.mocked(mockClient.get).mockResolvedValue({ items: mockTags });
|
||||
|
||||
const result = await service.getTags();
|
||||
|
||||
expect(result).toEqual(mockTags);
|
||||
expect(mockClient.get).toHaveBeenCalledWith("/apis/content.halo.run/v1alpha1/tags");
|
||||
});
|
||||
});
|
||||
|
||||
describe("getCategoryNames", () => {
|
||||
it("should return existing category names", async () => {
|
||||
const mockCategories: Category[] = [
|
||||
{
|
||||
metadata: { name: "cat-1" },
|
||||
spec: { displayName: "技术", slug: "tech", description: "", cover: "", template: "", priority: 0, children: [] },
|
||||
},
|
||||
];
|
||||
|
||||
vi.mocked(mockClient.get).mockResolvedValue({ items: mockCategories });
|
||||
|
||||
const result = await service.getCategoryNames(["技术"]);
|
||||
|
||||
expect(result).toContain("cat-1");
|
||||
});
|
||||
|
||||
it("should create new categories if not exist", async () => {
|
||||
const mockCategories: Category[] = [];
|
||||
const newCategory: Category = {
|
||||
metadata: { name: "new-cat" },
|
||||
spec: { displayName: "新分类", slug: "xin-fen-lei", description: "", cover: "", template: "", priority: 0, children: [] },
|
||||
};
|
||||
|
||||
vi.mocked(mockClient.get).mockResolvedValue({ items: mockCategories });
|
||||
vi.mocked(mockClient.post).mockResolvedValue(newCategory);
|
||||
|
||||
const result = await service.getCategoryNames(["新分类"]);
|
||||
|
||||
expect(result).toContain("new-cat");
|
||||
expect(mockClient.post).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("getTagNames", () => {
|
||||
it("should return existing tag names", async () => {
|
||||
const mockTags: Tag[] = [
|
||||
{
|
||||
metadata: { name: "tag-1" },
|
||||
spec: { displayName: "Python", slug: "python", color: "#3776AB", cover: "" },
|
||||
},
|
||||
];
|
||||
|
||||
vi.mocked(mockClient.get).mockResolvedValue({ items: mockTags });
|
||||
|
||||
const result = await service.getTagNames(["Python"]);
|
||||
|
||||
expect(result).toContain("tag-1");
|
||||
});
|
||||
|
||||
it("should create new tags if not exist", async () => {
|
||||
const mockTags: Tag[] = [];
|
||||
const newTag: Tag = {
|
||||
metadata: { name: "new-tag" },
|
||||
spec: { displayName: "新标签", slug: "xin-biao-qian", color: "#ffffff", cover: "" },
|
||||
};
|
||||
|
||||
vi.mocked(mockClient.get).mockResolvedValue({ items: mockTags });
|
||||
vi.mocked(mockClient.post).mockResolvedValue(newTag);
|
||||
|
||||
const result = await service.getTagNames(["新标签"]);
|
||||
|
||||
expect(result).toContain("new-tag");
|
||||
expect(mockClient.post).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("getCategoryDisplayNames", () => {
|
||||
it("should convert category names to display names", async () => {
|
||||
const mockCategories: Category[] = [
|
||||
{
|
||||
metadata: { name: "cat-1" },
|
||||
spec: { displayName: "技术", slug: "tech", description: "", cover: "", template: "", priority: 0, children: [] },
|
||||
},
|
||||
];
|
||||
|
||||
vi.mocked(mockClient.get).mockResolvedValue({ items: mockCategories });
|
||||
|
||||
const result = await service.getCategoryDisplayNames(["cat-1"]);
|
||||
|
||||
expect(result).toEqual(["技术"]);
|
||||
});
|
||||
|
||||
it("should return empty array for empty input", async () => {
|
||||
const result = await service.getCategoryDisplayNames([]);
|
||||
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
|
||||
it("should filter out unknown category names", async () => {
|
||||
const mockCategories: Category[] = [
|
||||
{
|
||||
metadata: { name: "cat-1" },
|
||||
spec: { displayName: "技术", slug: "tech", description: "", cover: "", template: "", priority: 0, children: [] },
|
||||
},
|
||||
];
|
||||
|
||||
vi.mocked(mockClient.get).mockResolvedValue({ items: mockCategories });
|
||||
|
||||
const result = await service.getCategoryDisplayNames(["cat-1", "unknown-cat"]);
|
||||
|
||||
expect(result).toEqual(["技术"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getTagDisplayNames", () => {
|
||||
it("should convert tag names to display names", async () => {
|
||||
const mockTags: Tag[] = [
|
||||
{
|
||||
metadata: { name: "tag-1" },
|
||||
spec: { displayName: "Python", slug: "python", color: "#3776AB", cover: "" },
|
||||
},
|
||||
];
|
||||
|
||||
vi.mocked(mockClient.get).mockResolvedValue({ items: mockTags });
|
||||
|
||||
const result = await service.getTagDisplayNames(["tag-1"]);
|
||||
|
||||
expect(result).toEqual(["Python"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("createCategory", () => {
|
||||
it("should create a new category", async () => {
|
||||
const newCategory: Category = {
|
||||
metadata: { name: "cat-created" },
|
||||
spec: { displayName: "新分类", slug: "xin-fen-lei", description: "", cover: "", template: "", priority: 0, children: [] },
|
||||
};
|
||||
|
||||
vi.mocked(mockClient.post).mockResolvedValue(newCategory);
|
||||
|
||||
const result = await service.createCategory("新分类", "xin-fen-lei", 0);
|
||||
|
||||
expect(result).toEqual(newCategory);
|
||||
expect(mockClient.post).toHaveBeenCalledWith(
|
||||
"/apis/content.halo.run/v1alpha1/categories",
|
||||
expect.objectContaining({
|
||||
spec: expect.objectContaining({ displayName: "新分类", slug: "xin-fen-lei" }),
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("createTag", () => {
|
||||
it("should create a new tag", async () => {
|
||||
const newTag: Tag = {
|
||||
metadata: { name: "tag-created" },
|
||||
spec: { displayName: "新标签", slug: "xin-biao-qian", color: "#ffffff", cover: "" },
|
||||
};
|
||||
|
||||
vi.mocked(mockClient.post).mockResolvedValue(newTag);
|
||||
|
||||
const result = await service.createTag("新标签", "xin-biao-qian", "#ffffff");
|
||||
|
||||
expect(result).toEqual(newTag);
|
||||
expect(mockClient.post).toHaveBeenCalledWith(
|
||||
"/apis/content.halo.run/v1alpha1/tags",
|
||||
expect.objectContaining({
|
||||
spec: expect.objectContaining({ displayName: "新标签", slug: "xin-biao-qian", color: "#ffffff" }),
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("deleteCategory", () => {
|
||||
it("should delete a category", async () => {
|
||||
vi.mocked(mockClient.delete).mockResolvedValue();
|
||||
|
||||
await service.deleteCategory("cat-1");
|
||||
|
||||
expect(mockClient.delete).toHaveBeenCalledWith("/apis/content.halo.run/v1alpha1/categories/cat-1");
|
||||
});
|
||||
});
|
||||
|
||||
describe("deleteTag", () => {
|
||||
it("should delete a tag", async () => {
|
||||
vi.mocked(mockClient.delete).mockResolvedValue();
|
||||
|
||||
await service.deleteTag("tag-1");
|
||||
|
||||
expect(mockClient.delete).toHaveBeenCalledWith("/apis/content.halo.run/v1alpha1/tags/tag-1");
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,17 +1,24 @@
|
||||
import { requestUrl } from "obsidian";
|
||||
import type { HaloSite } from "../settings";
|
||||
import { HaloError, HttpError } from "./error";
|
||||
import { withRetry, type RetryOptions } from "../utils/retry";
|
||||
|
||||
export interface HaloClientOptions {
|
||||
retry?: RetryOptions;
|
||||
}
|
||||
|
||||
export class HaloClient {
|
||||
private readonly baseUrl: string;
|
||||
private readonly headers: Record<string, string>;
|
||||
private readonly retryOptions: RetryOptions;
|
||||
|
||||
constructor(site: HaloSite) {
|
||||
constructor(site: HaloSite, options: HaloClientOptions = {}) {
|
||||
this.baseUrl = site.url;
|
||||
this.headers = {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${site.token}`,
|
||||
};
|
||||
this.retryOptions = options.retry || {};
|
||||
}
|
||||
|
||||
private handleResponse<T>(response: { json: unknown; status: number }): T {
|
||||
@@ -25,7 +32,7 @@ export class HaloClient {
|
||||
}
|
||||
|
||||
private async request<T>(path: string, options: { method: string; body?: object }): Promise<T> {
|
||||
try {
|
||||
const doRequest = async () => {
|
||||
const response = await requestUrl({
|
||||
url: `${this.baseUrl}${path}`,
|
||||
method: options.method,
|
||||
@@ -35,12 +42,15 @@ export class HaloClient {
|
||||
});
|
||||
|
||||
return this.handleResponse<T>({ json: response.json, status: response.status });
|
||||
};
|
||||
|
||||
try {
|
||||
return await withRetry(doRequest, this.retryOptions);
|
||||
} catch (error) {
|
||||
if (error instanceof HttpError) {
|
||||
throw this.mapHttpError(error);
|
||||
}
|
||||
if (error instanceof TypeError) {
|
||||
// Network error
|
||||
throw HaloError.network(error);
|
||||
}
|
||||
throw HaloError.unknown(error);
|
||||
@@ -77,7 +87,7 @@ export class HaloClient {
|
||||
}
|
||||
|
||||
async delete(path: string): Promise<void> {
|
||||
try {
|
||||
const doDelete = async () => {
|
||||
const response = await requestUrl({
|
||||
url: `${this.baseUrl}${path}`,
|
||||
method: "DELETE",
|
||||
@@ -87,6 +97,10 @@ export class HaloClient {
|
||||
if (response.status >= 400) {
|
||||
throw HttpError.fromStatus(response.status, response.json);
|
||||
}
|
||||
};
|
||||
|
||||
try {
|
||||
await withRetry(doDelete, this.retryOptions);
|
||||
} catch (error) {
|
||||
if (error instanceof HttpError) {
|
||||
throw this.mapHttpError(error);
|
||||
@@ -99,7 +113,7 @@ export class HaloClient {
|
||||
}
|
||||
|
||||
async putVoid(path: string, body?: object): Promise<void> {
|
||||
try {
|
||||
const doPut = async () => {
|
||||
const response = await requestUrl({
|
||||
url: `${this.baseUrl}${path}`,
|
||||
method: "PUT",
|
||||
@@ -111,6 +125,10 @@ export class HaloClient {
|
||||
if (response.status >= 400) {
|
||||
throw HttpError.fromStatus(response.status, response.json);
|
||||
}
|
||||
};
|
||||
|
||||
try {
|
||||
await withRetry(doPut, this.retryOptions);
|
||||
} catch (error) {
|
||||
if (error instanceof HttpError) {
|
||||
throw this.mapHttpError(error);
|
||||
|
||||
@@ -1,19 +1,21 @@
|
||||
import { type App, Notice, type TFile } from "obsidian";
|
||||
import { randomUUID } from "./utils/id";
|
||||
import markdownIt from "./utils/markdown";
|
||||
import { randomUUID } from "../utils/id";
|
||||
import markdownIt from "../utils/markdown";
|
||||
import { slugify } from "transliteration";
|
||||
import type { HaloSetting, HaloSite } from "./settings";
|
||||
import type { HaloClient } from "./services/client";
|
||||
import { PostService } from "./services/post-service";
|
||||
import { ImageService } from "./services/image-service";
|
||||
import { TaxonomyService } from "./services/taxonomy-service";
|
||||
import { ContentService } from "./services/content-service";
|
||||
import type { Content, Post } from "./services/types";
|
||||
import type { HaloSetting, HaloSite } from "../settings";
|
||||
import { HaloClient } from "./client";
|
||||
import { PostService } from "./post-service";
|
||||
import { ImageService } from "./image-service";
|
||||
import { TaxonomyService } from "./taxonomy-service";
|
||||
import { ContentService } from "./content-service";
|
||||
import type { Content, Post } from "./types";
|
||||
import { HaloError } from "./error";
|
||||
import { logger } from "../utils/logger";
|
||||
|
||||
export class HaloService {
|
||||
private readonly app: App;
|
||||
private readonly siteUrl: string;
|
||||
private readonly settings: HaloSetting;
|
||||
private readonly client: HaloClient;
|
||||
private readonly postService: PostService;
|
||||
private readonly imageService: ImageService;
|
||||
@@ -23,6 +25,7 @@ export class HaloService {
|
||||
constructor(app: App, settings: HaloSetting, site: HaloSite) {
|
||||
this.app = app;
|
||||
this.siteUrl = site.url;
|
||||
this.settings = settings;
|
||||
this.client = new HaloClient(site);
|
||||
this.postService = new PostService(app, this.client);
|
||||
this.imageService = new ImageService(site);
|
||||
@@ -162,10 +165,10 @@ export class HaloService {
|
||||
new Notice("发布成功");
|
||||
} catch (error) {
|
||||
if (error instanceof HaloError) {
|
||||
console.error(`[HaloService] 发布失败 [${error.code}]:`, error.message);
|
||||
logger.error("HaloService", `发布失败 [${error.code}]`, error.message);
|
||||
new Notice(error.message);
|
||||
} else {
|
||||
console.error("[HaloService] 发布失败:", error);
|
||||
logger.error("HaloService", "发布失败", error);
|
||||
new Notice("发布失败");
|
||||
}
|
||||
}
|
||||
@@ -317,9 +320,9 @@ export class HaloService {
|
||||
return !!post && !!post.metadata;
|
||||
} catch (error) {
|
||||
if (error instanceof HaloError) {
|
||||
console.error(`[HaloService] 导入文章失败 [${error.code}]:`, error.message);
|
||||
logger.error("HaloService", `导入文章失败 [${error.code}]`, error.message);
|
||||
} else {
|
||||
console.error("[HaloService] 导入文章失败:", error);
|
||||
logger.error("HaloService", "导入文章失败", error);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -331,9 +334,9 @@ export class HaloService {
|
||||
return true;
|
||||
} catch (error) {
|
||||
if (error instanceof HaloError) {
|
||||
console.error(`[HaloService] 删除文章失败 [${error.code}]:`, error.message);
|
||||
logger.error("HaloService", `删除文章失败 [${error.code}]`, error.message);
|
||||
} else {
|
||||
console.error("[HaloService] 删除文章失败:", error);
|
||||
logger.error("HaloService", "删除文章失败", error);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import { randomUUID } from "../utils/id";
|
||||
import type { HaloClient } from "./client";
|
||||
import type { Post, Snapshot, Content } from "./types";
|
||||
import { HaloError } from "./error";
|
||||
import { ApiPaths } from "../utils/api-paths";
|
||||
|
||||
export class PostService {
|
||||
constructor(
|
||||
@@ -12,11 +13,9 @@ export class PostService {
|
||||
|
||||
async getPost(name: string): Promise<{ post: Post; content: Content } | undefined> {
|
||||
try {
|
||||
const post = await this.client.get<Post>(`/apis/uc.api.content.halo.run/v1alpha1/posts/${name}`);
|
||||
const post = await this.client.get<Post>(ApiPaths.posts.get(name));
|
||||
|
||||
const snapshot = await this.client.get<Snapshot>(
|
||||
`/apis/uc.api.content.halo.run/v1alpha1/posts/${name}/draft?patched=true`,
|
||||
);
|
||||
const snapshot = await this.client.get<Snapshot>(ApiPaths.posts.getDraft(name));
|
||||
|
||||
const { "content.halo.run/patched-content": patchedContent, "content.halo.run/patched-raw": patchedRaw } =
|
||||
snapshot.metadata.annotations || {};
|
||||
@@ -39,21 +38,19 @@ export class PostService {
|
||||
}
|
||||
|
||||
async createPost(params: Post): Promise<Post> {
|
||||
return await this.client.post<Post>("/apis/uc.api.content.halo.run/v1alpha1/posts", params);
|
||||
return await this.client.post<Post>(ApiPaths.posts.create(), params);
|
||||
}
|
||||
|
||||
async updatePost(name: string, params: Post): Promise<void> {
|
||||
await this.client.put(`/apis/uc.api.content.halo.run/v1alpha1/posts/${name}`, params);
|
||||
await this.client.put(ApiPaths.posts.update(name), params);
|
||||
}
|
||||
|
||||
async deletePost(name: string): Promise<void> {
|
||||
await this.client.delete(`/apis/uc.api.content.halo.run/v1alpha1/posts/${name}`);
|
||||
await this.client.delete(ApiPaths.posts.delete(name));
|
||||
}
|
||||
|
||||
async changePublishStatus(name: string, publish: boolean): Promise<void> {
|
||||
await this.client.putVoid(
|
||||
`/apis/uc.api.content.halo.run/v1alpha1/posts/${name}/${publish ? "publish" : "unpublish"}`,
|
||||
);
|
||||
await this.client.putVoid(publish ? ApiPaths.posts.publish(name) : ApiPaths.posts.unpublish(name));
|
||||
}
|
||||
|
||||
async createPostFromFile(
|
||||
|
||||
@@ -1,17 +1,18 @@
|
||||
import { slugify } from "transliteration";
|
||||
import type { HaloClient } from "./client";
|
||||
import type { Category, Tag } from "./types";
|
||||
import { ApiPaths } from "../utils/api-paths";
|
||||
|
||||
export class TaxonomyService {
|
||||
constructor(private client: HaloClient) {}
|
||||
|
||||
async getCategories(): Promise<Category[]> {
|
||||
const data = await this.client.get<{ items: Category[] }>("/apis/content.halo.run/v1alpha1/categories");
|
||||
const data = await this.client.get<{ items: Category[] }>(ApiPaths.categories.list());
|
||||
return data.items;
|
||||
}
|
||||
|
||||
async getTags(): Promise<Tag[]> {
|
||||
const data = await this.client.get<{ items: Tag[] }>("/apis/content.halo.run/v1alpha1/tags");
|
||||
const data = await this.client.get<{ items: Tag[] }>(ApiPaths.tags.list());
|
||||
return data.items;
|
||||
}
|
||||
|
||||
@@ -50,7 +51,7 @@ export class TaxonomyService {
|
||||
}
|
||||
|
||||
async createCategory(displayName: string, slug: string, priority: number): Promise<Category> {
|
||||
return await this.client.post<Category>("/apis/content.halo.run/v1alpha1/categories", {
|
||||
return await this.client.post<Category>(ApiPaths.categories.create(), {
|
||||
spec: {
|
||||
displayName,
|
||||
slug,
|
||||
@@ -67,15 +68,15 @@ export class TaxonomyService {
|
||||
}
|
||||
|
||||
async updateCategory(name: string, displayName: string, slug: string, priority: number): Promise<void> {
|
||||
const category = await this.client.get<Category>(`/apis/content.halo.run/v1alpha1/categories/${name}`);
|
||||
const category = await this.client.get<Category>(ApiPaths.categories.get(name));
|
||||
category.spec.displayName = displayName;
|
||||
category.spec.slug = slug;
|
||||
category.spec.priority = priority;
|
||||
await this.client.put(`/apis/content.halo.run/v1alpha1/categories/${name}`, category);
|
||||
await this.client.put(ApiPaths.categories.update(name), category);
|
||||
}
|
||||
|
||||
async deleteCategory(name: string): Promise<void> {
|
||||
await this.client.delete(`/apis/content.halo.run/v1alpha1/categories/${name}`);
|
||||
await this.client.delete(ApiPaths.categories.delete(name));
|
||||
}
|
||||
|
||||
async getTagNames(displayNames: string[]): Promise<string[]> {
|
||||
@@ -111,7 +112,7 @@ export class TaxonomyService {
|
||||
}
|
||||
|
||||
async createTag(displayName: string, slug: string, color: string): Promise<Tag> {
|
||||
return await this.client.post<Tag>("/apis/content.halo.run/v1alpha1/tags", {
|
||||
return await this.client.post<Tag>(ApiPaths.tags.create(), {
|
||||
spec: {
|
||||
displayName,
|
||||
slug,
|
||||
@@ -125,14 +126,14 @@ export class TaxonomyService {
|
||||
}
|
||||
|
||||
async updateTag(name: string, displayName: string, slug: string, color: string): Promise<void> {
|
||||
const tag = await this.client.get<Tag>(`/apis/content.halo.run/v1alpha1/tags/${name}`);
|
||||
const tag = await this.client.get<Tag>(ApiPaths.tags.get(name));
|
||||
tag.spec.displayName = displayName;
|
||||
tag.spec.slug = slug;
|
||||
tag.spec.color = color || "#ffffff";
|
||||
await this.client.put(`/apis/content.halo.run/v1alpha1/tags/${name}`, tag);
|
||||
await this.client.put(ApiPaths.tags.update(name), tag);
|
||||
}
|
||||
|
||||
async deleteTag(name: string): Promise<void> {
|
||||
await this.client.delete(`/apis/content.halo.run/v1alpha1/tags/${name}`);
|
||||
await this.client.delete(ApiPaths.tags.delete(name));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,9 +34,12 @@ export interface Post {
|
||||
export interface Snapshot {
|
||||
metadata: {
|
||||
annotations?: Record<string, string>;
|
||||
name?: string;
|
||||
};
|
||||
spec?: {
|
||||
rawType?: string;
|
||||
displayName?: string;
|
||||
slug?: string;
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user