Skip to content

Commit

Permalink
fix: handle API#kv.commit results correctly
Browse files Browse the repository at this point in the history
  • Loading branch information
jviide committed Jan 31, 2024
1 parent f8ce22b commit 2004759
Showing 1 changed file with 23 additions and 14 deletions.
37 changes: 23 additions & 14 deletions src/api/kv.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as v from "@badrap/valita";
import type { Client } from "./client.js";
import { Client, HTTPError } from "./client.js";

type KvKey = (number | string | boolean)[];

Expand Down Expand Up @@ -43,10 +43,7 @@ const ListResponse = v.object({
cursor: v.string().optional(),
});

const CommitResponse = v.union(
v.object({ ok: v.literal(true), versionstamp: v.string() }),
v.object({ ok: v.literal(false) }),
);
const CommitResponse = v.union(v.object({ versionstamp: v.string() }));

export class Kv {
constructor(private readonly client: Client) {}
Expand Down Expand Up @@ -137,14 +134,26 @@ class AtomicOperation {
}

async commit(): Promise<KvCommitResult | KvCommitError> {
return this.base.request({
method: "POST",
path: ["kv", "mutate"],
json: {
checks: this._checks,
mutations: this._mutations,
},
responseType: CommitResponse,
});
return this.base
.request({
method: "POST",
path: ["kv", "mutate"],
json: {
checks: this._checks,
mutations: this._mutations,
},
responseType: CommitResponse,
})
.then(
({ versionstamp }) => {
return { ok: true, versionstamp };
},
(err) => {
if (err instanceof HTTPError && err.statusCode === 409) {
return { ok: false };
}
throw err;
},
);
}
}

0 comments on commit 2004759

Please sign in to comment.