Unverified Commit 71cc4881 authored by An Nyeong's avatar An Nyeong
Browse files

Fix cas() error with undefined newValue

cas() has an error when set a key with undefined newValue.

Added controll of edge case and a test case.
parent 80b71541
Loading
Loading
Loading
Loading
+2 −0
Original line number Diff line number Diff line
@@ -180,6 +180,8 @@ test("SqliteKvStore.cas()", async () => {
    assert.strictEqual(await store.get(["foo", "bar"]), undefined);
    assert.strictEqual(await store.cas(["foo", "bar"], undefined, "baz"), true);
    assert.strictEqual(await store.get(["foo", "bar"]), "baz");
    assert.strictEqual(await store.cas(["foo", "bar"], "baz", undefined), true);
    assert.strictEqual(await store.get(["foo", "bar"]), undefined);
  } finally {
    await store.drop();
    await db.close();
+11 −5
Original line number Diff line number Diff line
@@ -142,7 +142,6 @@ export class SqliteKvStore implements KvStore {
    await this.initialize();

    const encodedKey = this.#encodeKey(key);
    const newValueJson = this.#encodeValue(newValue);
    const now = Temporal.Now.instant().epochMilliseconds;
    const expiresAt = options?.ttl !== undefined
      ? now + options.ttl.total({ unit: "milliseconds" })
@@ -167,6 +166,15 @@ export class SqliteKvStore implements KvStore {
        return false;
      }

      if (newValue === undefined) {
        this.#db
          .prepare(`
            DELETE FROM "${this.#tableName}" WHERE key = ?
          `)
          .run(encodedKey);
      } else {
      const newValueJson = this.#encodeValue(newValue);
      
      if (currentResult) {
        this.#db
          .prepare(`
@@ -175,7 +183,7 @@ export class SqliteKvStore implements KvStore {
            WHERE key = ?
          `)
          .run(newValueJson, expiresAt, encodedKey);
      } else if (newValue !== undefined) {
      } else {
        this.#db
          .prepare(`
            INSERT INTO "${this.#tableName}" (key, value, created, expires)
@@ -183,6 +191,7 @@ export class SqliteKvStore implements KvStore {
          `)
          .run(encodedKey, newValueJson, now, expiresAt);
      }
      }

      this.#db.exec("COMMIT");
      await this.#expire();
@@ -260,9 +269,6 @@ export class SqliteKvStore implements KvStore {
  }

  #encodeValue(value: unknown): string {
    if (value === undefined) {
      throw new RangeError("Cannot encode undefined value");
    }
    return JSON.stringify(value);
  }