@@ -15,6 +15,10 @@ type Item = {
1515 * Name
1616 */
1717 n : string
18+ /**
19+ * Auto rules
20+ */
21+ a ?: string [ ]
1822}
1923
2024type Items = Record < number , Item >
@@ -49,43 +53,58 @@ class SiteCateDatabase extends BaseDatabase {
4953
5054 async listAll ( ) : Promise < timer . site . Cate [ ] > {
5155 const items = await this . getItems ( )
52- return Object . entries ( items ) . map ( ( [ id , { n = '' } = { } ] ) => {
56+ return Object . entries ( items ) . map ( ( [ id , { n = '' , a } = { } ] ) => {
5357 return {
5458 id : parseInt ( id ) ,
5559 name : n ,
60+ autoRules : a ?? [ ] ,
5661 } satisfies timer . site . Cate
5762 } )
5863 }
5964
60- async add ( name : string ) : Promise < timer . site . Cate > {
65+ async add ( name : string , autoRules : string [ ] ) : Promise < timer . site . Cate > {
6166 const items = await this . getItems ( )
6267 const existId = Object . entries ( items ) . find ( ( [ _ , v ] ) => v . n === name ) ?. [ 0 ]
6368 if ( existId ) {
6469 // Exist already
65- return { id : parseInt ( existId ) , name }
70+ return { id : parseInt ( existId ) , name, autoRules }
6671 }
6772
6873 const id = ( Object . keys ( items || { } ) . map ( k => parseInt ( k ) ) . sort ( ) . reverse ( ) ?. [ 0 ] ?? 0 ) + 1
69- items [ id ] = { n : name || items [ id ] ?. n }
74+ items [ id ] = { n : name || items [ id ] ?. n , a : autoRules }
7075
7176 await this . saveItems ( items )
72- return { name, id }
77+ return { name, id, autoRules }
7378 }
7479
75- async update ( id : number , name : string ) : Promise < void > {
76- if ( ! name ) return
77-
80+ private async updateWithReplacer ( id : number , replacer : ( exist : Item ) => Item ) : Promise < void > {
7881 const items = await this . getItems ( )
79- const existId = Object . entries ( items ) . find ( ( [ _ , v ] ) => v . n === name ) ?. [ 0 ]
82+ const exist = items [ id ]
83+ if ( ! exist ) return
8084
81- if ( existId ) {
85+ const replaced = replacer ( exist )
86+
87+ if ( Object . entries ( items ) . some ( ( [ vid , v ] ) => v . n === replaced . n && parseInt ( vid ) !== id ) ) {
88+ // Name exist already
8289 return
8390 }
8491
85- items [ id ] = { ... items [ id ] || { } , n : name }
92+ items [ id ] = replaced
8693 await this . saveItems ( items )
8794 }
8895
96+ async updateName ( id : number , name : string ) : Promise < void > {
97+ await this . updateWithReplacer ( id , exist => ( { ...exist , n : name } ) )
98+ }
99+
100+ async update ( cate : timer . site . Cate ) : Promise < void > {
101+ await this . updateWithReplacer ( cate . id , exist => ( {
102+ ...exist ,
103+ n : cate . name ,
104+ a : cate . autoRules ,
105+ } ) )
106+ }
107+
89108 async importData ( data : any ) : Promise < void > {
90109 let toImport = data [ KEY ] as Items
91110 // Not import
0 commit comments