Skip to content

Commit 48676d2

Browse files
authored
Add precondition check (#21)
* Add precondition check * Better message * Add precondition check for upsert
1 parent a95f27e commit 48676d2

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

src/handler/replace-document.ts

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,19 @@ export default async (
3131

3232
if (data.id !== body.id) {
3333
res.statusCode = 400;
34-
return { Message: "replacing id is not allowed" };
34+
return {
35+
code: "BadRequest",
36+
message: "replacing id is not allowed"
37+
};
38+
}
39+
40+
if (req.headers["if-match"] && req.headers["if-match"] !== data._etag) {
41+
res.statusCode = 412;
42+
return {
43+
code: "PreconditionFailed",
44+
message:
45+
"Operation cannot be performed because one of the specified precondition is not met."
46+
};
3547
}
3648

3749
return collection.documents.replace(body);

src/handler/upsert-document.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,5 +26,17 @@ export default async (
2626
return {};
2727
}
2828

29+
if (req.headers["if-match"]) {
30+
const data = collection.document(body.id).read();
31+
if (data && req.headers["if-match"] !== data._etag) {
32+
res.statusCode = 412;
33+
return {
34+
code: "PreconditionFailed",
35+
message:
36+
"Operation cannot be performed because one of the specified precondition is not met."
37+
};
38+
}
39+
}
40+
2941
return collection.documents.upsert(body);
3042
};

0 commit comments

Comments
 (0)