@@ -55,6 +55,21 @@ export class D1Storage implements IStorage {
5555 return result ? ( result . id as number ) : null ;
5656 }
5757
58+ // 如果用户不存在则自动创建(角色默认为 user)
59+ private async ensureUser ( username : string ) : Promise < number > {
60+ let userId = await this . getUserId ( username ) ;
61+ if ( userId ) return userId ;
62+
63+ await this . db
64+ . prepare ( 'INSERT INTO users (username, password, role) VALUES (?, ?, ?)' )
65+ . bind ( username , '' , 'user' )
66+ . run ( ) ;
67+
68+ userId = await this . getUserId ( username ) ;
69+ if ( ! userId ) throw new Error ( 'Failed to create user' ) ;
70+ return userId ;
71+ }
72+
5873 async registerUser ( userName : string , password : string ) : Promise < void > {
5974 await this . db
6075 . prepare ( 'INSERT INTO users (username, password) VALUES (?, ?)' )
@@ -159,8 +174,7 @@ export class D1Storage implements IStorage {
159174 record : PlayRecord
160175 ) : Promise < void > {
161176 const [ source , videoId ] = key . split ( '+' ) ;
162- const userId = await this . getUserId ( userName ) ;
163- if ( ! userId ) throw new Error ( 'User not found' ) ;
177+ const userId = await this . ensureUser ( userName ) ;
164178
165179 await this . db
166180 . prepare (
@@ -278,8 +292,7 @@ export class D1Storage implements IStorage {
278292 favorite : Favorite
279293 ) : Promise < void > {
280294 const [ source , videoId ] = key . split ( '+' ) ;
281- const userId = await this . getUserId ( userName ) ;
282- if ( ! userId ) throw new Error ( 'User not found' ) ;
295+ const userId = await this . ensureUser ( userName ) ;
283296
284297 await this . db
285298 . prepare (
@@ -375,8 +388,7 @@ export class D1Storage implements IStorage {
375388 }
376389
377390 async addSearchHistory ( userName : string , keyword : string ) : Promise < void > {
378- const userId = await this . getUserId ( userName ) ;
379- if ( ! userId ) throw new Error ( 'User not found' ) ;
391+ const userId = await this . ensureUser ( userName ) ;
380392
381393 // 先删除已存在的相同关键词
382394 await this . db
@@ -605,8 +617,7 @@ export class D1Storage implements IStorage {
605617 id : string ,
606618 config : SkipConfig
607619 ) : Promise < void > {
608- const userId = await this . getUserId ( userName ) ;
609- if ( ! userId ) throw new Error ( 'User not found' ) ;
620+ const userId = await this . ensureUser ( userName ) ;
610621
611622 await this . db
612623 . prepare (
0 commit comments