File
Blob: types/test/types/do.ts
| 1 | import { DurableObject } from "cloudflare:workers"; |
| 2 | import { expectTypeOf } from "expect-type"; |
| 3 | |
| 4 | // Aliased as SqlStorageValue, but let's assert it includes the raw types we expect |
| 5 | type Value = ArrayBuffer | string | number | null; |
| 6 | |
| 7 | class TestDOSql extends DurableObject { |
| 8 | test() { |
| 9 | const db = this.ctx.storage.sql; |
| 10 | |
| 11 | expectTypeOf<SqlStorage>(db); |
| 12 | |
| 13 | expectTypeOf<number>(db.databaseSize); |
| 14 | |
| 15 | // Verify default row type of exec |
| 16 | for (const row of db.exec("...")) { |
| 17 | expectTypeOf<Record<string, Value>>(row); |
| 18 | } |
| 19 | |
| 20 | // Verify scoped row type of exec |
| 21 | for (const row of db.exec<{ name: string; phone: number }>("...")) { |
| 22 | expectTypeOf<{ name: string; phone: number }>(row); |
| 23 | |
| 24 | // @ts-expect-error double-checking our assertions are strict |
| 25 | expectTypeOf<{ name: string; phone: string }>(row); |
| 26 | // @ts-expect-error double-checking our assertions are strict |
| 27 | expectTypeOf<Record<string, number>>(row); |
| 28 | } |
| 29 | |
| 30 | const cursor = db.exec("...", 1, "two") |
| 31 | expectTypeOf<SqlStorageCursor<Record<string, Value>>>(cursor); |
| 32 | |
| 33 | expectTypeOf<number>(cursor.rowsRead); |
| 34 | expectTypeOf<number>(cursor.rowsWritten); |
| 35 | expectTypeOf<string[]>(cursor.columnNames); |
| 36 | |
| 37 | expectTypeOf<Record<string, Value>[]>(cursor.toArray()); |
| 38 | expectTypeOf<Record<string, Value>>(cursor.one()); |
| 39 | |
| 40 | const next = cursor.next(); |
| 41 | // Can narrow the type by checking .done |
| 42 | if (!next.done) { |
| 43 | expectTypeOf<Record<string, Value>>(next.value); |
| 44 | } |
| 45 | |
| 46 | const another = cursor.next() |
| 47 | // Or check .value to do the same thing |
| 48 | if (another.value) { |
| 49 | expectTypeOf<Record<string, Value>>(another.value); |
| 50 | expectTypeOf<false | undefined>(another.done); |
| 51 | } else { |
| 52 | expectTypeOf<undefined>(another.value); |
| 53 | expectTypeOf<true>(another.done); |
| 54 | } |
| 55 | |
| 56 | // Common shorthand usage |
| 57 | const { value: thirdRow } = cursor.next() |
| 58 | if (!thirdRow) throw new Error('No value!') |
| 59 | expectTypeOf<Record<string, Value>>(thirdRow); |
| 60 | } |
| 61 | } |