@@ -9,27 +9,34 @@ const usePrivateKeysStore = defineStore("privateKey", () => {
99 privateKeys . value = JSON . parse ( localStorage . getItem ( "privateKeys" ) || "[]" ) ;
1010 } ;
1111
12- const addPrivateKey = ( newKey : Omit < IPrivateKey , "id" > ) => {
13- const existentIds : number [ ] = [ ] ;
12+ const validateKeyUniqueness = ( name : string , data : string , currentKeyId ?: number ) => {
13+ // currentKeyId prevents validating against the key being edited
14+ const hasSameName = privateKeys . value . some ( ( key ) => key . id !== currentKeyId && key . name === name ) ;
15+ const hasSameData = privateKeys . value . some ( ( key ) => key . id !== currentKeyId && key . data === data ) ;
16+
17+ if ( hasSameName && hasSameData ) throw new Error ( "both" ) ;
18+ if ( hasSameData ) throw new Error ( "private_key" ) ;
19+ if ( hasSameName ) throw new Error ( "name" ) ;
20+ } ;
1421
15- privateKeys . value . forEach ( ( key : IPrivateKey ) => {
16- if ( key . data === newKey . data && key . name === newKey . name ) throw new Error ( "both" ) ;
17- if ( key . data === newKey . data ) throw new Error ( "private_key" ) ;
18- if ( key . name === newKey . name ) throw new Error ( "name" ) ;
19- existentIds . push ( key . id ) ;
20- } ) ;
22+ const addPrivateKey = ( newKey : Omit < IPrivateKey , "id" > ) => {
23+ validateKeyUniqueness ( newKey . name , newKey . data ) ;
2124
25+ const existentIds = privateKeys . value . map ( ( key ) => key . id ) ;
2226 const newKeyId = existentIds . length ? Math . max ( ...existentIds ) + 1 : 1 ;
27+
2328 privateKeys . value . push ( { ...newKey , id : newKeyId } ) ;
2429 localStorage . setItem ( "privateKeys" , JSON . stringify ( privateKeys . value ) ) ;
2530 } ;
2631
2732 const editPrivateKey = ( updatedKey : IPrivateKey ) => {
2833 const index = privateKeys . value . findIndex ( ( key ) => key . id === updatedKey . id ) ;
34+ if ( index === - 1 ) throw new Error ( "Key not found" ) ;
35+
2936 const existingKey = privateKeys . value [ index ] ;
3037
31- if ( existingKey && existingKey . data === updatedKey . data && existingKey . name === updatedKey . name ) {
32- throw new Error ( ) ;
38+ if ( existingKey . name !== updatedKey . name || existingKey . data !== updatedKey . data ) {
39+ validateKeyUniqueness ( updatedKey . name , updatedKey . data , updatedKey . id ) ;
3340 }
3441
3542 privateKeys . value . splice ( index , 1 , updatedKey ) ;
0 commit comments