@supatype/client 0.8.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.turbo/turbo-build.log +1 -1
- package/.turbo/turbo-test.log +70 -69
- package/.turbo/turbo-typecheck.log +1 -1
- package/CHANGELOG.md +28 -0
- package/bin/supatype-prepare.js +68 -0
- package/dist/auth.d.ts +9 -0
- package/dist/auth.d.ts.map +1 -1
- package/dist/auth.js +30 -8
- package/dist/auth.js.map +1 -1
- package/dist/bindings.d.ts +1 -1
- package/dist/bindings.d.ts.map +1 -1
- package/dist/graphql-transport.d.ts +2 -2
- package/dist/graphql-transport.d.ts.map +1 -1
- package/dist/graphql-transport.js.map +1 -1
- package/dist/index.d.ts +16 -13
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +14 -11
- package/dist/index.js.map +1 -1
- package/dist/mutation-request.d.ts +17 -4
- package/dist/mutation-request.d.ts.map +1 -1
- package/dist/mutation-request.js +16 -14
- package/dist/mutation-request.js.map +1 -1
- package/dist/query.d.ts +40 -16
- package/dist/query.d.ts.map +1 -1
- package/dist/query.js +81 -21
- package/dist/query.js.map +1 -1
- package/package.json +5 -2
- package/src/auth.ts +29 -8
- package/src/bindings.ts +1 -1
- package/src/graphql-transport.ts +2 -2
- package/src/index.ts +20 -16
- package/src/mutation-request.ts +32 -18
- package/src/query.ts +102 -37
- package/tests/data-plane-auth.test.ts +1 -6
- package/tests/draft-insert.test.ts +9 -9
- package/tests/draft-update.test.ts +5 -5
- package/tests/minimal-writes.test.ts +118 -0
- package/tests/postgrest-error-codes.test.ts +1 -1
- package/tests/query.test.ts +3 -3
- package/tests/realtime-session-auth.test.ts +1 -4
- package/tests/rpc-resend.test.ts +33 -8
- package/tests/supatype-prepare.test.ts +139 -0
- package/tests/support/jwt.ts +4 -0
- package/tests/unauthorized-resend.test.ts +107 -0
- package/tsconfig.tsbuildinfo +1 -1
package/src/query.ts
CHANGED
|
@@ -173,22 +173,49 @@ export function bearerToken(headers: Record<string, string>): string {
|
|
|
173
173
|
// with plain `fetch` as it always has.
|
|
174
174
|
export type { RequestTransport }
|
|
175
175
|
|
|
176
|
-
/**
|
|
176
|
+
/**
|
|
177
|
+
* What a client does once the server has called `refusedToken` expired or invalid: refresh the
|
|
178
|
+
* session it belongs to, whatever the local clock says of it, and answer whether the session now
|
|
179
|
+
* holds a different token. False when there is no session, as for an anon caller.
|
|
180
|
+
*/
|
|
181
|
+
export type UnauthorizedHandler = (refusedToken: string) => Promise<boolean>
|
|
182
|
+
|
|
183
|
+
/** A token PostgREST could not verify, or whose claims it rejected (an expired token among them). */
|
|
184
|
+
const STALE_TOKEN_CODES: ReadonlySet<string> = new Set([PostgrestErrorCodes.JWT_INVALID, PostgrestErrorCodes.JWT_EXPIRED])
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* Whether a 401 refuses the token itself rather than what the caller asked to do.
|
|
188
|
+
*
|
|
189
|
+
* Read from a clone, so the caller still reads the body it is handed. A row rule refusing an anon
|
|
190
|
+
* write also answers 401 (42501), and sending that again only repeats the refusal.
|
|
191
|
+
*/
|
|
192
|
+
async function refusesToken(res: Response): Promise<boolean> {
|
|
193
|
+
const body = await readJsonObject(res.clone())
|
|
194
|
+
if (typeof body["code"] === "string" && STALE_TOKEN_CODES.has(body["code"])) return true
|
|
195
|
+
return /jwt expired/i.test(refusalText(body) ?? "")
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* Send once. On a 401 that refuses the token, refresh the session and send again, but only when the
|
|
200
|
+
* refresh produced a token other than the one refused: anything else would repeat the same request
|
|
201
|
+
* to the same answer, and a write twice.
|
|
202
|
+
*/
|
|
177
203
|
export async function fetchWithOptional401Retry(
|
|
178
204
|
send: RequestTransport,
|
|
179
205
|
url: string,
|
|
180
206
|
init: RequestInit & FetchOptions,
|
|
181
207
|
resolveHeaders: () => Promise<Record<string, string>>,
|
|
182
|
-
onUnauthorized?:
|
|
208
|
+
onUnauthorized?: UnauthorizedHandler | undefined,
|
|
183
209
|
): Promise<Response> {
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
if (res.status
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
return res
|
|
210
|
+
const headers = await resolveHeaders()
|
|
211
|
+
const res = await send(url, { ...init, headers })
|
|
212
|
+
if (res.status !== 401 || onUnauthorized === undefined) return res
|
|
213
|
+
const refused = bearerToken(headers)
|
|
214
|
+
if (!(await refusesToken(res)) || !(await onUnauthorized(refused))) return res
|
|
215
|
+
const refreshed = await resolveHeaders()
|
|
216
|
+
// A preview link or a caller-supplied header can outrank the session, and then nothing changed.
|
|
217
|
+
if (bearerToken(refreshed) === refused) return res
|
|
218
|
+
return send(url, { ...init, headers: refreshed })
|
|
192
219
|
}
|
|
193
220
|
|
|
194
221
|
/**
|
|
@@ -208,7 +235,7 @@ export class QueryBuilder<TRow> extends FilterBuilder implements PromiseLike<Que
|
|
|
208
235
|
private readonly baseUrl: string
|
|
209
236
|
private readonly path: string
|
|
210
237
|
private readonly getHeaders: HeadersProvider
|
|
211
|
-
private readonly onUnauthorized:
|
|
238
|
+
private readonly onUnauthorized: UnauthorizedHandler | undefined
|
|
212
239
|
private readonly send: RequestTransport
|
|
213
240
|
private readonly extraHeaders: Record<string, string>
|
|
214
241
|
private readonly queryCache: QueryCache
|
|
@@ -222,7 +249,7 @@ export class QueryBuilder<TRow> extends FilterBuilder implements PromiseLike<Que
|
|
|
222
249
|
headers: Record<string, string> | HeadersProvider,
|
|
223
250
|
columns?: string | undefined,
|
|
224
251
|
queryCache: QueryCache = defaultQueryCache,
|
|
225
|
-
onUnauthorized?:
|
|
252
|
+
onUnauthorized?: UnauthorizedHandler | undefined,
|
|
226
253
|
selectOptions?: SelectQueryOptions | undefined,
|
|
227
254
|
transport: RequestTransport = plainFetch,
|
|
228
255
|
) {
|
|
@@ -483,13 +510,38 @@ export interface MutationOptions {
|
|
|
483
510
|
type ReturnedRow<TRow, TTables, TName extends string, TColumns extends string> =
|
|
484
511
|
[TTables] extends [Record<string, TableDef>] ? SelectRow<TTables, TName, TColumns> : TRow
|
|
485
512
|
|
|
486
|
-
|
|
513
|
+
/**
|
|
514
|
+
* The boundary between what a write resolved to and what its builder is typed to resolve to.
|
|
515
|
+
*
|
|
516
|
+
* `select()` both asks for the rows and types the builder as returning them, so a builder typed
|
|
517
|
+
* `null` resolves to `null` and one typed with rows resolves to the rows. That each row has the
|
|
518
|
+
* caller's row type is the same unchecked claim `isCallerRow` describes.
|
|
519
|
+
*/
|
|
520
|
+
function isWriteResult<TResult>(value: unknown): value is TResult {
|
|
521
|
+
return value === null || Array.isArray(value)
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
/** `single()` or `maybeSingle()` on a write that asked for no rows, refused before anything is sent. */
|
|
525
|
+
function rowNotSelected(): { data: null; error: SupatypeError; count: null } {
|
|
526
|
+
const message = "A write returns no rows until select() asks for them: call select() before single() or maybeSingle()"
|
|
527
|
+
return { data: null, error: { message }, count: null }
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
/**
|
|
531
|
+
* An insert, update, upsert or delete.
|
|
532
|
+
*
|
|
533
|
+
* Asks for no rows back, as postgrest-js does, and resolves to `data: null`: returning a row needs
|
|
534
|
+
* the right to read it, so a table whose rules let a caller create but not read refused every write
|
|
535
|
+
* that asked. `select()` asks for the rows and types `TResult` as them; `single()` and
|
|
536
|
+
* `maybeSingle()` exist only after it.
|
|
537
|
+
*/
|
|
538
|
+
export class MutationBuilder<TRow, TTables = unknown, TName extends string = string, TResult = null>
|
|
487
539
|
extends FilterBuilder
|
|
488
|
-
implements PromiseLike<QueryResult<
|
|
540
|
+
implements PromiseLike<QueryResult<TResult>> {
|
|
489
541
|
private readonly baseUrl: string
|
|
490
542
|
private readonly path: string
|
|
491
543
|
private readonly getHeaders: HeadersProvider
|
|
492
|
-
private readonly onUnauthorized:
|
|
544
|
+
private readonly onUnauthorized: UnauthorizedHandler | undefined
|
|
493
545
|
private readonly send: RequestTransport
|
|
494
546
|
private readonly extraHeaders: Record<string, string>
|
|
495
547
|
private readonly method: HttpMethod
|
|
@@ -497,6 +549,8 @@ export class MutationBuilder<TRow, TTables = unknown, TName extends string = str
|
|
|
497
549
|
private readonly createThrough: DraftCreate | undefined
|
|
498
550
|
private readonly editThrough: DraftEdit | undefined
|
|
499
551
|
private readonly refusal: SupatypeError | undefined
|
|
552
|
+
/** Set by `select()`: the write asks for the rows it wrote and resolves to them. */
|
|
553
|
+
private returning = false
|
|
500
554
|
|
|
501
555
|
constructor(
|
|
502
556
|
baseUrl: string,
|
|
@@ -505,7 +559,7 @@ export class MutationBuilder<TRow, TTables = unknown, TName extends string = str
|
|
|
505
559
|
method: HttpMethod,
|
|
506
560
|
body?: unknown,
|
|
507
561
|
opts?: MutationOptions | undefined,
|
|
508
|
-
onUnauthorized?:
|
|
562
|
+
onUnauthorized?: UnauthorizedHandler | undefined,
|
|
509
563
|
transport: RequestTransport = plainFetch,
|
|
510
564
|
) {
|
|
511
565
|
super()
|
|
@@ -522,8 +576,6 @@ export class MutationBuilder<TRow, TTables = unknown, TName extends string = str
|
|
|
522
576
|
this.refusal = opts?.refusal
|
|
523
577
|
|
|
524
578
|
if (opts?.upsert === true) this.prefer("resolution=merge-duplicates")
|
|
525
|
-
// Return inserted/updated rows
|
|
526
|
-
if (method !== "DELETE") this.prefer("return=representation")
|
|
527
579
|
}
|
|
528
580
|
|
|
529
581
|
private prefer(preference: string): void {
|
|
@@ -535,24 +587,26 @@ export class MutationBuilder<TRow, TTables = unknown, TName extends string = str
|
|
|
535
587
|
/**
|
|
536
588
|
* Return the written rows, limited to `columns`.
|
|
537
589
|
*
|
|
538
|
-
* Asks for the representation
|
|
539
|
-
*
|
|
590
|
+
* Asks for the representation, which no write does without it: the caller needs the right to
|
|
591
|
+
* read the rows as well as to write them.
|
|
540
592
|
*/
|
|
541
593
|
select<TColumns extends string = "*">(
|
|
542
594
|
columns?: TColumns | undefined,
|
|
543
|
-
): MutationBuilder<ReturnedRow<TRow, TTables, TName, TColumns>, TTables, TName>
|
|
544
|
-
/** Return the written rows typed as `
|
|
545
|
-
select<
|
|
546
|
-
// The same request, now described as returning the selected shape rather than
|
|
595
|
+
): MutationBuilder<ReturnedRow<TRow, TTables, TName, TColumns>, TTables, TName, ReturnedRow<TRow, TTables, TName, TColumns>[]>
|
|
596
|
+
/** Return the written rows typed as `TSelected`, for a shape the select string cannot describe. */
|
|
597
|
+
select<TSelected>(columns?: string | undefined): MutationBuilder<TSelected, TTables, TName, TSelected[]>
|
|
598
|
+
// The same request, now described as returning the selected shape rather than nothing. The
|
|
547
599
|
// overloads above say which shape; the row type is the caller's claim, checked by nothing at
|
|
548
600
|
// runtime, so the builder itself is returned rather than a copy that would split the request.
|
|
549
|
-
select(columns?: string | undefined): MutationBuilder<unknown, TTables, TName> {
|
|
601
|
+
select(columns?: string | undefined): MutationBuilder<unknown, TTables, TName, unknown> {
|
|
550
602
|
this.params.set("select", columns ?? "*")
|
|
551
603
|
this.prefer("return=representation")
|
|
604
|
+
this.returning = true
|
|
552
605
|
return this
|
|
553
606
|
}
|
|
554
607
|
|
|
555
|
-
async single(): Promise<QueryResult<TRow>> {
|
|
608
|
+
async single(this: MutationBuilder<TRow, TTables, TName, TRow[]>): Promise<QueryResult<TRow>> {
|
|
609
|
+
if (!this.returning) return rowNotSelected()
|
|
556
610
|
const { data, error, count, meta } = await this._execute({
|
|
557
611
|
Accept: "application/vnd.pgrst.object+json",
|
|
558
612
|
})
|
|
@@ -569,18 +623,26 @@ export class MutationBuilder<TRow, TTables = unknown, TName extends string = str
|
|
|
569
623
|
return { data: row, error: null, count: 1, ...(meta && { meta }) }
|
|
570
624
|
}
|
|
571
625
|
|
|
572
|
-
async maybeSingle(): Promise<QueryResult<TRow | null>> {
|
|
626
|
+
async maybeSingle(this: MutationBuilder<TRow, TTables, TName, TRow[]>): Promise<QueryResult<TRow | null>> {
|
|
627
|
+
if (!this.returning) return rowNotSelected()
|
|
573
628
|
const { data, error, count, meta } = await this._execute({})
|
|
574
629
|
if (error !== null) return { data: null, error, count: null, ...(meta && { meta }) }
|
|
575
630
|
const row = data !== null && data.length > 0 ? (data[0] ?? null) : null
|
|
576
631
|
return { data: row, error: null, count, ...(meta && { meta }) }
|
|
577
632
|
}
|
|
578
633
|
|
|
579
|
-
then<R1 = QueryResult<
|
|
580
|
-
onfulfilled?: ((value: QueryResult<
|
|
634
|
+
then<R1 = QueryResult<TResult>, R2 = never>(
|
|
635
|
+
onfulfilled?: ((value: QueryResult<TResult>) => R1 | PromiseLike<R1>) | null | undefined,
|
|
581
636
|
onrejected?: ((reason: unknown) => R2 | PromiseLike<R2>) | null | undefined,
|
|
582
637
|
): PromiseLike<R1 | R2> {
|
|
583
|
-
return this._execute()
|
|
638
|
+
return this._execute()
|
|
639
|
+
.then(({ data, ...rest }): QueryResult<TResult> => ({ ...rest, data: isWriteResult<TResult>(data) ? data : null }))
|
|
640
|
+
.then(onfulfilled, onrejected)
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
/** A write that succeeded with no rows to give: `[]` when `select()` asked for them, else null. */
|
|
644
|
+
private nothingReturned(): QueryResult<TRow[]> {
|
|
645
|
+
return this.returning ? { data: [], error: null, count: 0 } : { data: null, error: null, count: null }
|
|
584
646
|
}
|
|
585
647
|
|
|
586
648
|
/** POST, PATCH and DELETE: the transport applies the timeout and never retries them. */
|
|
@@ -620,9 +682,8 @@ export class MutationBuilder<TRow, TTables = unknown, TName extends string = str
|
|
|
620
682
|
return { data: null, error, count: null }
|
|
621
683
|
}
|
|
622
684
|
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
}
|
|
685
|
+
// Nothing asked for and so nothing to read: PostgREST answers 201 or 204 with no body.
|
|
686
|
+
if (!this.returning || res.status === 204) return this.nothingReturned()
|
|
626
687
|
|
|
627
688
|
// The returned representation of what was just written, so it needs the same care as a read.
|
|
628
689
|
const result = readRows<TRow>(await res.text(), this.path, res.status, null)
|
|
@@ -630,7 +691,8 @@ export class MutationBuilder<TRow, TTables = unknown, TName extends string = str
|
|
|
630
691
|
}
|
|
631
692
|
|
|
632
693
|
/**
|
|
633
|
-
* Create the records as their first drafts, then read them back as an
|
|
694
|
+
* Create the records as their first drafts, then, when `select()` asked, read them back as an
|
|
695
|
+
* insert returns them.
|
|
634
696
|
*
|
|
635
697
|
* Read from the draft view, which has the table's row type: the live row of a new record holds no
|
|
636
698
|
* locale yet, so reading the table would hand back empty translations for what was just written.
|
|
@@ -645,8 +707,9 @@ export class MutationBuilder<TRow, TTables = unknown, TName extends string = str
|
|
|
645
707
|
}
|
|
646
708
|
|
|
647
709
|
/**
|
|
648
|
-
* Save a draft of each record the filters match, publishing it too when asked, then
|
|
649
|
-
* drafts back as an update returns its rows. The live rows are left to
|
|
710
|
+
* Save a draft of each record the filters match, publishing it too when asked, then, when
|
|
711
|
+
* `select()` asked, read the drafts back as an update returns its rows. The live rows are left to
|
|
712
|
+
* publishing.
|
|
650
713
|
*
|
|
651
714
|
* The records are the ones the caller reads in the table under the update's filters, as a `PATCH`
|
|
652
715
|
* would match them, and `save_drafts` saves all of them or none.
|
|
@@ -655,7 +718,7 @@ export class MutationBuilder<TRow, TTables = unknown, TName extends string = str
|
|
|
655
718
|
const matched = await this.matchedKeys(target.primaryKey)
|
|
656
719
|
if (!Array.isArray(matched)) return { data: null, error: matched, count: null }
|
|
657
720
|
// A `PATCH` that matches nothing answers no rows, and so does this, having saved nothing.
|
|
658
|
-
if (matched.length === 0) return
|
|
721
|
+
if (matched.length === 0) return this.nothingReturned()
|
|
659
722
|
const body = { model_table: target.table, record_ids: matched, data: this.body, publish: target.publish }
|
|
660
723
|
const keys = await this.callPublishing("save_drafts", body)
|
|
661
724
|
if (!Array.isArray(keys)) return { data: null, error: keys, count: null }
|
|
@@ -681,6 +744,8 @@ export class MutationBuilder<TRow, TTables = unknown, TName extends string = str
|
|
|
681
744
|
|
|
682
745
|
/** `keys`' newest drafts, from the draft view, with this write's select and in the order given. */
|
|
683
746
|
private async readDrafts(target: DraftCreate, keys: string[]): Promise<QueryResult<TRow[]>> {
|
|
747
|
+
// Only when asked: reading the drafts needs the right to read them, as returning a row does.
|
|
748
|
+
if (!this.returning) return this.nothingReturned()
|
|
684
749
|
const select = readBackColumns(this.params.get("select"), target.primaryKey, keys.length)
|
|
685
750
|
const result = await new QueryBuilder<Record<string, unknown>>(
|
|
686
751
|
this.baseUrl,
|
|
@@ -5,17 +5,12 @@
|
|
|
5
5
|
import { describe, it, expect, vi, beforeEach } from "vitest"
|
|
6
6
|
import { createClient } from "../src/index.js"
|
|
7
7
|
import { fetchCalls, header, jsonResponse, requestUrl } from "./support/fetch-mock.js"
|
|
8
|
+
import { fakeJwt } from "./support/jwt.js"
|
|
8
9
|
|
|
9
10
|
const BASE = "http://localhost:18473"
|
|
10
11
|
const ANON_KEY = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoiYW5vbiJ9.test"
|
|
11
12
|
const AUTH = `${BASE}/auth/v1`
|
|
12
13
|
|
|
13
|
-
function fakeJwt(payload: Record<string, unknown>): string {
|
|
14
|
-
const header = btoa(JSON.stringify({ alg: "HS256", typ: "JWT" }))
|
|
15
|
-
const body = btoa(JSON.stringify(payload))
|
|
16
|
-
return `${header}.${body}.sig`
|
|
17
|
-
}
|
|
18
|
-
|
|
19
14
|
const RAW_USER = {
|
|
20
15
|
id: "user-1",
|
|
21
16
|
email: "a@b.com",
|
|
@@ -92,9 +92,9 @@ describe("insert on a model that keeps drafts", () => {
|
|
|
92
92
|
expect(header(readBack?.init ?? {}, "Accept-Profile")).toBe("draft")
|
|
93
93
|
})
|
|
94
94
|
|
|
95
|
-
it("returns the row as a plain insert would", async () => {
|
|
95
|
+
it("returns the row as a plain insert would, once select() asks", async () => {
|
|
96
96
|
serve(draftsServer())
|
|
97
|
-
const { data, error, count } = await client().from("posts").insert({ title: "Mine" })
|
|
97
|
+
const { data, error, count } = await client().from("posts").insert({ title: "Mine" }).select()
|
|
98
98
|
expect(error).toBeNull()
|
|
99
99
|
expect(data).toEqual([ROW])
|
|
100
100
|
expect(count).toBe(1)
|
|
@@ -109,7 +109,7 @@ describe("insert on a model that keeps drafts", () => {
|
|
|
109
109
|
|
|
110
110
|
it("treats a one-row array as one record", async () => {
|
|
111
111
|
const fetch = serve(draftsServer())
|
|
112
|
-
const { data } = await client().from("posts").insert([{ title: "Mine" }])
|
|
112
|
+
const { data } = await client().from("posts").insert([{ title: "Mine" }]).select()
|
|
113
113
|
expect(fetchCalls(fetch)[0]?.url).toBe(`${BASE}/rest/v1/rpc/create_record`)
|
|
114
114
|
expect(jsonBody(fetchCalls(fetch)[0]?.init ?? {})["data"]).toEqual({ title: "Mine" })
|
|
115
115
|
expect(data).toEqual([ROW])
|
|
@@ -158,8 +158,8 @@ describe("insert on a model that keeps drafts", () => {
|
|
|
158
158
|
|
|
159
159
|
it("leaves an empty insert a plain write, which creates nothing", async () => {
|
|
160
160
|
const fetch = serve(mockFetch(() => Promise.resolve(jsonResponse([], 201))))
|
|
161
|
-
const { data } = await client().from("posts").insert([])
|
|
162
|
-
expect(fetchCalls(fetch).map((call) => call.url)).toEqual([`${BASE}/rest/v1/posts
|
|
161
|
+
const { data } = await client().from("posts").insert([]).select()
|
|
162
|
+
expect(fetchCalls(fetch).map((call) => call.url)).toEqual([`${BASE}/rest/v1/posts?select=*`])
|
|
163
163
|
expect(data).toEqual([])
|
|
164
164
|
})
|
|
165
165
|
|
|
@@ -189,7 +189,7 @@ describe("insert on a model that keeps drafts", () => {
|
|
|
189
189
|
|
|
190
190
|
it("reaches the framework bindings, which insert through runMutation", async () => {
|
|
191
191
|
const fetch = serve(draftsServer())
|
|
192
|
-
const outcome = await runMutation(client(), "posts", "insert", { title: "Mine" })
|
|
192
|
+
const outcome = await runMutation(client(), "posts", "insert", { title: "Mine" }, { select: true })
|
|
193
193
|
expect(fetchCalls(fetch)[0]?.url).toBe(`${BASE}/rest/v1/rpc/create_record`)
|
|
194
194
|
expect(outcome.data).toEqual([ROW])
|
|
195
195
|
})
|
|
@@ -201,12 +201,12 @@ describe("insert on a model that keeps no drafts", () => {
|
|
|
201
201
|
vi.unstubAllGlobals()
|
|
202
202
|
})
|
|
203
203
|
|
|
204
|
-
it("is a plain insert asking for the row back", async () => {
|
|
204
|
+
it("is a plain insert, asking for the row back once select() does", async () => {
|
|
205
205
|
registerDraftModels({ version: 1, tables: { posts: { primaryKey: "id" } } })
|
|
206
206
|
const fetch = serve(mockFetch(() => Promise.resolve(jsonResponse([{ id: 1 }], 201))))
|
|
207
|
-
await client().from("tags").insert({ label: "news" })
|
|
207
|
+
await client().from("tags").insert({ label: "news" }).select()
|
|
208
208
|
const [only] = fetchCalls(fetch)
|
|
209
|
-
expect(only?.url).toBe(`${BASE}/rest/v1/tags
|
|
209
|
+
expect(only?.url).toBe(`${BASE}/rest/v1/tags?select=*`)
|
|
210
210
|
expect(header(only?.init ?? {}, "Prefer")).toContain("return=representation")
|
|
211
211
|
})
|
|
212
212
|
|
|
@@ -96,7 +96,7 @@ describe("update on a model that keeps drafts", () => {
|
|
|
96
96
|
|
|
97
97
|
it("saves nothing when the filters match no record, as a PATCH that matches nothing", async () => {
|
|
98
98
|
const fetch = serve(draftsServer([]))
|
|
99
|
-
const { data, error, count } = await client().from("posts").update({ title: "Edited" }).eq("id", ID)
|
|
99
|
+
const { data, error, count } = await client().from("posts").update({ title: "Edited" }).eq("id", ID).select()
|
|
100
100
|
expect(fetchCalls(fetch)).toHaveLength(1)
|
|
101
101
|
expect({ data, error, count }).toEqual({ data: [], error: null, count: 0 })
|
|
102
102
|
})
|
|
@@ -116,7 +116,7 @@ describe("update on a model that keeps drafts", () => {
|
|
|
116
116
|
|
|
117
117
|
it("reaches the framework bindings, which update through runMutation", async () => {
|
|
118
118
|
const fetch = serve(draftsServer())
|
|
119
|
-
const outcome = await runMutation(client(), "posts", "update", { title: "Edited" }, { id: ID },
|
|
119
|
+
const outcome = await runMutation(client(), "posts", "update", { title: "Edited" }, { filter: { id: ID }, publish: true, select: true })
|
|
120
120
|
expect(fetchCalls(fetch)[1]?.url).toBe(`${BASE}/rest/v1/rpc/save_drafts`)
|
|
121
121
|
expect(jsonBody(fetchCalls(fetch)[1]?.init ?? {})["publish"]).toBe(true)
|
|
122
122
|
expect(outcome.data).toEqual([DRAFT])
|
|
@@ -129,14 +129,14 @@ describe("update on a model that keeps no drafts", () => {
|
|
|
129
129
|
vi.unstubAllGlobals()
|
|
130
130
|
})
|
|
131
131
|
|
|
132
|
-
it("is a plain PATCH asking for the rows back", async () => {
|
|
132
|
+
it("is a plain PATCH, asking for the rows back once select() does", async () => {
|
|
133
133
|
registerDraftModels({ version: 1, tables: { posts: { primaryKey: "id" } } })
|
|
134
134
|
const fetch = serve(mockFetch(() => Promise.resolve(jsonResponse([{ id: 1, label: "news" }]))))
|
|
135
|
-
const { data } = await client().from("tags").update({ label: "news" }).eq("id", 1)
|
|
135
|
+
const { data } = await client().from("tags").update({ label: "news" }).eq("id", 1).select()
|
|
136
136
|
const [only] = fetchCalls(fetch)
|
|
137
137
|
expect(fetchCalls(fetch)).toHaveLength(1)
|
|
138
138
|
expect(only?.init.method).toBe("PATCH")
|
|
139
|
-
expect(only?.url).toBe(`${BASE}/rest/v1/tags?id=eq.1
|
|
139
|
+
expect(only?.url).toBe(`${BASE}/rest/v1/tags?id=eq.1&select=*`)
|
|
140
140
|
expect(header(only?.init ?? {}, "Prefer")).toContain("return=representation")
|
|
141
141
|
expect(data).toEqual([{ id: 1, label: "news" }])
|
|
142
142
|
})
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { afterEach, beforeEach, describe, expect, expectTypeOf, it, vi } from "vitest"
|
|
2
|
+
import { createClient, forgetRegisteredDraftModels, registerDraftModels, type AnyDatabase, type QueryResult } from "../src/index.js"
|
|
3
|
+
import { fetchCalls, header, jsonResponse, mockFetch, requestUrl, type FetchMock } from "./support/fetch-mock.js"
|
|
4
|
+
|
|
5
|
+
// A write asks for no rows back unless `.select()` says to, as postgrest-js does. Returning a row
|
|
6
|
+
// needs SELECT on it, so a table whose rules let a caller create but not read refused every insert
|
|
7
|
+
// that asked: an anon order form, say, answered 401 42501 for a row it was allowed to write.
|
|
8
|
+
|
|
9
|
+
const BASE = "http://localhost:18473"
|
|
10
|
+
const ID = "7b1f115e-418d-4e92-91d0-f199ebd06e5e"
|
|
11
|
+
const ROW = { id: ID, title: "Mine" }
|
|
12
|
+
|
|
13
|
+
/** PostgREST answering a write that asked for nothing back: 201 or 204, and no body. */
|
|
14
|
+
function minimalServer(): FetchMock {
|
|
15
|
+
return mockFetch((_input, init) => {
|
|
16
|
+
const prefer = header(init ?? {}, "Prefer") ?? ""
|
|
17
|
+
if (prefer.includes("return=representation")) return Promise.resolve(jsonResponse([ROW], 201))
|
|
18
|
+
return Promise.resolve(new Response(null, { status: init?.method === "POST" ? 201 : 204 }))
|
|
19
|
+
})
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function serve(fetch: FetchMock): FetchMock {
|
|
23
|
+
vi.stubGlobal("fetch", fetch)
|
|
24
|
+
return fetch
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const client = () => createClient<AnyDatabase>({ url: BASE, anonKey: "anon-key", auth: { persistSession: false } })
|
|
28
|
+
|
|
29
|
+
describe("a write without select()", () => {
|
|
30
|
+
afterEach(() => vi.unstubAllGlobals())
|
|
31
|
+
|
|
32
|
+
it("insert asks for no representation and resolves to no rows", async () => {
|
|
33
|
+
const fetch = serve(minimalServer())
|
|
34
|
+
const result = await client().from("orders").insert({ title: "Mine" })
|
|
35
|
+
expect(header(fetchCalls(fetch)[0]?.init ?? {}, "Prefer")).toBeNull()
|
|
36
|
+
expect(result).toEqual({ data: null, error: null, count: null })
|
|
37
|
+
})
|
|
38
|
+
|
|
39
|
+
it("update asks for no representation and resolves to no rows", async () => {
|
|
40
|
+
const fetch = serve(minimalServer())
|
|
41
|
+
const result = await client().from("orders").update({ title: "Edited" }).eq("id", ID)
|
|
42
|
+
expect(header(fetchCalls(fetch)[0]?.init ?? {}, "Prefer")).toBeNull()
|
|
43
|
+
expect(result).toEqual({ data: null, error: null, count: null })
|
|
44
|
+
})
|
|
45
|
+
|
|
46
|
+
it("upsert keeps only its conflict resolution", async () => {
|
|
47
|
+
const fetch = serve(minimalServer())
|
|
48
|
+
const result = await client().from("orders").upsert({ id: ID, title: "Mine" })
|
|
49
|
+
expect(header(fetchCalls(fetch)[0]?.init ?? {}, "Prefer")).toBe("resolution=merge-duplicates")
|
|
50
|
+
expect(result.data).toBeNull()
|
|
51
|
+
})
|
|
52
|
+
|
|
53
|
+
it("delete resolves to no rows", async () => {
|
|
54
|
+
serve(minimalServer())
|
|
55
|
+
const result = await client().from("orders").delete().eq("id", ID)
|
|
56
|
+
expect(result).toEqual({ data: null, error: null, count: null })
|
|
57
|
+
})
|
|
58
|
+
})
|
|
59
|
+
|
|
60
|
+
describe("a write with select()", () => {
|
|
61
|
+
afterEach(() => vi.unstubAllGlobals())
|
|
62
|
+
|
|
63
|
+
it("asks for the representation and resolves to the rows", async () => {
|
|
64
|
+
const fetch = serve(minimalServer())
|
|
65
|
+
const { data, count } = await client().from("orders").insert({ title: "Mine" }).select()
|
|
66
|
+
expect(header(fetchCalls(fetch)[0]?.init ?? {}, "Prefer")).toBe("return=representation")
|
|
67
|
+
expect({ data, count }).toEqual({ data: [ROW], count: 1 })
|
|
68
|
+
})
|
|
69
|
+
})
|
|
70
|
+
|
|
71
|
+
describe("a drafts-model write without select()", () => {
|
|
72
|
+
beforeEach(() => registerDraftModels({ version: 1, tables: { posts: { primaryKey: "id" } } }))
|
|
73
|
+
afterEach(() => {
|
|
74
|
+
forgetRegisteredDraftModels()
|
|
75
|
+
vi.unstubAllGlobals()
|
|
76
|
+
})
|
|
77
|
+
|
|
78
|
+
/** create_record and save_drafts answer with the record keys; a table read names the matches. */
|
|
79
|
+
function draftsServer(): FetchMock {
|
|
80
|
+
return mockFetch((input) => {
|
|
81
|
+
const url = requestUrl(input)
|
|
82
|
+
if (url.endsWith("/rpc/create_record")) return Promise.resolve(jsonResponse({ record_id: ID, version: 1 }))
|
|
83
|
+
if (url.endsWith("/rpc/save_drafts")) return Promise.resolve(jsonResponse([{ record_id: ID, version: 2 }]))
|
|
84
|
+
return Promise.resolve(jsonResponse([ROW]))
|
|
85
|
+
})
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
it("insert creates the record and reads nothing back", async () => {
|
|
89
|
+
const fetch = serve(draftsServer())
|
|
90
|
+
const result = await client().from("posts").insert({ title: "Mine" })
|
|
91
|
+
expect(fetchCalls(fetch).map(({ url }) => url)).toEqual([`${BASE}/rest/v1/rpc/create_record`])
|
|
92
|
+
expect(result).toEqual({ data: null, error: null, count: null })
|
|
93
|
+
})
|
|
94
|
+
|
|
95
|
+
it("update saves the drafts and reads none of them back", async () => {
|
|
96
|
+
const fetch = serve(draftsServer())
|
|
97
|
+
const result = await client().from("posts").update({ title: "Edited" }).eq("id", ID)
|
|
98
|
+
expect(fetchCalls(fetch).map(({ url }) => new URL(url).pathname)).toEqual(["/rest/v1/posts", "/rest/v1/rpc/save_drafts"])
|
|
99
|
+
expect(result).toEqual({ data: null, error: null, count: null })
|
|
100
|
+
})
|
|
101
|
+
})
|
|
102
|
+
|
|
103
|
+
// Checked by `tsc -p tests/tsconfig.json`, not by vitest.
|
|
104
|
+
type Order = { Row: { id: string; title: string }; Insert: { title: string }; Update: { title?: string } }
|
|
105
|
+
type Shop = { public: { Tables: { orders: Order } } }
|
|
106
|
+
|
|
107
|
+
describe("the types of a write", () => {
|
|
108
|
+
it("resolve to null without select(), to rows with it, and allow single() only after it", () => {
|
|
109
|
+
const typed = createClient<Shop>({ url: BASE, anonKey: "anon-key" })
|
|
110
|
+
expectTypeOf(typed.from("orders").insert({ title: "x" })).resolves.toEqualTypeOf<QueryResult<null>>()
|
|
111
|
+
expectTypeOf(typed.from("orders").insert({ title: "x" }).select("id")).resolves.toEqualTypeOf<QueryResult<{ id: string }[]>>()
|
|
112
|
+
void typed.from("orders").insert({ title: "x" }).select().single()
|
|
113
|
+
// @ts-expect-error a write returns no row until select() asks for one
|
|
114
|
+
void typed.from("orders").insert({ title: "x" }).single()
|
|
115
|
+
// @ts-expect-error a write returns no row until select() asks for one
|
|
116
|
+
void typed.from("orders").update({ title: "x" }).eq("id", ID).maybeSingle()
|
|
117
|
+
})
|
|
118
|
+
})
|
|
@@ -55,7 +55,7 @@ describe("single() without exactly one row", () => {
|
|
|
55
55
|
|
|
56
56
|
it("a write words it as PostgREST does", async () => {
|
|
57
57
|
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(emptyArray()))
|
|
58
|
-
const { error } = await new MutationBuilder("http://x", "/rest/v1/t", {}, "PATCH", {}).single()
|
|
58
|
+
const { error } = await new MutationBuilder("http://x", "/rest/v1/t", {}, "PATCH", {}).select().single()
|
|
59
59
|
vi.unstubAllGlobals()
|
|
60
60
|
expect(error).toEqual({ message: SINGLE_ROW_MESSAGE, code: "PGRST116" })
|
|
61
61
|
})
|
package/tests/query.test.ts
CHANGED
|
@@ -268,7 +268,7 @@ describe("MutationBuilder: insert", () => {
|
|
|
268
268
|
it("sends POST with body", async () => {
|
|
269
269
|
const fetch = mockFetch([{ id: "1", title: "New", status: "draft" }])
|
|
270
270
|
vi.stubGlobal("fetch", fetch)
|
|
271
|
-
const { data, error } = await new MutationBuilder<Post>(BASE, PATH, HEADERS, "POST", { title: "New", status: "draft" })
|
|
271
|
+
const { data, error } = await new MutationBuilder<Post>(BASE, PATH, HEADERS, "POST", { title: "New", status: "draft" }).select()
|
|
272
272
|
expect(error).toBeNull()
|
|
273
273
|
expect(data?.[0]?.id).toBe("1")
|
|
274
274
|
const { init } = fetchCall(fetch)
|
|
@@ -305,9 +305,9 @@ describe("MutationBuilder: update / delete", () => {
|
|
|
305
305
|
expect(url).toContain("id=eq.1")
|
|
306
306
|
})
|
|
307
307
|
|
|
308
|
-
it("204 No Content returns empty data array", async () => {
|
|
308
|
+
it("204 No Content to delete().select() returns an empty data array", async () => {
|
|
309
309
|
vi.stubGlobal("fetch", mockFetch(null, { status: 204 }))
|
|
310
|
-
const { data, error } = await new MutationBuilder<Post>(BASE, PATH, HEADERS, "DELETE").eq("id", "1")
|
|
310
|
+
const { data, error } = await new MutationBuilder<Post>(BASE, PATH, HEADERS, "DELETE").eq("id", "1").select()
|
|
311
311
|
expect(error).toBeNull()
|
|
312
312
|
expect(data).toEqual([])
|
|
313
313
|
})
|
|
@@ -22,6 +22,7 @@ import {
|
|
|
22
22
|
} from "./helpers/mock-websocket.js"
|
|
23
23
|
import { createClient } from "../src/index.js"
|
|
24
24
|
import type { Session } from "../src/types.js"
|
|
25
|
+
import { fakeJwt } from "./support/jwt.js"
|
|
25
26
|
|
|
26
27
|
const settle = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 10))
|
|
27
28
|
|
|
@@ -30,10 +31,6 @@ function bearerHeaders(token: string): Record<string, string> {
|
|
|
30
31
|
return { apikey: "anon-key", Authorization: `Bearer ${token}` }
|
|
31
32
|
}
|
|
32
33
|
|
|
33
|
-
function fakeJwt(payload: Record<string, unknown>): string {
|
|
34
|
-
return `${btoa(JSON.stringify({ alg: "HS256", typ: "JWT" }))}.${btoa(JSON.stringify(payload))}.sig`
|
|
35
|
-
}
|
|
36
|
-
|
|
37
34
|
const ANON_KEY = fakeJwt({ role: "anon" })
|
|
38
35
|
const USER_TOKEN = fakeJwt({
|
|
39
36
|
role: "authenticated",
|
package/tests/rpc-resend.test.ts
CHANGED
|
@@ -1,22 +1,47 @@
|
|
|
1
1
|
import { describe, it, expect, vi, beforeEach } from "vitest"
|
|
2
|
-
import { createClient } from "../src/index.js"
|
|
3
|
-
import { fetchCalls, header, jsonResponse, mockFetch } from "./support/fetch-mock.js"
|
|
2
|
+
import { createClient, type Session } from "../src/index.js"
|
|
3
|
+
import { fetchCalls, header, jsonResponse, mockFetch, requestUrl } from "./support/fetch-mock.js"
|
|
4
|
+
import { fakeJwt } from "./support/jwt.js"
|
|
5
|
+
|
|
6
|
+
// A resend follows only a refresh that replaced a refused session token, so the caller is signed in.
|
|
7
|
+
const NOW = Math.floor(Date.now() / 1000)
|
|
8
|
+
const userJwt = (n: number): string => fakeJwt({ role: "authenticated", sub: "u1", exp: NOW + 3600, n })
|
|
9
|
+
|
|
10
|
+
const USER = { id: "u1", appMetadata: {}, userMetadata: {}, createdAt: "2026-01-01T00:00:00Z", updatedAt: "2026-01-01T00:00:00Z" }
|
|
11
|
+
const SESSION: Session = { accessToken: userJwt(1), tokenType: "bearer", expiresIn: 3600, refreshToken: "rt-1", user: USER }
|
|
12
|
+
const REFRESHED = {
|
|
13
|
+
access_token: userJwt(2),
|
|
14
|
+
refresh_token: "rt-2",
|
|
15
|
+
token_type: "bearer",
|
|
16
|
+
expires_in: 3600,
|
|
17
|
+
user: { id: "u1", app_metadata: {}, user_metadata: {}, created_at: "2026-01-01T00:00:00Z", updated_at: "2026-01-01T00:00:00Z" },
|
|
18
|
+
}
|
|
4
19
|
|
|
5
20
|
describe("rpc: the resend after a 401 is the same request", () => {
|
|
6
21
|
beforeEach(() => vi.restoreAllMocks())
|
|
7
22
|
|
|
8
23
|
it("keeps Content-Profile and Prefer on the second send", async () => {
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
.
|
|
24
|
+
let refused = false
|
|
25
|
+
const fetch = mockFetch((input) => {
|
|
26
|
+
if (requestUrl(input).includes("/auth/v1/token")) return Promise.resolve(jsonResponse(REFRESHED))
|
|
27
|
+
if (refused) return Promise.resolve(jsonResponse(1, 200))
|
|
28
|
+
refused = true
|
|
29
|
+
return Promise.resolve(jsonResponse({ code: "PGRST303", message: "JWT expired" }, 401))
|
|
30
|
+
})
|
|
12
31
|
vi.stubGlobal("fetch", fetch)
|
|
13
|
-
const client = createClient({
|
|
32
|
+
const client = createClient({
|
|
33
|
+
url: "http://localhost:18473",
|
|
34
|
+
anonKey: "anon",
|
|
35
|
+
auth: { persistSession: false, autoRefreshToken: false },
|
|
36
|
+
initialSession: SESSION,
|
|
37
|
+
})
|
|
14
38
|
|
|
15
39
|
const { error } = await client.rpc("publish", undefined, { schema: "supatype", count: "exact" })
|
|
16
40
|
|
|
17
41
|
expect(error).toBeNull()
|
|
18
|
-
|
|
19
|
-
|
|
42
|
+
const sends = fetchCalls(fetch).filter(({ url }) => url.includes("/rpc/publish"))
|
|
43
|
+
expect(sends).toHaveLength(2)
|
|
44
|
+
for (const { init } of sends) {
|
|
20
45
|
expect(header(init, "Content-Profile")).toBe("supatype")
|
|
21
46
|
expect(header(init, "Prefer")).toBe("count=exact")
|
|
22
47
|
}
|