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/draft.js ADDED
@@ -0,0 +1,186 @@
1
+ import { config } from './config.js'
2
+ import { ConflictError, ValidationError } from './errors.js'
3
+ import { hydrate } from './hydrate.js'
4
+ import { requestNamed } from './request.js'
5
+ import { runRules } from './rules.js'
6
+
7
+ /**
8
+ * The editing of an object, new or stored: what a form binds to (`v-model="draft.values.name"`).
9
+ *
10
+ * - `values`: the values being edited;
11
+ * - `base`: the values read at the start. An update sends only the changed fields, with their base value in
12
+ * `expected` (D14): the server refuses with CONFLICT if another user changed one of them in the meantime;
13
+ * - `errors`: one message per field, from the local rules (validate), the server check (check) or the save;
14
+ * - `conflicts`: the fields of the last conflict, whose value was replaced by the one of the server.
15
+ *
16
+ * The draft is reactive when configure({ reactive }) is set (D8).
17
+ * @template T
18
+ */
19
+ export class Draft {
20
+ /**
21
+ * @param {Function & {fields: string[], defaults: object, typeName: string, operations: object}} type
22
+ * @param {T | null} object the stored object, or null for a new one
23
+ * @param {object} [values] values set on top of the start values
24
+ */
25
+ constructor(type, object, values = {}) {
26
+ this.type = type
27
+ this.object = object
28
+ this.base = object ? object.values() : { ...type.defaults }
29
+ this.values = { ...this.base, ...values }
30
+ this.errors = {}
31
+ this.conflicts = []
32
+ return config.reactive(this)
33
+ }
34
+
35
+ /** True for an object not created yet. */
36
+ get isNew() {
37
+ return this.object === null
38
+ }
39
+
40
+ /** The fields of the input: the stored fields and foreign keys, without the id. */
41
+ get inputFields() {
42
+ return this.type.fields.filter(field => field !== 'id')
43
+ }
44
+
45
+ /** The fields whose value differs from the value read at the start. */
46
+ get changed() {
47
+ return this.inputFields.filter(field => !sameValue(this.values[field], this.base[field]))
48
+ }
49
+
50
+ /**
51
+ * Sets some values.
52
+ * @param {object} values
53
+ * @returns {this}
54
+ */
55
+ set(values) {
56
+ Object.assign(this.values, values)
57
+ return this
58
+ }
59
+
60
+ /** Back to the values read at the start, without errors. */
61
+ reset() {
62
+ this.values = { ...this.base }
63
+ this.errors = {}
64
+ this.conflicts = []
65
+ return this
66
+ }
67
+
68
+ /**
69
+ * Runs the local rules (generated and of the extended class) without a request. Sets `errors` for these fields.
70
+ * @param {string[]} [fields] all the input fields by default
71
+ * @returns {boolean} true when they are all valid
72
+ */
73
+ validate(fields = this.inputFields) {
74
+ const errors = runRules(this.type, { ...this.values }, this.object ?? undefined, fields)
75
+ Object.assign(this.errors, errors)
76
+ return Object.values(errors).every(message => message === '')
77
+ }
78
+
79
+ /**
80
+ * Checks the values on the server (xxxDataCheck), without changing anything: the rules of the server, its
81
+ * foreign keys and unique indexes included. Sets `errors` for these fields.
82
+ * @param {string[]} [fields] all the input fields by default
83
+ * @param {{name?: string, signal?: AbortSignal}} [options]
84
+ * @returns {Promise<boolean>} true when they are all valid
85
+ */
86
+ async check(fields = this.inputFields, { name, signal } = {}) {
87
+ const { typeName, operations } = this.type
88
+ const input = this.isNew ? this.input(this.inputFields) : this.input(this.changed)
89
+ const data = await requestNamed(`${typeName}DataCheck`, operation =>
90
+ `query ${operation}($input: ${typeName}Input!, $id: Int) { ${operations.dataCheck}(${operations.argument}: $input, id: $id) { ${this.inputFields.join(' ')} } }`,
91
+ { input, id: this.object?.id ?? null }, { name, signal })
92
+ const messages = data[operations.dataCheck]
93
+ for (const field of fields) this.errors[field] = messages[field] ?? ''
94
+ return fields.every(field => !this.errors[field])
95
+ }
96
+
97
+ /**
98
+ * Creates or updates the object. The local rules run first: an invalid draft is not sent.
99
+ * - a creation sends every input field;
100
+ * - an update sends only the changed fields, with `expected`; nothing is sent when nothing changed.
101
+ * On CONFLICT, the object is reloaded and each conflicting field of the draft takes the value of the server;
102
+ * `conflicts` lists them, and the error is thrown again: the form shows an alert, the user decides (D14).
103
+ * @param {{name?: string, signal?: AbortSignal}} [options]
104
+ * @returns {Promise<T>} the object, as the server stored it
105
+ */
106
+ async save({ name, signal } = {}) {
107
+ const { typeName, operations } = this.type
108
+ const fields = this.isNew ? this.inputFields : this.changed
109
+ if (!this.isNew && fields.length === 0) return this.object
110
+ if (!this.validate(fields)) {
111
+ throw new ValidationError(`${typeName} has invalid fields: ${fields.filter(field => this.errors[field]).join(', ')}`,
112
+ Object.fromEntries(fields.filter(field => this.errors[field]).map(field => [field, this.errors[field]])))
113
+ }
114
+ this.conflicts = []
115
+ let data
116
+ try {
117
+ if (this.isNew) {
118
+ data = await requestNamed(`${typeName}Create`, operation =>
119
+ `mutation ${operation}($input: ${typeName}Input!) { ${operations.create}(${operations.argument}: $input) { ${this.selection()} } }`,
120
+ { input: this.input(fields) }, { name, signal })
121
+ } else {
122
+ data = await requestNamed(`${typeName}Update`, operation =>
123
+ `mutation ${operation}($id: Int!, $input: ${typeName}Input!, $expected: ${typeName}Input) { ${operations.update}(id: $id, ${operations.argument}: $input, expected: $expected) { ${this.selection()} } }`,
124
+ { id: this.object.id, input: this.input(fields), expected: pick(this.base, fields) }, { name, signal })
125
+ }
126
+ } catch (error) {
127
+ if (error instanceof ValidationError) Object.assign(this.errors, error.fieldErrors)
128
+ if (error instanceof ConflictError) await this.takeConflict(error, signal)
129
+ throw error
130
+ }
131
+ const object = hydrate(this.type, data[this.isNew ? operations.create : operations.update])
132
+ this.object = object
133
+ this.base = object.values()
134
+ this.values = { ...this.base }
135
+ for (const field of fields) this.errors[field] = ''
136
+ return object
137
+ }
138
+
139
+ /**
140
+ * After a CONFLICT: reloads the object (the error does not hold its computed fields, D14) and puts the values of
141
+ * the server in the conflicting fields. Without the right to see the object, the draft is left as it is.
142
+ * @param {ConflictError} error
143
+ * @param {AbortSignal} [signal]
144
+ */
145
+ async takeConflict(error, signal) {
146
+ try {
147
+ await this.object.reload({ signal })
148
+ } catch {
149
+ return
150
+ }
151
+ const current = this.object.values()
152
+ // A field the user did not change follows the server: otherwise the next save would send the old value
153
+ // back and undo the change of the other user. A conflicting field takes the value of the server too.
154
+ for (const field of this.inputFields) {
155
+ if (error.fields.includes(field) || sameValue(this.values[field], this.base[field])) this.values[field] = current[field]
156
+ }
157
+ this.base = current
158
+ this.conflicts = [...error.fields]
159
+ }
160
+
161
+ /**
162
+ * The values of some fields, for an input.
163
+ * @param {string[]} fields
164
+ */
165
+ input(fields) {
166
+ return pick(this.values, fields)
167
+ }
168
+
169
+ /** The selection of the object returned by a mutation: its fields, computed and @transient fields. */
170
+ selection() {
171
+ return [...this.type.fields, ...this.type.computed, ...this.type.transient].join(' ')
172
+ }
173
+ }
174
+
175
+ function pick(values, fields) {
176
+ return Object.fromEntries(fields.map(field => [field, values[field] ?? null]))
177
+ }
178
+
179
+ // The same comparison as the server for expected (ramdb2 D45): strict, in depth for JSON values
180
+ function sameValue(a, b) {
181
+ if (a === b) return true
182
+ if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) return false
183
+ if (Array.isArray(a) !== Array.isArray(b)) return false
184
+ const keys = Object.keys(a)
185
+ return keys.length === Object.keys(b).length && keys.every(key => sameValue(a[key], b[key]))
186
+ }
package/src/errors.js ADDED
@@ -0,0 +1,105 @@
1
+ // The errors of ramdb2-server become typed JavaScript errors (D9): the caller catches them without reading the JSON.
2
+
3
+ /**
4
+ * Base class of the errors of ramdb2-client.
5
+ * `code` is the code of the server (extensions.code), `errors` the raw GraphQL errors of the response.
6
+ */
7
+ export class RamdbError extends Error {
8
+ name = 'RamdbError'
9
+
10
+ /**
11
+ * @param {string} message
12
+ * @param {{code?: string, errors?: object[], path?: (string|number)[]}} [details]
13
+ */
14
+ constructor(message, { code, errors = [], path } = {}) {
15
+ super(message)
16
+ this.code = code
17
+ this.errors = errors
18
+ this.path = path
19
+ }
20
+ }
21
+
22
+ /** BAD_USER_INPUT: `fieldErrors` holds one message per field, when the server gives them. */
23
+ export class ValidationError extends RamdbError {
24
+ name = 'ValidationError'
25
+
26
+ /**
27
+ * @param {string} message
28
+ * @param {Record<string, string>} fieldErrors
29
+ * @param {object} [details]
30
+ */
31
+ constructor(message, fieldErrors = {}, details = {}) {
32
+ super(message, { code: 'BAD_USER_INPUT', ...details })
33
+ this.fieldErrors = fieldErrors
34
+ }
35
+ }
36
+
37
+ /** CONFLICT (D14): `fields` changed in the meantime, `current` holds the stored values of the server, or undefined. */
38
+ export class ConflictError extends RamdbError {
39
+ name = 'ConflictError'
40
+
41
+ /**
42
+ * @param {string} message
43
+ * @param {string[]} fields
44
+ * @param {object | undefined} current
45
+ * @param {object} [details]
46
+ */
47
+ constructor(message, fields, current, details = {}) {
48
+ super(message, { code: 'CONFLICT', ...details })
49
+ this.fields = fields
50
+ this.current = current
51
+ }
52
+ }
53
+
54
+ export class NotFoundError extends RamdbError { name = 'NotFoundError' }
55
+ export class ForbiddenError extends RamdbError { name = 'ForbiddenError' }
56
+ export class IntegrityError extends RamdbError { name = 'IntegrityError' }
57
+ export class UnauthenticatedError extends RamdbError { name = 'UnauthenticatedError' }
58
+
59
+ /** The request did not reach the server, or its answer is not a GraphQL response. `status` is the HTTP status. */
60
+ export class NetworkError extends RamdbError {
61
+ name = 'NetworkError'
62
+
63
+ /**
64
+ * @param {string} message
65
+ * @param {{status?: number, cause?: unknown}} [details]
66
+ */
67
+ constructor(message, { status, cause } = {}) {
68
+ super(message)
69
+ this.status = status
70
+ if (cause !== undefined) this.cause = cause
71
+ }
72
+ }
73
+
74
+ /** A relation read without being loaded by the query (D5): add it to `include`. */
75
+ export class RelationNotLoadedError extends Error {
76
+ name = 'RelationNotLoadedError'
77
+ }
78
+
79
+ const BY_CODE = {
80
+ NOT_FOUND: NotFoundError,
81
+ FORBIDDEN: ForbiddenError,
82
+ INTEGRITY: IntegrityError,
83
+ UNAUTHENTICATED: UnauthenticatedError,
84
+ }
85
+
86
+ /**
87
+ * Builds the typed error of a GraphQL response from its `errors` list. The first error with a code is used.
88
+ * @param {object[]} errors
89
+ * @returns {RamdbError}
90
+ */
91
+ export function fromGraphQLErrors(errors) {
92
+ const first = errors.find(error => error.extensions?.code) ?? errors[0]
93
+ const extensions = first.extensions ?? {}
94
+ const details = { errors, path: first.path }
95
+ switch (extensions.code) {
96
+ case 'BAD_USER_INPUT':
97
+ return new ValidationError(first.message, extensions.errors ?? {}, details)
98
+ case 'CONFLICT':
99
+ return new ConflictError(first.message, extensions.fields ?? [], extensions.current, details)
100
+ default: {
101
+ const ErrorClass = BY_CODE[extensions.code] ?? RamdbError
102
+ return new ErrorClass(first.message, { code: extensions.code, ...details })
103
+ }
104
+ }
105
+ }
package/src/fields.js ADDED
@@ -0,0 +1,120 @@
1
+ // What a client class says about its fields, for the screens that show and edit them (D20): kind of input,
2
+ // label, required, allowed values, related type; and the text that shows an object.
3
+
4
+ const DISPLAY_FIELDS = ['name', 'label', 'title', 'code', 'login']
5
+
6
+ /**
7
+ * @typedef {object} FieldInfo
8
+ * @property {string} name the field, e.g. idProject
9
+ * @property {string} label from static labels, or the name of the field
10
+ * @property {'text' | 'textarea' | 'number' | 'boolean' | 'enum' | 'relation'} input the input that edits it
11
+ * @property {boolean} stored a stored field or a foreign key; false for a computed or @transient one (read-only)
12
+ * @property {boolean} required
13
+ * @property {any[]} [values] the values of an enum
14
+ * @property {Record<string, string>} [valueLabels] their labels, from static valueLabels
15
+ * @property {string} [relation] for a foreign key: the name of the relation, e.g. project
16
+ * @property {string} [type] for a foreign key: the related type, e.g. Project
17
+ */
18
+
19
+ /**
20
+ * Describes a field of a class.
21
+ * @param {Function & {fields: string[], computed: string[], transient: string[], relations: object, defaults: object, generatedRules: object, labels: object, inputs: object}} cls
22
+ * @param {string} field
23
+ * @returns {FieldInfo}
24
+ */
25
+ export function describeField(cls, field) {
26
+ const rules = cls.generatedRules?.[field] ?? []
27
+ const relationEntry = Object.entries(cls.relations).find(([, relation]) => !relation.list && relation.key === field)
28
+ const info = {
29
+ name: field,
30
+ label: labelOf(cls, field),
31
+ stored: cls.fields.includes(field),
32
+ required: rules.some(rule => rule.required),
33
+ input: 'text',
34
+ }
35
+ const allowed = rules.find(rule => rule.allowed)?.allowed
36
+ if (relationEntry) Object.assign(info, { input: 'relation', relation: relationEntry[0], type: relationEntry[1].type })
37
+ // An enum has no required rule: a nullable one allows null among its values (spec section 3 of ramdb2)
38
+ else if (allowed) Object.assign(info, { input: 'enum', values: allowed.filter(value => value !== null), required: !allowed.includes(null), valueLabels: cls.valueLabels?.[field] ?? {} })
39
+ else if (typeof cls.defaults[field] === 'number') info.input = 'number'
40
+ else if (typeof cls.defaults[field] === 'boolean') info.input = 'boolean'
41
+ if (cls.inputs?.[field]) info.input = cls.inputs[field]
42
+ return info
43
+ }
44
+
45
+ /**
46
+ * The label of a field, or of a path through relations (project.name). A foreign key takes the label of its
47
+ * relation when it has none: idProject -> labels.project.
48
+ * @param {Function & {labels: object, relations: object}} cls
49
+ * @param {string} path
50
+ */
51
+ export function labelOf(cls, path) {
52
+ if (cls.labels?.[path]) return cls.labels[path]
53
+ const [first, ...rest] = path.split('.')
54
+ // project.name: the label of the relation, "Project", is what a reader expects in a header
55
+ if (rest.length > 0) return labelOf(cls, first)
56
+ const relationEntry = Object.entries(cls.relations ?? {}).find(([, relation]) => !relation.list && relation.key === first)
57
+ if (relationEntry) return cls.labels?.[relationEntry[0]] ?? relationEntry[0]
58
+ return first
59
+ }
60
+
61
+ /**
62
+ * The field that shows an object of a class: static display, or the first of name, label, title, code, login.
63
+ * @param {Function & {display?: string, fields: string[]}} cls
64
+ * @returns {string} 'id' when there is none
65
+ */
66
+ export function displayField(cls) {
67
+ if (cls.display) return cls.display
68
+ return DISPLAY_FIELDS.find(field => cls.fields.includes(field)) ?? 'id'
69
+ }
70
+
71
+ /**
72
+ * The text that shows an object, e.g. in a list of choices or in a column of a relation.
73
+ * @param {object | null | undefined} obj
74
+ */
75
+ export function displayOf(obj) {
76
+ if (!obj) return ''
77
+ return String(obj[displayField(obj.constructor)] ?? obj.id)
78
+ }
79
+
80
+ /**
81
+ * The value at a path through loaded relations: valueAt(task, 'project.name'). Null when a relation is null.
82
+ * @param {object} obj
83
+ * @param {string} path
84
+ */
85
+ export function valueAt(obj, path) {
86
+ let value = obj
87
+ for (const part of path.split('.')) {
88
+ if (value === null || value === undefined) return null
89
+ value = value[part]
90
+ }
91
+ return value
92
+ }
93
+
94
+ /**
95
+ * The relations to include to show some columns: project.name -> project, and a foreign key -> its relation.
96
+ * @param {Function & {relations: object}} cls
97
+ * @param {string[]} columns
98
+ */
99
+ export function includeFor(cls, columns) {
100
+ const include = new Set()
101
+ for (const column of columns) {
102
+ const parts = column.split('.')
103
+ if (parts.length > 1) include.add(parts.slice(0, -1).join('.'))
104
+ else {
105
+ const relationEntry = Object.entries(cls.relations).find(([, relation]) => !relation.list && relation.key === column)
106
+ if (relationEntry) include.add(relationEntry[0])
107
+ }
108
+ }
109
+ return [...include]
110
+ }
111
+
112
+ /**
113
+ * The label of a value of an enum: static valueLabels, or the value itself.
114
+ * @param {Function & {valueLabels?: object}} cls
115
+ * @param {string} field
116
+ * @param {any} value
117
+ */
118
+ export function valueLabelOf(cls, field, value) {
119
+ return cls.valueLabels?.[field]?.[value] ?? (value === null || value === undefined ? '' : String(value))
120
+ }
package/src/hydrate.js ADDED
@@ -0,0 +1,57 @@
1
+ import { classOf, config } from './config.js'
2
+ import { getInstance, setInstance } from './identity.js'
3
+
4
+ // From the classes to the GraphQL selections, and from the responses to the instances (D5): an object is always
5
+ // loaded whole (stored fields, foreign keys, computed and @transient fields), its relations only when the query
6
+ // includes them.
7
+
8
+ /**
9
+ * Reads `include` into a tree, checking each relation: ['project', 'taskRoles.task'] -> {project: {}, taskRoles: {task: {}}}.
10
+ * @param {Function & {relations: object, typeName: string}} cls
11
+ * @param {string[]} [include]
12
+ */
13
+ export function includeTree(cls, include = []) {
14
+ const tree = {}
15
+ for (const path of include) {
16
+ let current = cls
17
+ let node = tree
18
+ for (const name of path.split('.')) {
19
+ const relation = current.relations[name]
20
+ if (!relation) throw new Error(`${current.typeName} has no relation ${name} (include: '${path}')`)
21
+ node = node[name] ??= {}
22
+ current = classOf(relation.type)
23
+ }
24
+ }
25
+ return tree
26
+ }
27
+
28
+ /**
29
+ * The GraphQL selection of a class: its fields, its computed and @transient fields, and the relations of the tree.
30
+ * @param {Function & {fields: string[], computed: string[], transient: string[], relations: object}} cls
31
+ * @param {object} [tree] from includeTree
32
+ */
33
+ export function selection(cls, tree = {}) {
34
+ const parts = [...cls.fields, ...cls.computed, ...cls.transient]
35
+ for (const [name, subtree] of Object.entries(tree)) {
36
+ parts.push(`${name} { ${selection(classOf(cls.relations[name].type), subtree)} }`)
37
+ }
38
+ return parts.join(' ')
39
+ }
40
+
41
+ /**
42
+ * The instance of an object received from the server: the one of the identity map, updated, or a new one.
43
+ * @template T
44
+ * @param {new () => T} cls
45
+ * @param {object} data the object in the response
46
+ * @param {object} [tree] the relations loaded with it
47
+ * @returns {T}
48
+ */
49
+ export function hydrate(cls, data, tree = {}) {
50
+ let instance = getInstance(cls.typeName, data.id)
51
+ if (!instance) {
52
+ instance = config.reactive(new cls())
53
+ setInstance(cls.typeName, data.id, instance)
54
+ }
55
+ instance._load(data, tree)
56
+ return instance
57
+ }
@@ -0,0 +1,58 @@
1
+ // The identity map (D5, D15): one instance per object, by type and id, so that every screen shows the same values.
2
+ // It holds weak references: an object that no component, list or other object holds any more is released by the
3
+ // garbage collector, and its entry is forgotten. It is not a cache (D14): every screen queries the server.
4
+
5
+ /** @type {Map<string, Map<number, WeakRef<object>>>} */
6
+ const tables = new Map()
7
+
8
+ const registry = new FinalizationRegistry(({ typeName, id, ref }) => {
9
+ const table = tables.get(typeName)
10
+ // The entry may hold a newer instance of the same object: forget only the released one
11
+ if (table?.get(id) === ref) table.delete(id)
12
+ })
13
+
14
+ /**
15
+ * The instance of an object, if one is alive.
16
+ * @param {string} typeName
17
+ * @param {number} id
18
+ * @returns {object | undefined}
19
+ */
20
+ export function getInstance(typeName, id) {
21
+ return tables.get(typeName)?.get(id)?.deref()
22
+ }
23
+
24
+ /**
25
+ * Records the instance of an object.
26
+ * @param {string} typeName
27
+ * @param {number} id
28
+ * @param {object} instance the object as the application sees it: the reactive proxy with Vue (D8)
29
+ */
30
+ export function setInstance(typeName, id, instance) {
31
+ let table = tables.get(typeName)
32
+ if (!table) tables.set(typeName, table = new Map())
33
+ const ref = new WeakRef(instance)
34
+ table.set(id, ref)
35
+ registry.register(instance, { typeName, id, ref })
36
+ }
37
+
38
+ /**
39
+ * Forgets an object, e.g. after its deletion.
40
+ * @param {string} typeName
41
+ * @param {number} id
42
+ */
43
+ export function forgetInstance(typeName, id) {
44
+ tables.get(typeName)?.delete(id)
45
+ }
46
+
47
+ /** Forgets every object: at logout, the data of the previous user does not stay in memory (D10). */
48
+ export function clearInstances() {
49
+ tables.clear()
50
+ }
51
+
52
+ /**
53
+ * Number of entries of a type, released objects included until the garbage collector reports them. For the tests.
54
+ * @param {string} typeName
55
+ */
56
+ export function instanceCount(typeName) {
57
+ return tables.get(typeName)?.size ?? 0
58
+ }
package/src/index.js ADDED
@@ -0,0 +1,13 @@
1
+ export { configure, register, classOf, setOperationPrefix, memoryStorage } from './config.js'
2
+ export { ClientObject } from './object.js'
3
+ export { Draft } from './draft.js'
4
+ export { request } from './request.js'
5
+ export { activity } from './transport.js'
6
+ export { login, logout, loadMe, session, isLoggedIn, renew, token, tokenExpiry } from './auth.js'
7
+ export { required, requiredKey, pattern, oneOf } from './rules.js'
8
+ export { clearInstances } from './identity.js'
9
+ export { describeField, labelOf, valueLabelOf, displayField, displayOf, valueAt, includeFor } from './fields.js'
10
+ export {
11
+ RamdbError, ValidationError, ConflictError, NotFoundError, ForbiddenError, IntegrityError,
12
+ UnauthenticatedError, NetworkError, RelationNotLoadedError,
13
+ } from './errors.js'