Skip to content

Commit 45b1454

Browse files
committed
refactor: introduce PostCateStore
1 parent 6862b3e commit 45b1454

File tree

5 files changed

+105
-59
lines changed

5 files changed

+105
-59
lines changed

src/service/post/post-cat.ts

Lines changed: 0 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,6 @@ import { UserService } from '../user.service'
88
// TODO: need better cache impl
99
let siteCategoryCache: SiteCat[] | null = null
1010

11-
const DEFAULT_ORDER = 999999
12-
1311
async function getAuthedPostCatReq() {
1412
const token = await AuthManager.acquireToken()
1513
// TODO: need better solution
@@ -31,53 +29,6 @@ export namespace PostCatService {
3129
}
3230
}
3331

34-
export async function getFlatAll() {
35-
const categories = await getAll()
36-
if (categories == null || categories.length === 0) return []
37-
38-
const flat = []
39-
const queue = categories
40-
while (queue.length > 0) {
41-
const current = queue.pop()
42-
if (current == null) continue
43-
flat.push(current)
44-
if (current.children != null) for (const child of current.children) queue.unshift(child)
45-
}
46-
47-
return flat.sort((x, y) => {
48-
const order1 = x.order ?? DEFAULT_ORDER
49-
const order2 = y.order ?? DEFAULT_ORDER
50-
if (order1 > order2) return 1
51-
else if (order1 < order2) return -1
52-
else return x.title.localeCompare(y.title)
53-
})
54-
}
55-
56-
export async function getOne(categoryId: number) {
57-
const req = await getAuthedPostCatReq()
58-
try {
59-
const resp = await req.getOne(categoryId)
60-
const { parent } = <{ parent: PostCat | null }>JSON.parse(resp)
61-
return Object.assign(new PostCat(), parent)
62-
} catch (e) {
63-
if (await UserService.hasBlog()) void Alert.err(`查询随笔分类失败: ${<string>e}`)
64-
throw e
65-
}
66-
}
67-
68-
export async function getAllUnder(parentId: number) {
69-
const req = await getAuthedPostCatReq()
70-
try {
71-
const resp = await req.getOne(parentId)
72-
const { categories } = <{ categories: PostCat[] }>JSON.parse(resp)
73-
if (categories == null) return []
74-
return categories.map(x => Object.assign(new PostCat(), x))
75-
} catch (e) {
76-
if (await UserService.hasBlog()) void Alert.err(`查询随笔分类失败: ${<string>e}`)
77-
throw e
78-
}
79-
}
80-
8132
export async function create(dto: PostCatAddDto) {
8233
const req = await getAuthedPostCatReq()
8334
const body = JSON.stringify(dto)

src/service/post/post-cfg-panel.ts

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import { Token } from '@/wasm'
1717
import { PostTagReq } from '@/wasm'
1818
import { PostTag } from '@/wasm'
1919
import { AuthManager } from '@/auth/auth-manager'
20+
import { PostCateStore } from '@/stores/post-cate-store'
2021

2122
async function getAuthedPostTagReq() {
2223
const token = await AuthManager.acquireToken()
@@ -72,11 +73,13 @@ export namespace PostCfgPanel {
7273
baseUrl: webview.asWebviewUri(Uri.joinPath(globalCtx.assetsUri, 'fonts')).toString() + '/',
7374
} as WebviewMsg.SetFluentIconBaseUrlMsg)
7475

76+
const postCateStore = await PostCateStore.create()
77+
7578
await webview.postMessage({
7679
command: Webview.Cmd.Ui.editPostCfg,
7780
post: cloneDeep(post),
7881
activeTheme: vscode.window.activeColorTheme.kind,
79-
userCats: cloneDeep(await PostCatService.getFlatAll()),
82+
userCats: cloneDeep(postCateStore.getFlatAll()),
8083
siteCats: cloneDeep(await PostCatService.getSitePresetList()),
8184
tags,
8285
breadcrumbs,
@@ -161,10 +164,11 @@ const observeWebviewMsg = (panel: WebviewPanel, options: PostCfgPanelOpenOption)
161164
await doUploadImg(webview, <WebviewMsg.UploadImgMsg>message)
162165
} else if (command === Webview.Cmd.Ext.getChildCategories) {
163166
const { payload } = message as WebviewCommonCmd<Webview.Cmd.GetChildCategoriesPayload>
167+
const cateStore = await PostCateStore.create()
164168
await webview.postMessage({
165169
command: Webview.Cmd.Ui.updateChildCategories,
166170
payload: {
167-
value: await PostCatService.getAllUnder(payload.parentId).catch(() => []),
171+
value: cateStore.getChildren(payload.parentId),
168172
parentId: payload.parentId,
169173
},
170174
})

src/stores/post-cate-store.ts

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
import { PostCat } from '@/model/post-cat'
2+
import { PostCatService } from '@/service/post/post-cat'
3+
import { cloneDeep } from 'lodash'
4+
5+
const DEFAULT_ORDER: number = 999999
6+
7+
export class PostCateStore {
8+
// eslint-disable-next-line prettier/prettier
9+
constructor(private categories: PostCat[]) { }
10+
11+
static async create() {
12+
const categories = await PostCatService.getAll()
13+
return new PostCateStore(categories)
14+
}
15+
16+
async refresh() {
17+
this.categories = await PostCatService.getAll()
18+
}
19+
20+
getFlatAll() {
21+
if (this.categories == null || this.categories.length === 0) return []
22+
23+
const flat: PostCat[] = []
24+
const queue = this.categories
25+
while (queue.length > 0) {
26+
const current = queue.pop()
27+
if (current == null) continue
28+
flat.push(current)
29+
if (current.children != null) for (const child of current.children) queue.unshift(child)
30+
}
31+
32+
return flat.sort((x, y) => {
33+
const order1 = x.order ?? DEFAULT_ORDER
34+
const order2 = y.order ?? DEFAULT_ORDER
35+
if (order1 > order2) return 1
36+
else if (order1 < order2) return -1
37+
else return x.title.localeCompare(y.title)
38+
})
39+
}
40+
41+
getChildren(categoryId: number) {
42+
if (this.categories == null || this.categories.length === 0) return []
43+
44+
let children: PostCat[] = []
45+
const queue = this.categories
46+
while (queue.length > 0) {
47+
const current = queue.pop()
48+
if (current == null) continue
49+
if (current.categoryId === categoryId) {
50+
children = cloneDeep(current.children ?? [])
51+
break
52+
}
53+
54+
if (current.children != null) for (const child of current.children) queue.unshift(child)
55+
}
56+
57+
children.forEach(x => (x.children = undefined))
58+
return children
59+
}
60+
61+
getOne(categoryId: number) {
62+
if (this.categories == null || this.categories.length === 0) return null
63+
64+
let category: PostCat | null = null
65+
const queue = this.categories
66+
while (queue.length > 0) {
67+
const current = queue.pop()
68+
if (current == null) continue
69+
if (current.categoryId === categoryId) {
70+
category = cloneDeep(current)
71+
break
72+
}
73+
74+
if (current.children != null) for (const child of current.children) queue.unshift(child)
75+
}
76+
77+
if (category != null) category.children = []
78+
return category
79+
}
80+
}

src/tree-view/model/post-metadata.ts

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
/* eslint-disable prettier/prettier */
12
import differenceInSeconds from 'date-fns/differenceInSeconds'
23
import differenceInYears from 'date-fns/differenceInYears'
34
import format from 'date-fns/format'
@@ -6,12 +7,12 @@ import zhCN from 'date-fns/locale/zh-CN'
67
import { TreeItem, TreeItemCollapsibleState, ThemeIcon } from 'vscode'
78
import { AccessPermission, Post, formatAccessPermission } from '@/model/post'
89
import { PostEditDto } from '@/model/post-edit-dto'
9-
import { PostCatService } from '@/service/post/post-cat'
1010
import { PostService } from '@/service/post/post'
1111
import { BaseEntryTreeItem } from './base-entry-tree-item'
1212
import { BaseTreeItemSource } from './base-tree-item-source'
1313
import { PostTreeItem } from './post-tree-item'
1414
import { PostCat } from '@/model/post-cat'
15+
import { PostCateStore } from '@/stores/post-cate-store'
1516

1617
export enum RootPostMetadataType {
1718
categoryEntry = 'categoryEntry',
@@ -81,8 +82,8 @@ export abstract class PostMetadata extends BaseTreeItemSource {
8182

8283
export abstract class PostEntryMetadata<T extends PostMetadata = PostMetadata>
8384
extends PostMetadata
84-
implements BaseEntryTreeItem<T>
85-
{
85+
// eslint-disable-next-line prettier/prettier
86+
implements BaseEntryTreeItem<T> {
8687
constructor(
8788
parent: Post,
8889
public readonly children: T[]
@@ -138,8 +139,10 @@ export class PostCatMetadata extends PostMetadata {
138139
static async parse(parent: Post, editDto?: PostEditDto): Promise<PostCatMetadata[]> {
139140
if (editDto === undefined) editDto = await PostService.getPostEditDto(parent.id)
140141

142+
const cateStore = await PostCateStore.create()
143+
141144
const categoryIds = editDto.post.categoryIds ?? []
142-
const futList = categoryIds.map(PostCatService.getOne)
145+
const futList = categoryIds.map(x => cateStore.getOne(x))
143146
const categoryList = await Promise.all(futList)
144147

145148
return categoryList
@@ -214,8 +217,8 @@ export abstract class PostDateMetadata extends PostMetadata {
214217
toTreeItem = (): TreeItem =>
215218
Object.assign<TreeItem, TreeItem>(
216219
new TreeItem(
217-
`${this.label}: ${
218-
this.shouldUseDistance() ? this.distance + `(${this.formattedDate})` : this.formattedDate
220+
// eslint-disable-next-line prettier/prettier
221+
`${this.label}: ${this.shouldUseDistance() ? this.distance + `(${this.formattedDate})` : this.formattedDate
219222
}`
220223
),
221224
{
@@ -267,7 +270,7 @@ export class PostAccessPermissionMetadata extends PostMetadata {
267270
Object.assign<TreeItem, Partial<TreeItem>>(
268271
new TreeItem(
269272
`访问权限: ${formatAccessPermission(this.parent.accessPermission)}` +
270-
(isPasswordRequired ? '(需密码)' : '')
273+
(isPasswordRequired ? '(需密码)' : '')
271274
),
272275
{
273276
iconPath: PostAccessPermissionMetadata.parseIcon(this.parent.accessPermission, isPasswordRequired),

src/tree-view/provider/post-category-tree-data-provider.ts

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,13 @@ import { PostEntryMetadata, PostMetadata, RootPostMetadataType } from '@/tree-vi
99
import { PostTreeItem } from '@/tree-view/model/post-tree-item'
1010
import { Alert } from '@/infra/alert'
1111
import { setCtx } from '@/ctx/global-ctx'
12+
import { PostCateStore } from '@/stores/post-cate-store'
1213

1314
export class PostCatTreeDataProvider implements TreeDataProvider<PostCatListTreeItem> {
1415
private _treeDataChanged = new EventEmitter<PostCatListTreeItem | null | undefined>()
1516
private _isLoading = false
1617
private _roots: PostCatTreeItem[] | null = null
18+
private _postCateStore: PostCateStore | null = null
1719

1820
get isLoading() {
1921
return this._isLoading
@@ -38,6 +40,11 @@ export class PostCatTreeDataProvider implements TreeDataProvider<PostCatListTree
3840
return this._treeDataChanged.event
3941
}
4042

43+
async getPostCateStore() {
44+
if (this._postCateStore == null) this._postCateStore = await PostCateStore.create()
45+
return this._postCateStore
46+
}
47+
4148
async setIsRefreshing(value: boolean) {
4249
await setCtx('post-cat-list.isLoading', value)
4350
this._isLoading = value
@@ -74,6 +81,7 @@ export class PostCatTreeDataProvider implements TreeDataProvider<PostCatListTree
7481

7582
refresh() {
7683
this._roots = null
84+
this._postCateStore?.refresh().then().catch(console.error)
7785
this.fireTreeDataChangedEvent()
7886
}
7987

@@ -119,7 +127,7 @@ export class PostCatTreeDataProvider implements TreeDataProvider<PostCatListTree
119127
private async getCategories(parentId: number) {
120128
await this.setIsRefreshing(true)
121129
try {
122-
const categories = await PostCatService.getAllUnder(parentId)
130+
const categories = (await this.getPostCateStore()).getChildren(parentId)
123131
await this.setIsRefreshing(false)
124132
return categories.map(x => new PostCatTreeItem(x))
125133
} catch (e) {

0 commit comments

Comments
 (0)