Skip to content
This repository was archived by the owner on Mar 13, 2025. It is now read-only.

Commit e164a92

Browse files
committed
Support conditional R2Bucket#put()
1 parent 27432a4 commit e164a92

File tree

2 files changed

+16
-5
lines changed

2 files changed

+16
-5
lines changed

packages/tre/src/plugins/r2/gateway.ts

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,17 @@ export class R2Gateway {
102102
value: Uint8Array,
103103
options: R2PutOptions
104104
): Promise<R2Object> {
105-
const checksums = validate.key(key).size(value).hash(value, options);
105+
let meta: R2Object | undefined;
106+
try {
107+
meta = await this.head(key);
108+
} catch (e) {
109+
if (!(e instanceof NoSuchKey)) throw e;
110+
}
111+
const checksums = validate
112+
.key(key)
113+
.size(value)
114+
.condition(meta, options.onlyIf)
115+
.hash(value, options);
106116

107117
// build metadata
108118
const md5Hash = crypto.createHash("md5").update(value).digest("hex");

packages/tre/src/plugins/r2/validator.ts

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -94,10 +94,11 @@ export class Validator {
9494
return checksums;
9595
}
9696

97-
condition(meta: R2Object, onlyIf?: R2Conditional): Validator {
98-
// test conditional should it exist
99-
if (!testR2Conditional(onlyIf, meta) || meta?.size === 0) {
100-
throw new PreconditionFailed().attach(meta);
97+
condition(meta?: R2Object, onlyIf?: R2Conditional): Validator {
98+
if (onlyIf !== undefined && !testR2Conditional(onlyIf, meta)) {
99+
let error = new PreconditionFailed();
100+
if (meta !== undefined) error = error.attach(meta);
101+
throw error;
101102
}
102103
return this;
103104
}

0 commit comments

Comments
 (0)