|
1 | | -import { describe, expect, it } from "vitest"; |
2 | | -import { v } from "../index"; |
| 1 | +import { describe, expect, expectTypeOf, it } from "vitest"; |
| 2 | +import { memoryAdapter, v } from "../index"; |
3 | 3 | import { attrsOf, validate } from "../schema"; |
4 | | -import { db, generateId, id } from "./db"; |
| 4 | +import type { ValueOfVar } from "../var"; |
| 5 | +import { db, generateId, id, schema } from "./db"; |
5 | 6 |
|
6 | 7 | const ALPHANUMERIC = /^[a-zA-Z0-9]+$/; |
7 | 8 |
|
@@ -64,3 +65,51 @@ describe("db.id", () => { |
64 | 65 | }); |
65 | 66 | }); |
66 | 67 | }); |
| 68 | + |
| 69 | +describe("schema", () => { |
| 70 | + it("is a named export and the same helper as db.schema", () => { |
| 71 | + expect(schema).toBe(db.schema); |
| 72 | + }); |
| 73 | + |
| 74 | + it("wraps v.var with default null and an object schema", () => { |
| 75 | + const user = schema("dbt_user", { |
| 76 | + id: db.id(v.string({})), |
| 77 | + email: db.unique(v.string()), |
| 78 | + }); |
| 79 | + expect(user.$var).toBe(true); |
| 80 | + expect(user.name).toBe("dbt_user"); |
| 81 | + expect(user.default).toBeNull(); |
| 82 | + expect(user.schema?.name).toBe("object"); |
| 83 | + expect(attrsOf(user.schema?.shape?.email, "db")).toEqual({ unique: true }); |
| 84 | + }); |
| 85 | + |
| 86 | + it("types the var as the row or null, and works as a storage model", async () => { |
| 87 | + const item = schema("dbt_item", { |
| 88 | + id: db.id(v.string({})), |
| 89 | + tag: v.string(), |
| 90 | + }); |
| 91 | + expectTypeOf<ValueOfVar<typeof item>>().toEqualTypeOf<{ |
| 92 | + id: string; |
| 93 | + tag: string; |
| 94 | + } | null>(); |
| 95 | + |
| 96 | + const store = v.storage(memoryAdapter(), { item }); |
| 97 | + type CreateArg = Parameters<typeof store.item.create>[0]; |
| 98 | + expectTypeOf<CreateArg>().toEqualTypeOf<{ tag: string; id?: string }>(); |
| 99 | + |
| 100 | + const created = await store.item.create({ tag: "a" }); |
| 101 | + expect(created.tag).toBe("a"); |
| 102 | + expect(created.id).toHaveLength(32); |
| 103 | + expect(await store.item.findOne({ id: created.id })).toEqual(created); |
| 104 | + |
| 105 | + const read = v.fn({ use: [{ item }] }, (c) => { |
| 106 | + expectTypeOf(c.dbt_item).toEqualTypeOf<{ |
| 107 | + id: string; |
| 108 | + tag: string; |
| 109 | + } | null>(); |
| 110 | + return c.dbt_item; |
| 111 | + }); |
| 112 | + expect(read()).toBeNull(); |
| 113 | + expect(read.with({ dbt_item: created })()).toEqual(created); |
| 114 | + }); |
| 115 | +}); |
0 commit comments