@supatype/client 0.3.5 → 0.7.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 +58 -31
- package/.turbo/turbo-typecheck.log +2 -2
- package/LICENSE +1 -1
- package/dist/auth-redirect.d.ts +48 -0
- package/dist/auth-redirect.d.ts.map +1 -0
- package/dist/auth-redirect.js +70 -0
- package/dist/auth-redirect.js.map +1 -0
- package/dist/auth.d.ts +78 -4
- package/dist/auth.d.ts.map +1 -1
- package/dist/auth.js +373 -274
- package/dist/auth.js.map +1 -1
- package/dist/bindings.d.ts +16 -0
- package/dist/bindings.d.ts.map +1 -0
- package/dist/bindings.js +13 -0
- package/dist/bindings.js.map +1 -0
- package/dist/caller-types.d.ts +18 -0
- package/dist/caller-types.d.ts.map +1 -0
- package/dist/caller-types.js +22 -0
- package/dist/caller-types.js.map +1 -0
- package/dist/draft-create.d.ts +12 -0
- package/dist/draft-create.d.ts.map +1 -0
- package/dist/draft-create.js +47 -0
- package/dist/draft-create.js.map +1 -0
- package/dist/draft-models-registry.d.ts +27 -0
- package/dist/draft-models-registry.d.ts.map +1 -0
- package/dist/draft-models-registry.js +61 -0
- package/dist/draft-models-registry.js.map +1 -0
- package/dist/error-codes-doc.d.ts +1 -1
- package/dist/error-codes-doc.d.ts.map +1 -1
- package/dist/error-codes-doc.js +42 -34
- package/dist/error-codes-doc.js.map +1 -1
- package/dist/errors.d.ts +102 -60
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +69 -28
- package/dist/errors.js.map +1 -1
- package/dist/exact-response.d.ts.map +1 -1
- package/dist/exact-response.js +2 -1
- package/dist/exact-response.js.map +1 -1
- package/dist/exact-values.d.ts +2 -0
- package/dist/exact-values.d.ts.map +1 -1
- package/dist/exact-values.js +12 -10
- package/dist/exact-values.js.map +1 -1
- package/dist/fetch-with-retry.d.ts +21 -6
- package/dist/fetch-with-retry.d.ts.map +1 -1
- package/dist/fetch-with-retry.js +67 -53
- package/dist/fetch-with-retry.js.map +1 -1
- package/dist/field-kinds-registry.d.ts +11 -3
- package/dist/field-kinds-registry.d.ts.map +1 -1
- package/dist/field-kinds-registry.js +10 -6
- package/dist/field-kinds-registry.js.map +1 -1
- package/dist/filters.d.ts +51 -0
- package/dist/filters.d.ts.map +1 -0
- package/dist/filters.js +117 -0
- package/dist/filters.js.map +1 -0
- package/dist/generated-client.d.ts +7 -0
- package/dist/generated-client.d.ts.map +1 -0
- package/dist/generated-client.js +7 -0
- package/dist/generated-client.js.map +1 -0
- package/dist/graphql-document.d.ts +39 -0
- package/dist/graphql-document.d.ts.map +1 -0
- package/dist/graphql-document.js +228 -0
- package/dist/graphql-document.js.map +1 -0
- package/dist/graphql-json.d.ts +56 -0
- package/dist/graphql-json.d.ts.map +1 -0
- package/dist/graphql-json.js +220 -0
- package/dist/graphql-json.js.map +1 -0
- package/dist/graphql-transport.d.ts +28 -0
- package/dist/graphql-transport.d.ts.map +1 -0
- package/dist/graphql-transport.js +77 -0
- package/dist/graphql-transport.js.map +1 -0
- package/dist/index.d.ts +103 -40
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +153 -157
- package/dist/index.js.map +1 -1
- package/dist/json.d.ts +61 -0
- package/dist/json.d.ts.map +1 -0
- package/dist/json.js +83 -0
- package/dist/json.js.map +1 -0
- package/dist/jwt.d.ts +16 -0
- package/dist/jwt.d.ts.map +1 -0
- package/dist/jwt.js +37 -0
- package/dist/jwt.js.map +1 -0
- package/dist/live-preview.d.ts +23 -0
- package/dist/live-preview.d.ts.map +1 -0
- package/dist/live-preview.js +28 -0
- package/dist/live-preview.js.map +1 -0
- package/dist/mutation-request.d.ts +17 -0
- package/dist/mutation-request.d.ts.map +1 -0
- package/dist/mutation-request.js +41 -0
- package/dist/mutation-request.js.map +1 -0
- package/dist/preview.d.ts.map +1 -1
- package/dist/preview.js +8 -6
- package/dist/preview.js.map +1 -1
- package/dist/query-cache.d.ts.map +1 -1
- package/dist/query-cache.js +19 -13
- package/dist/query-cache.js.map +1 -1
- package/dist/query.d.ts +108 -29
- package/dist/query.d.ts.map +1 -1
- package/dist/query.js +294 -224
- package/dist/query.js.map +1 -1
- package/dist/realtime.d.ts +20 -2
- package/dist/realtime.d.ts.map +1 -1
- package/dist/realtime.js +105 -12
- package/dist/realtime.js.map +1 -1
- package/dist/select-types.d.ts +99 -0
- package/dist/select-types.d.ts.map +1 -0
- package/dist/select-types.js +2 -0
- package/dist/select-types.js.map +1 -0
- package/dist/storage.d.ts +81 -11
- package/dist/storage.d.ts.map +1 -1
- package/dist/storage.js +129 -37
- package/dist/storage.js.map +1 -1
- package/dist/table-subscription.d.ts +69 -0
- package/dist/table-subscription.d.ts.map +1 -0
- package/dist/table-subscription.js +93 -0
- package/dist/table-subscription.js.map +1 -0
- package/dist/types.d.ts +84 -5
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +6 -1
- package/dist/types.js.map +1 -1
- package/package.json +6 -2
- package/src/auth-redirect.ts +90 -0
- package/src/auth.ts +421 -280
- package/src/bindings.ts +22 -0
- package/src/caller-types.ts +27 -0
- package/src/draft-create.ts +51 -0
- package/src/draft-models-registry.ts +81 -0
- package/src/error-codes-doc.ts +44 -35
- package/src/errors.ts +72 -28
- package/src/exact-response.ts +2 -1
- package/src/exact-values.ts +16 -9
- package/src/fetch-with-retry.ts +80 -70
- package/src/field-kinds-registry.ts +22 -9
- package/src/filters.ts +133 -0
- package/src/generated-client.ts +6 -0
- package/src/graphql-document.ts +234 -0
- package/src/graphql-json.ts +243 -0
- package/src/graphql-transport.ts +97 -0
- package/src/index.ts +272 -201
- package/src/json.ts +117 -0
- package/src/jwt.ts +37 -0
- package/src/live-preview.ts +37 -0
- package/src/mutation-request.ts +66 -0
- package/src/preview.ts +9 -11
- package/src/query-cache.ts +19 -16
- package/src/query.ts +389 -270
- package/src/realtime.ts +116 -13
- package/src/select-types.ts +184 -0
- package/src/storage.ts +214 -43
- package/src/table-subscription.ts +160 -0
- package/src/types.ts +90 -5
- package/tests/auth-error-codes.test.ts +53 -0
- package/tests/auth-errors.test.ts +84 -0
- package/tests/auth-events.test.ts +136 -0
- package/tests/auth-url-session.test.ts +204 -0
- package/tests/auth.test.ts +122 -26
- package/tests/count.test.ts +60 -0
- package/tests/data-plane-auth.test.ts +21 -46
- package/tests/draft-insert.integration.test.ts +118 -0
- package/tests/draft-insert.test.ts +225 -0
- package/tests/draft-profile.test.ts +55 -84
- package/tests/draft-update.integration.test.ts +122 -0
- package/tests/draft-update.test.ts +174 -0
- package/tests/dynamic-headers.test.ts +45 -0
- package/tests/entry-points.test.ts +42 -0
- package/tests/exact-response.test.ts +4 -4
- package/tests/exact-values.test.ts +14 -25
- package/tests/field-kinds-registry.test.ts +3 -3
- package/tests/filters.test.ts +146 -0
- package/tests/graphql-json.test.ts +199 -0
- package/tests/helpers/mock-websocket.ts +44 -11
- package/tests/helpers/oauth-binding.ts +92 -0
- package/tests/helpers/signup-binding.ts +73 -0
- package/tests/helpers/socket-swap.ts +139 -0
- package/tests/mfa-totp-integration.test.ts +13 -20
- package/tests/postgrest-error-codes.test.ts +85 -0
- package/tests/query-cache.test.ts +116 -117
- package/tests/query.test.ts +29 -31
- package/tests/rate-limit-integration.test.ts +4 -12
- package/tests/realtime-exact-values.test.ts +2 -4
- package/tests/realtime-presence.test.ts +75 -0
- package/tests/realtime-session-auth.test.ts +2 -4
- package/tests/realtime-swap-status.test.ts +62 -0
- package/tests/retry-integration.test.ts +3 -8
- package/tests/retry-policy.test.ts +166 -0
- package/tests/rpc-resend.test.ts +24 -0
- package/tests/server-bodies.test.ts +139 -0
- package/tests/serverless.test.ts +2 -2
- package/tests/signed-url-absolute.test.ts +2 -5
- package/tests/storage-object-shape.test.ts +101 -0
- package/tests/storage-quota-integration.test.ts +3 -2
- package/tests/storage-reference-url.test.ts +51 -0
- package/tests/storage-upload-browser.test.ts +71 -0
- package/tests/storage-upload-limit-integration.test.ts +12 -22
- package/tests/subscribe-frame.test.ts +5 -11
- package/tests/support/fetch-mock.ts +64 -0
- package/tests/support/storage-object.ts +37 -0
- package/tests/table-subscribe.test.ts +13 -13
- package/tests/table-subscription.test.ts +105 -0
- package/tests/table-transport.test.ts +94 -0
- package/tests/tsconfig.json +1 -1
- package/tests/types.test.ts +153 -1
- package/tsconfig.json +1 -1
- package/tsconfig.tsbuildinfo +1 -1
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Turning pg_graphql's `JSON` scalar strings back into the values they encode.
|
|
3
|
+
*
|
|
4
|
+
* pg_graphql types every json and jsonb column (rich text, blocks, json fields, and any function or
|
|
5
|
+
* view returning one) as its `JSON` scalar, "a Javascript Object Notation value serialized as a
|
|
6
|
+
* string". The scalar is the only reliable marker: the generated field kinds know a model's columns
|
|
7
|
+
* but not the names pg_graphql gives its connection, edge and relation types, so the schema itself
|
|
8
|
+
* is asked, once per role, and each answer is walked against the query that produced it.
|
|
9
|
+
*
|
|
10
|
+
* A key is decoded only when every field selected under it is a `JSON` scalar. A key the schema
|
|
11
|
+
* does not know, a document with more than one operation, or a string that does not parse is left
|
|
12
|
+
* as the server sent it.
|
|
13
|
+
*/
|
|
14
|
+
import { parseGraphqlDocument, type GraphqlDocument, type GraphqlOperationKind, type GraphqlSelection } from "./graphql-document.js"
|
|
15
|
+
import { isArrayOf, isJsonObject, isShape, isString } from "./json.js"
|
|
16
|
+
|
|
17
|
+
/** What the client needs from a GraphQL schema: each type's fields, by the type they return. */
|
|
18
|
+
export type GraphqlSchema = {
|
|
19
|
+
readonly roots: Readonly<Partial<Record<GraphqlOperationKind, string>>>
|
|
20
|
+
/** Type name to field name to the named type the field returns, lists and non-null removed. */
|
|
21
|
+
readonly types: ReadonlyMap<string, ReadonlyMap<string, string>>
|
|
22
|
+
readonly jsonScalars: ReadonlySet<string>
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** The answer with its `JSON` fields decoded, and whether the schema was missing a field it used. */
|
|
26
|
+
export type GraphqlJsonDecoding = { readonly data: unknown; readonly schemaIsStale: boolean }
|
|
27
|
+
|
|
28
|
+
/** pg_graphql's name for the scalar it gives json and jsonb. */
|
|
29
|
+
const JSON_SCALAR = "JSON"
|
|
30
|
+
|
|
31
|
+
const TYPE_REF = "kind name ofType { kind name ofType { kind name ofType { kind name ofType { kind name ofType { kind name } } } } }"
|
|
32
|
+
|
|
33
|
+
/** The introspection query whose `data` {@link readGraphqlSchema} reads. */
|
|
34
|
+
export const GRAPHQL_SCHEMA_QUERY =
|
|
35
|
+
"query SupatypeSchemaFields { __schema { queryType { name } mutationType { name } subscriptionType { name } " +
|
|
36
|
+
`types { name kind fields(includeDeprecated: true) { name type { ${TYPE_REF} } } } } }`
|
|
37
|
+
|
|
38
|
+
type TypeRef = { kind: string; name: string | null; ofType?: TypeRef | null }
|
|
39
|
+
|
|
40
|
+
function isTypeRef(value: unknown): value is TypeRef {
|
|
41
|
+
if (!isJsonObject(value) || !isString(value["kind"])) return false
|
|
42
|
+
const name = value["name"]
|
|
43
|
+
const ofType = value["ofType"]
|
|
44
|
+
return (name === null || isString(name)) && (ofType === undefined || ofType === null || isTypeRef(ofType))
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const isField = isShape({ name: isString, type: isTypeRef })
|
|
48
|
+
const isType = isShape({ name: isString, kind: isString })
|
|
49
|
+
|
|
50
|
+
function namedType(ref: TypeRef): string | null {
|
|
51
|
+
return ref.ofType === undefined || ref.ofType === null ? ref.name : namedType(ref.ofType)
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function rootName(value: unknown): string | null {
|
|
55
|
+
return isJsonObject(value) && isString(value["name"]) ? value["name"] : null
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** The fields of one introspected type, or none for a scalar, enum or input. */
|
|
59
|
+
function fieldsOf(type: Record<string, unknown>): Map<string, string> {
|
|
60
|
+
const fields = new Map<string, string>()
|
|
61
|
+
const declared = type["fields"]
|
|
62
|
+
if (!Array.isArray(declared)) return fields
|
|
63
|
+
for (const field of declared) {
|
|
64
|
+
if (!isField(field)) continue
|
|
65
|
+
const returns = namedType(field.type)
|
|
66
|
+
if (returns !== null) fields.set(field.name, returns)
|
|
67
|
+
}
|
|
68
|
+
return fields
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function rootsOf(schema: Record<string, unknown>): Partial<Record<GraphqlOperationKind, string>> {
|
|
72
|
+
const roots: Partial<Record<GraphqlOperationKind, string>> = {}
|
|
73
|
+
const entries = [["query", "queryType"], ["mutation", "mutationType"], ["subscription", "subscriptionType"]] as const
|
|
74
|
+
for (const [kind, key] of entries) {
|
|
75
|
+
const name = rootName(schema[key])
|
|
76
|
+
if (name !== null) roots[kind] = name
|
|
77
|
+
}
|
|
78
|
+
return roots
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** The schema in the `data` of a {@link GRAPHQL_SCHEMA_QUERY} answer, or null when it is not one. */
|
|
82
|
+
export function readGraphqlSchema(data: unknown): GraphqlSchema | null {
|
|
83
|
+
const schema = isJsonObject(data) ? data["__schema"] : undefined
|
|
84
|
+
if (!isJsonObject(schema)) return null
|
|
85
|
+
const types = schema["types"]
|
|
86
|
+
if (!isArrayOf(isType)(types)) return null
|
|
87
|
+
const fields = new Map<string, ReadonlyMap<string, string>>()
|
|
88
|
+
const jsonScalars = new Set<string>()
|
|
89
|
+
for (const type of types) {
|
|
90
|
+
if (type.kind === "SCALAR" && type.name === JSON_SCALAR) jsonScalars.add(type.name)
|
|
91
|
+
fields.set(type.name, fieldsOf(type))
|
|
92
|
+
}
|
|
93
|
+
return { roots: rootsOf(schema), types: fields, jsonScalars }
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** A selection set, and the type its fields are looked up on. */
|
|
97
|
+
type Scope = { readonly selections: readonly GraphqlSelection[]; readonly type: string }
|
|
98
|
+
|
|
99
|
+
/** Everything selected under one response key. Decoded only when it is unambiguous. */
|
|
100
|
+
type Entry = { json: boolean; other: boolean; readonly children: Scope[]; childEntries?: Map<string, Entry> }
|
|
101
|
+
|
|
102
|
+
type Walk = { readonly schema: GraphqlSchema; readonly document: GraphqlDocument; stale: boolean }
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* `data` with every `JSON` scalar field of `query` decoded, following aliases, fragments, nested
|
|
106
|
+
* selections and lists. For a GraphQL client other than this one, given the schema it introspected.
|
|
107
|
+
*/
|
|
108
|
+
export function decodeGraphqlJsonFields(query: string, data: unknown, schema: GraphqlSchema): GraphqlJsonDecoding {
|
|
109
|
+
const document = parseGraphqlDocument(query)
|
|
110
|
+
const operation = document?.operations.length === 1 ? document.operations[0] : undefined
|
|
111
|
+
const root = operation === undefined ? undefined : schema.roots[operation.kind]
|
|
112
|
+
if (document === null || operation === undefined || root === undefined) return { data, schemaIsStale: false }
|
|
113
|
+
const walk: Walk = { schema, document, stale: false }
|
|
114
|
+
const decoded = decodeWith(data, entriesFor([{ selections: operation.selections, type: root }], walk), walk)
|
|
115
|
+
return { data: decoded, schemaIsStale: walk.stale }
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function entriesFor(scopes: readonly Scope[], walk: Walk): Map<string, Entry> {
|
|
119
|
+
const entries = new Map<string, Entry>()
|
|
120
|
+
for (const scope of scopes) collect(entries, scope, walk, new Set())
|
|
121
|
+
return entries
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function collect(entries: Map<string, Entry>, scope: Scope, walk: Walk, fragmentsSeen: ReadonlySet<string>): void {
|
|
125
|
+
for (const selection of scope.selections) {
|
|
126
|
+
if (selection.kind === "field") {
|
|
127
|
+
addField(entries, selection, scope.type, walk)
|
|
128
|
+
} else if (selection.kind === "inline") {
|
|
129
|
+
collect(entries, { selections: selection.selections, type: selection.typeCondition ?? scope.type }, walk, fragmentsSeen)
|
|
130
|
+
} else {
|
|
131
|
+
const fragment = walk.document.fragments.get(selection.fragment)
|
|
132
|
+
if (fragment === undefined || fragmentsSeen.has(selection.fragment)) continue
|
|
133
|
+
const seen = new Set([...fragmentsSeen, selection.fragment])
|
|
134
|
+
collect(entries, { selections: fragment.selections, type: fragment.typeCondition }, walk, seen)
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
type FieldSelection = Extract<GraphqlSelection, { kind: "field" }>
|
|
140
|
+
|
|
141
|
+
function addField(entries: Map<string, Entry>, field: FieldSelection, type: string, walk: Walk): void {
|
|
142
|
+
const entry = entries.get(field.key) ?? { json: false, other: false, children: [] }
|
|
143
|
+
entries.set(field.key, entry)
|
|
144
|
+
if (field.name.startsWith("__")) {
|
|
145
|
+
entry.other = true
|
|
146
|
+
return
|
|
147
|
+
}
|
|
148
|
+
const returns = walk.schema.types.get(type)?.get(field.name)
|
|
149
|
+
if (returns === undefined) {
|
|
150
|
+
entry.other = true
|
|
151
|
+
walk.stale = true
|
|
152
|
+
} else if (walk.schema.jsonScalars.has(returns)) {
|
|
153
|
+
entry.json = true
|
|
154
|
+
} else if (field.selections.length > 0) {
|
|
155
|
+
entry.children.push({ selections: field.selections, type: returns })
|
|
156
|
+
} else {
|
|
157
|
+
entry.other = true
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** `value` with `entries` applied to it, or to each item when it is a list. */
|
|
162
|
+
function decodeWith(value: unknown, entries: ReadonlyMap<string, Entry>, walk: Walk): unknown {
|
|
163
|
+
if (Array.isArray(value)) return value.map((item) => decodeWith(item, entries, walk))
|
|
164
|
+
if (!isJsonObject(value)) return value
|
|
165
|
+
const decoded: Record<string, unknown> = { ...value }
|
|
166
|
+
for (const [key, entry] of entries) {
|
|
167
|
+
if (key in value) decoded[key] = decodeEntry(value[key], entry, walk)
|
|
168
|
+
}
|
|
169
|
+
return decoded
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function decodeEntry(value: unknown, entry: Entry, walk: Walk): unknown {
|
|
173
|
+
if (entry.other) return value
|
|
174
|
+
if (entry.json && entry.children.length === 0) return decodeJson(value)
|
|
175
|
+
if (entry.json || entry.children.length === 0) return value
|
|
176
|
+
// Collected once per entry, not once per object: `edges { node }` visits `node` for every edge.
|
|
177
|
+
entry.childEntries ??= entriesFor(entry.children, walk)
|
|
178
|
+
return decodeWith(value, entry.childEntries, walk)
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** The value a `JSON` scalar string encodes, through lists; anything else as it is. */
|
|
182
|
+
function decodeJson(value: unknown): unknown {
|
|
183
|
+
if (Array.isArray(value)) return value.map(decodeJson)
|
|
184
|
+
if (typeof value !== "string") return value
|
|
185
|
+
try {
|
|
186
|
+
const parsed: unknown = JSON.parse(value)
|
|
187
|
+
return parsed
|
|
188
|
+
} catch {
|
|
189
|
+
return value
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** True when `value` holds a string anywhere: an answer without one has nothing to decode. */
|
|
194
|
+
function containsString(value: unknown): boolean {
|
|
195
|
+
if (typeof value === "string") return true
|
|
196
|
+
if (Array.isArray(value)) return value.some(containsString)
|
|
197
|
+
return isJsonObject(value) && Object.values(value).some(containsString)
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* Schemas by whoever reads them. pg_graphql shows each Postgres role only what it may use, so an
|
|
202
|
+
* anonymous caller's schema can lack types a signed-in one has. A failed read is not kept, and
|
|
203
|
+
* neither is a schema an answer showed to be stale: the next call reads it again.
|
|
204
|
+
*/
|
|
205
|
+
export class GraphqlSchemaCache {
|
|
206
|
+
private readonly schemas = new Map<string, Promise<GraphqlSchema | null>>()
|
|
207
|
+
|
|
208
|
+
get(key: string, load: () => Promise<GraphqlSchema | null>): Promise<GraphqlSchema | null> {
|
|
209
|
+
const cached = this.schemas.get(key)
|
|
210
|
+
if (cached !== undefined) return cached
|
|
211
|
+
const loading = load().catch(() => null).then((schema) => {
|
|
212
|
+
if (schema === null) this.schemas.delete(key)
|
|
213
|
+
return schema
|
|
214
|
+
})
|
|
215
|
+
this.schemas.set(key, loading)
|
|
216
|
+
return loading
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
forget(key: string): void {
|
|
220
|
+
this.schemas.delete(key)
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** Where a schema comes from: whose it is, and how to read it when the cache has none. */
|
|
225
|
+
export type GraphqlSchemaSource = {
|
|
226
|
+
readonly key: () => Promise<string>
|
|
227
|
+
readonly load: () => Promise<GraphqlSchema | null>
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/** `data` decoded against the schema `source` names, read once when an answer first needs it. */
|
|
231
|
+
export async function decodeGraphqlAnswer(
|
|
232
|
+
answer: { readonly query: string; readonly data: unknown },
|
|
233
|
+
schemas: GraphqlSchemaCache,
|
|
234
|
+
source: GraphqlSchemaSource,
|
|
235
|
+
): Promise<unknown> {
|
|
236
|
+
if (!containsString(answer.data)) return answer.data
|
|
237
|
+
const key = await source.key()
|
|
238
|
+
const schema = await schemas.get(key, source.load)
|
|
239
|
+
if (schema === null) return answer.data
|
|
240
|
+
const { data, schemaIsStale } = decodeGraphqlJsonFields(answer.query, answer.data, schema)
|
|
241
|
+
if (schemaIsStale) schemas.forget(key)
|
|
242
|
+
return data
|
|
243
|
+
}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `supatype.graphql()`: the request, what the answer means, and the decoding of its `JSON` fields.
|
|
3
|
+
*
|
|
4
|
+
* The schema the decoding needs is read through the same transport as the query, carrying the same
|
|
5
|
+
* credential, because pg_graphql shows each role only what it may use. It is cached per role, so a
|
|
6
|
+
* refreshed token for the same role reuses it.
|
|
7
|
+
*/
|
|
8
|
+
import { transportFailure } from "./errors.js"
|
|
9
|
+
import type { RequestTransport } from "./fetch-with-retry.js"
|
|
10
|
+
import { GRAPHQL_SCHEMA_QUERY, GraphqlSchemaCache, decodeGraphqlAnswer, readGraphqlSchema, type GraphqlSchema } from "./graphql-json.js"
|
|
11
|
+
import { isJsonObject, refusalText } from "./json.js"
|
|
12
|
+
import { bearerRole } from "./jwt.js"
|
|
13
|
+
import { fetchWithOptional401Retry, type HeadersProvider } from "./query.js"
|
|
14
|
+
import type { SupatypeError } from "./types.js"
|
|
15
|
+
|
|
16
|
+
/** Where GraphQL requests go and what they carry. Studio builds one per send-as choice. */
|
|
17
|
+
export type GraphqlTransport = {
|
|
18
|
+
/** The `/graphql/v1` URL. */
|
|
19
|
+
readonly endpoint: string
|
|
20
|
+
readonly send: RequestTransport
|
|
21
|
+
readonly headers: HeadersProvider
|
|
22
|
+
readonly onUnauthorized?: (() => Promise<void>) | undefined
|
|
23
|
+
/** Whose schema a request reads, from its headers. Defaults to the bearer token's role. */
|
|
24
|
+
readonly schemaKey?: ((headers: Record<string, string>) => string) | undefined
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
type GraphqlAnswer = { data: unknown; error: SupatypeError | null }
|
|
28
|
+
type GraphqlRunner = (
|
|
29
|
+
query: string,
|
|
30
|
+
variables?: Record<string, unknown> | undefined,
|
|
31
|
+
options?: { idempotent?: boolean | undefined } | undefined,
|
|
32
|
+
) => Promise<GraphqlAnswer>
|
|
33
|
+
type Reply = { readonly json: unknown; readonly res: Response } | { readonly failure: SupatypeError }
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Runs GraphQL requests over `transport`, decoding `JSON` scalar fields against a schema cached in
|
|
37
|
+
* `schemas`. Pass a long-lived cache when the runner itself is short-lived.
|
|
38
|
+
*/
|
|
39
|
+
export function createGraphqlRunner(transport: GraphqlTransport, schemas = new GraphqlSchemaCache()): GraphqlRunner {
|
|
40
|
+
const keyOf = transport.schemaKey ?? schemaKey
|
|
41
|
+
const source = {
|
|
42
|
+
key: async (): Promise<string> => keyOf(await transport.headers()),
|
|
43
|
+
load: (): Promise<GraphqlSchema | null> => loadSchema(transport),
|
|
44
|
+
}
|
|
45
|
+
return async (query, variables, options) => {
|
|
46
|
+
const body = { query, ...(variables !== undefined && { variables }) }
|
|
47
|
+
const reply = await post(transport, body, options?.idempotent === true)
|
|
48
|
+
if ("failure" in reply) return { data: null, error: reply.failure }
|
|
49
|
+
const result = graphqlResult(reply.json, reply.res)
|
|
50
|
+
return { data: await decodeGraphqlAnswer({ query, data: result.data }, schemas, source), error: result.error }
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
async function post(transport: GraphqlTransport, body: Record<string, unknown>, idempotent: boolean): Promise<Reply> {
|
|
55
|
+
const init = { method: "POST", body: JSON.stringify(body), ...(idempotent && { idempotent: true }) }
|
|
56
|
+
let res: Response
|
|
57
|
+
try {
|
|
58
|
+
res = await fetchWithOptional401Retry(transport.send, transport.endpoint, init, transport.headers, transport.onUnauthorized)
|
|
59
|
+
} catch (e) {
|
|
60
|
+
return { failure: transportFailure(e) }
|
|
61
|
+
}
|
|
62
|
+
try {
|
|
63
|
+
const json: unknown = await res.json()
|
|
64
|
+
return { json, res }
|
|
65
|
+
} catch {
|
|
66
|
+
return { failure: { message: `GraphQL endpoint returned a non-JSON response (HTTP ${res.status} ${res.statusText})` } }
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
async function loadSchema(transport: GraphqlTransport): Promise<GraphqlSchema | null> {
|
|
71
|
+
const reply = await post(transport, { query: GRAPHQL_SCHEMA_QUERY }, true)
|
|
72
|
+
if ("failure" in reply || !reply.res.ok || !isJsonObject(reply.json)) return null
|
|
73
|
+
return readGraphqlSchema(reply.json["data"])
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Who a schema is read as: the token's role when it names one, otherwise the credential itself. */
|
|
77
|
+
function schemaKey(headers: Record<string, string>): string {
|
|
78
|
+
const role = bearerRole(headers)
|
|
79
|
+
return role !== null ? `role:${role}` : `credential:${headers["Authorization"] ?? headers["apikey"] ?? ""}`
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** What a GraphQL endpoint's JSON answer means: its data, and the first error it reports. */
|
|
83
|
+
function graphqlResult(json: unknown, res: Response): GraphqlAnswer {
|
|
84
|
+
if (!isJsonObject(json)) {
|
|
85
|
+
return { data: null, error: { message: `GraphQL endpoint returned JSON that is not an object (HTTP ${res.status})`, status: res.status } }
|
|
86
|
+
}
|
|
87
|
+
const data = json["data"] ?? null
|
|
88
|
+
if (!res.ok) {
|
|
89
|
+
const message = refusalText(json) ?? `GraphQL request failed (HTTP ${res.status})`
|
|
90
|
+
return { data, error: { message, status: res.status } }
|
|
91
|
+
}
|
|
92
|
+
const errors = json["errors"]
|
|
93
|
+
if (errors === undefined) return { data, error: null }
|
|
94
|
+
const first = Array.isArray(errors) ? errors[0] : undefined
|
|
95
|
+
const message = isJsonObject(first) && typeof first["message"] === "string" ? first["message"] : "GraphQL error"
|
|
96
|
+
return { data, error: { message } }
|
|
97
|
+
}
|