ramdb2-client 0.0.0-stage → 2.0.0-alpha.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/src/object.js ADDED
@@ -0,0 +1,207 @@
1
+ import { classOf } from './config.js'
2
+ import { Draft } from './draft.js'
3
+ import { RelationNotLoadedError } from './errors.js'
4
+ import { forgetInstance } from './identity.js'
5
+ import { hydrate, includeTree, selection } from './hydrate.js'
6
+ import { requestNamed } from './request.js'
7
+
8
+ /**
9
+ * @typedef {object} Relation a relation declared by a generated class
10
+ * @property {string} type the GraphQL type of the related objects
11
+ * @property {string} key the foreign key: on this type for an object relation, on the other type for a list
12
+ * @property {boolean} [list] a list relation (the other type holds the foreign key)
13
+ *
14
+ * @typedef {object} ListResult
15
+ * @property {any[]} items the instances, [] with a groupBy
16
+ * @property {number} total number of items, or of groups, before pagination
17
+ * @property {object | null} aggregates the aggregates without groupBy
18
+ * @property {object[] | null} groups the groups with a groupBy: [{ key, ...aggregates }]
19
+ *
20
+ * @typedef {object} CallOptions
21
+ * @property {string} [name] the operation name, instead of the default one (D9)
22
+ * @property {AbortSignal} [signal] to cancel the request, e.g. a search while typing
23
+ */
24
+
25
+ /**
26
+ * Base class of the client objects. The classes are generated by ramdb2-cli (XxxBase), then extended by hand (Xxx).
27
+ *
28
+ * An instance holds the values of the server: it is read-only. A change goes through a Draft (edit(), newDraft()),
29
+ * which sends only the changed fields, with the values read at the start (D14).
30
+ * Internal values use the _ prefix, never # private fields: they would break the reactive proxy of Vue (D8).
31
+ * - `_f`: stored fields and foreign keys, `_c`: computed and @transient fields, `_r`: relations loaded by `include` (D5).
32
+ */
33
+ export class ClientObject {
34
+ /** @type {string} the GraphQL type */
35
+ static typeName
36
+ /** @type {{list: string, byId: string, dataCheck: string, default: string, create: string, update: string, delete: string, argument: string}} the operations of ramdb2-server */
37
+ static operations
38
+ /** @type {string[]} stored fields and foreign keys, id first */
39
+ static fields = ['id']
40
+ /** @type {string[]} computed fields, calculated by the server */
41
+ static computed = []
42
+ /** @type {string[]} @transient fields of a scalar type: resolved by the project on the server, always loaded */
43
+ static transient = []
44
+ /** @type {string[]} fields with a FULLTEXT index on the server: the search uses $text on them (D20) */
45
+ static fullText = []
46
+ /** @type {Record<string, Relation>} */
47
+ static relations = {}
48
+ /** @type {Record<string, string>} labels of the fields, written in the extended class (D20) */
49
+ static labels = {}
50
+ /** @type {Record<string, Record<string, string>>} labels of the values of an enum: { status: { OPEN: 'Ouvert' } } (D20) */
51
+ static valueLabels = {}
52
+ /** @type {string | undefined} the field that shows an object, e.g. in a list of choices (D20) */
53
+ static display
54
+ /** @type {Record<string, string>} the input of a field, when the default one does not fit: { description: 'textarea' } */
55
+ static inputs = {}
56
+ /** @type {Record<string, any>} values of a new object: the defaults of the server (spec section 3 of ramdb2) */
57
+ static defaults = { id: 0 }
58
+ /** @type {Record<string, Function[]>} rules generated from the schema */
59
+ static generatedRules = {}
60
+ /** @type {Record<string, Function[]>} rules written in the extended class */
61
+ static rules = {}
62
+
63
+ constructor() {
64
+ this._f = { ...this.constructor.defaults }
65
+ this._c = {}
66
+ this._r = {}
67
+ this._deleted = false
68
+ }
69
+
70
+ /** @returns {number} */
71
+ get id() { return this._f.id }
72
+
73
+ /** True once deleted: the instance stays readable, the identity map forgets it. */
74
+ get deleted() { return this._deleted }
75
+
76
+ /**
77
+ * The stored values (fields and foreign keys), as a new object.
78
+ * @returns {Record<string, any>}
79
+ */
80
+ values() {
81
+ return { ...this._f }
82
+ }
83
+
84
+ /**
85
+ * A relation loaded by `include`, or an error: a getter never sends a request on its own (D5).
86
+ * @param {string} name
87
+ */
88
+ _relation(name) {
89
+ if (!(name in this._r)) {
90
+ throw new RelationNotLoadedError(`${this.constructor.typeName}.${name} was not loaded: add '${name}' to include`)
91
+ }
92
+ return this._r[name]
93
+ }
94
+
95
+ /**
96
+ * Updates the instance with an object of a response. The relations not loaded by this response are kept,
97
+ * except an object relation whose foreign key changed.
98
+ * @param {object} data
99
+ * @param {object} tree the relations loaded with it
100
+ */
101
+ _load(data, tree) {
102
+ const cls = /** @type {typeof ClientObject} */ (this.constructor)
103
+ for (const [name, relation] of Object.entries(cls.relations)) {
104
+ if (!relation.list && !(name in tree) && name in this._r && data[relation.key] !== this._f[relation.key]) delete this._r[name]
105
+ }
106
+ for (const field of cls.fields) if (field in data) this._f[field] = data[field]
107
+ for (const field of [...cls.computed, ...cls.transient]) if (field in data) this._c[field] = data[field]
108
+ for (const [name, subtree] of Object.entries(tree)) {
109
+ const relation = cls.relations[name]
110
+ const target = classOf(relation.type)
111
+ const value = data[name]
112
+ this._r[name] = relation.list ? (value ?? []).map(item => hydrate(target, item, subtree))
113
+ : value ? hydrate(target, value, subtree) : null
114
+ }
115
+ }
116
+
117
+ /**
118
+ * A query on the server (spec section 10 of ramdb2): MongoDB syntax, sent in variables.
119
+ * @template T
120
+ * @this {new () => T}
121
+ * @param {{query?: object, include?: string[]} & CallOptions} [options]
122
+ * @returns {Promise<ListResult & {items: T[]}>}
123
+ */
124
+ static async list({ query, include, name, signal } = {}) {
125
+ const cls = /** @type {typeof ClientObject} */ (this)
126
+ const tree = includeTree(cls, include)
127
+ const ops = cls.operations
128
+ const data = await requestNamed(`${cls.typeName}List`, operation =>
129
+ `query ${operation}($query: ${cls.typeName}Query) { ${ops.list}(query: $query) { items { ${selection(cls, tree)} } total aggregates groups } }`,
130
+ { query }, { name, signal })
131
+ const result = data[ops.list]
132
+ return {
133
+ items: (result.items ?? []).map(item => hydrate(cls, item, tree)),
134
+ total: result.total,
135
+ aggregates: result.aggregates ?? null,
136
+ groups: result.groups ?? null,
137
+ }
138
+ }
139
+
140
+ /**
141
+ * One object by its id. NotFoundError when it does not exist.
142
+ * @template T
143
+ * @this {new () => T}
144
+ * @param {number} id
145
+ * @param {{include?: string[]} & CallOptions} [options]
146
+ * @returns {Promise<T>}
147
+ */
148
+ static async byId(id, { include, name, signal } = {}) {
149
+ const cls = /** @type {typeof ClientObject} */ (this)
150
+ const tree = includeTree(cls, include)
151
+ const data = await requestNamed(`${cls.typeName}ById`, operation =>
152
+ `query ${operation}($id: Int!) { ${cls.operations.byId}(id: $id) { ${selection(cls, tree)} } }`,
153
+ { id }, { name, signal })
154
+ return hydrate(cls, data[cls.operations.byId], tree)
155
+ }
156
+
157
+ /**
158
+ * A draft of a new object, with the default values of the schema and `values`.
159
+ * @template T
160
+ * @this {new () => T}
161
+ * @param {object} [values] e.g. the foreign key of the parent: { idProject: 3 }
162
+ * @returns {Draft<T>}
163
+ */
164
+ static newDraft(values = {}) {
165
+ return new Draft(this, null, values)
166
+ }
167
+
168
+ /**
169
+ * A draft to modify this object: a form edits the draft, the instance keeps the values of the server.
170
+ * @returns {Draft<this>}
171
+ */
172
+ edit() {
173
+ return new Draft(this.constructor, this)
174
+ }
175
+
176
+ /**
177
+ * Modifies some fields: a shortcut for edit().set(values).save(), e.g. an inline edit in a table.
178
+ * @param {object} values
179
+ * @param {CallOptions} [options]
180
+ * @returns {Promise<this>}
181
+ */
182
+ update(values, options) {
183
+ return this.edit().set(values).save(options)
184
+ }
185
+
186
+ /**
187
+ * Reloads this object, e.g. after a conflict.
188
+ * @param {{include?: string[]} & CallOptions} [options]
189
+ * @returns {Promise<this>}
190
+ */
191
+ reload(options) {
192
+ return /** @type {any} */ (this.constructor).byId(this.id, options)
193
+ }
194
+
195
+ /**
196
+ * Deletes this object (the @onDelete policies apply on the server). The identity map forgets it.
197
+ * @param {CallOptions} [options]
198
+ */
199
+ async delete({ name, signal } = {}) {
200
+ const cls = /** @type {typeof ClientObject} */ (this.constructor)
201
+ await requestNamed(`${cls.typeName}Delete`, operation =>
202
+ `mutation ${operation}($id: Int!) { ${cls.operations.delete}(id: $id) { id } }`,
203
+ { id: this.id }, { name, signal })
204
+ this._deleted = true
205
+ forgetInstance(cls.typeName, this.id)
206
+ }
207
+ }
package/src/request.js ADDED
@@ -0,0 +1,35 @@
1
+ import { afterError, authHeaders, beforeRequest } from './auth.js'
2
+ import { operationName } from './config.js'
3
+ import { send } from './transport.js'
4
+
5
+ /**
6
+ * Sends a GraphQL operation with the token of the session: the way to call the operations written by hand in a
7
+ * project (schema/project.graphql). The expiry of the token is checked before, and the errors that mean the
8
+ * session is over are translated after (D10).
9
+ * @param {string} document a GraphQL document with one named operation, e.g. `query PlanningLoad($id: Int!) { … }`
10
+ * @param {object} [variables]
11
+ * @param {{name?: string, signal?: AbortSignal, auth?: boolean}} [options] name: the operation name, read in the
12
+ * document when not given. auth: false to send without the token
13
+ * @returns {Promise<object>} the `data` of the response
14
+ */
15
+ export async function request(document, variables = {}, { name, signal, auth = true } = {}) {
16
+ const operation = name ?? /^\s*(?:query|mutation)\s+([_A-Za-z][_0-9A-Za-z]*)/.exec(document)?.[1]
17
+ if (auth) await beforeRequest()
18
+ try {
19
+ return await send(document, variables, { name: operation, signal, headers: auth ? authHeaders() : {} })
20
+ } catch (error) {
21
+ throw auth ? await afterError(error) : error
22
+ }
23
+ }
24
+
25
+ /**
26
+ * Sends an operation of a class, under its default name or the one of the caller (D9).
27
+ * @param {string} defaultName e.g. TaskList
28
+ * @param {(name: string) => string} build builds the document with the operation name
29
+ * @param {object} variables
30
+ * @param {{name?: string, signal?: AbortSignal}} options
31
+ */
32
+ export function requestNamed(defaultName, build, variables, { name, signal } = {}) {
33
+ const operation = operationName(defaultName, name)
34
+ return request(build(operation), variables, { name: operation, signal })
35
+ }
package/src/rules.js ADDED
@@ -0,0 +1,72 @@
1
+ // The local validation rules (D4): the same factories and the same messages as ramdb2 (spec section 7 of ramdb2),
2
+ // so that a form shows the message the server would give, without a round trip. The server stays the judge.
3
+ // A rule is a pure function (values, obj) => '' when valid, or a message.
4
+
5
+ /**
6
+ * A non-null field: refuses undefined, null and ''. A numeric 0 is valid.
7
+ * @param {string} field
8
+ */
9
+ export function required(field) {
10
+ return tag(values => {
11
+ const value = values[field]
12
+ return value === undefined || value === null || value === '' ? `${field} is required` : ''
13
+ }, { required: true })
14
+ }
15
+
16
+ /**
17
+ * A required foreign key: 0 means "no object" (spec section 3 of ramdb2) and is refused. Whether the object exists
18
+ * is checked by the server only.
19
+ * @param {string} field e.g. idProject
20
+ */
21
+ export function requiredKey(field) {
22
+ return tag(values => {
23
+ const value = values[field]
24
+ return value === undefined || value === null || value === 0 ? `${field} is required` : ''
25
+ }, { required: true })
26
+ }
27
+
28
+ /**
29
+ * @pattern(regex)
30
+ * @param {string} field
31
+ * @param {RegExp} regex
32
+ * @param {string} [message]
33
+ */
34
+ export function pattern(field, regex, message = `${field} does not match ${regex}`) {
35
+ return tag(values => regex.test(values[field]) ? '' : message, { pattern: regex })
36
+ }
37
+
38
+ /**
39
+ * An enum: the value must be one of `allowed`.
40
+ * @param {string} field
41
+ * @param {any[]} allowed
42
+ */
43
+ export function oneOf(field, allowed) {
44
+ return tag(values => allowed.includes(values[field]) ? '' : `${field} must be one of ${allowed.join(', ')}`, { allowed })
45
+ }
46
+
47
+ // A generated rule says what it checks (required, allowed, pattern): a form reads it to choose its input
48
+ function tag(rule, facts) {
49
+ return Object.assign(rule, facts)
50
+ }
51
+
52
+ /**
53
+ * Runs the rules of a class on some fields: generated rules first, then the rules of the extended class.
54
+ * Only the first message of a field is kept, as on the server.
55
+ * @param {Function & {generatedRules?: object, rules?: object}} cls
56
+ * @param {object} values the complete candidate state
57
+ * @param {object | undefined} obj the object before the change, undefined for a creation
58
+ * @param {string[]} fields
59
+ * @returns {Record<string, string>} one message per field, '' when valid
60
+ */
61
+ export function runRules(cls, values, obj, fields) {
62
+ const errors = {}
63
+ for (const field of fields) {
64
+ let message = ''
65
+ for (const rule of [...(cls.generatedRules?.[field] ?? []), ...(cls.rules?.[field] ?? [])]) {
66
+ message = rule(values, obj)
67
+ if (message) break
68
+ }
69
+ errors[field] = message
70
+ }
71
+ return errors
72
+ }
@@ -0,0 +1,58 @@
1
+ import { config } from './config.js'
2
+ import { fromGraphQLErrors, NetworkError } from './errors.js'
3
+
4
+ // The transport (D9): one POST per operation, the query always in variables (keys starting with $ cannot be
5
+ // written in the text of a GraphQL query). No retry: a mutation sent twice could be applied twice.
6
+
7
+ /**
8
+ * Sends a GraphQL operation and returns its data. Throws a typed error (errors.js) when the response has errors.
9
+ * An aborted request rejects with the AbortError of fetch, untouched.
10
+ * @param {string} document the GraphQL document, with one operation
11
+ * @param {object} [variables]
12
+ * @param {{name?: string, signal?: AbortSignal, headers?: Record<string, string>}} [options]
13
+ * @returns {Promise<object>} the `data` of the response
14
+ */
15
+ export async function send(document, variables = {}, { name, signal, headers = {} } = {}) {
16
+ activity().pending++
17
+ try {
18
+ return await exchange(document, variables, { name, signal, headers })
19
+ } finally {
20
+ activity().pending--
21
+ }
22
+ }
23
+
24
+ /**
25
+ * The requests in progress, e.g. for a loading indicator. Reactive when configure({ reactive }) is called first.
26
+ * @returns {{pending: number}}
27
+ */
28
+ export function activity() {
29
+ config.activity ??= config.reactive({ pending: 0 })
30
+ return config.activity
31
+ }
32
+
33
+ async function exchange(document, variables, { name, signal, headers }) {
34
+ let response
35
+ try {
36
+ response = await config.fetch(config.url, {
37
+ method: 'POST',
38
+ headers: { 'content-type': 'application/json', accept: 'application/json', ...headers },
39
+ body: JSON.stringify({ query: document, operationName: name, variables }),
40
+ signal,
41
+ })
42
+ } catch (error) {
43
+ if (error?.name === 'AbortError') throw error
44
+ throw new NetworkError(`The server cannot be reached: ${error?.message ?? error}`, { cause: error })
45
+ }
46
+ let body
47
+ try {
48
+ body = await response.json()
49
+ } catch (error) {
50
+ if (error?.name === 'AbortError') throw error
51
+ throw new NetworkError(`The server did not send a GraphQL response (HTTP ${response.status})`, { status: response.status, cause: error })
52
+ }
53
+ if (Array.isArray(body?.errors) && body.errors.length > 0) throw fromGraphQLErrors(body.errors)
54
+ if (!response.ok || body?.data == null) {
55
+ throw new NetworkError(`The server did not send a GraphQL response (HTTP ${response.status})`, { status: response.status })
56
+ }
57
+ return body.data
58
+ }