1- import type { FileInfo , FileReader , FileWriter } from "../filesystem" ;
1+ import { FileSystemError } from "../error" ;
2+ import type { FileCreateOptions , FileInfo , FileReader , FileWriter } from "../filesystem" ;
23import { calculateMd5 , md5OfText } from "@App/pkg/utils/crypto" ;
34import type BaiduFileSystem from "./baidu" ;
45
@@ -38,9 +39,12 @@ export class BaiduFileWriter implements FileWriter {
3839
3940 fs : BaiduFileSystem ;
4041
41- constructor ( fs : BaiduFileSystem , path : string ) {
42+ opts ?: FileCreateOptions ;
43+
44+ constructor ( fs : BaiduFileSystem , path : string , opts ?: FileCreateOptions ) {
4245 this . fs = fs ;
4346 this . path = path ;
47+ this . opts = opts ;
4448 }
4549
4650 size ( content : string | Blob ) {
@@ -58,6 +62,8 @@ export class BaiduFileWriter implements FileWriter {
5862 }
5963
6064 async write ( content : string | Blob ) : Promise < void > {
65+ await this . checkWritePrecondition ( ) ;
66+
6167 // 预上传获取id
6268 const size = this . size ( content ) . toString ( ) ;
6369 const md5 = await this . md5 ( content ) ;
@@ -124,4 +130,35 @@ export class BaiduFileWriter implements FileWriter {
124130 throw new Error ( JSON . stringify ( data ) ) ;
125131 }
126132 }
133+
134+ private async checkWritePrecondition ( ) : Promise < void > {
135+ if ( ! this . opts ?. expectedDigest && ! this . opts ?. createOnly && this . opts ?. overwrite !== false ) {
136+ return ;
137+ }
138+ const targetName = this . path . substring ( this . path . lastIndexOf ( "/" ) + 1 ) ;
139+ const existing = ( await this . fs . list ( ) ) . find ( ( file ) => file . name === targetName ) ;
140+
141+ if ( this . opts ?. createOnly || this . opts ?. overwrite === false ) {
142+ if ( existing ) {
143+ throw new FileSystemError ( {
144+ provider : "baidu" ,
145+ message : `File already exists: ${ this . path } ` ,
146+ status : 409 ,
147+ code : "nameAlreadyExists" ,
148+ conflict : true ,
149+ } ) ;
150+ }
151+ return ;
152+ }
153+
154+ if ( this . opts ?. expectedDigest && existing ?. digest !== this . opts . expectedDigest ) {
155+ throw new FileSystemError ( {
156+ provider : "baidu" ,
157+ message : `Baidu file digest changed before write: ${ this . path } ` ,
158+ status : 412 ,
159+ code : "digestMismatch" ,
160+ conflict : true ,
161+ } ) ;
162+ }
163+ }
127164}
0 commit comments