|
2 | 2 |
|
3 | 3 | /** |
4 | 4 | * [#29985 codemod] The "Data CRUD" facet of |
5 | | - * `ObjectStackProtocolImplementation`: the bodies of `probeRecord` moved out of |
6 | | - * `protocol.ts` whole by `scripts/codemod-split-protocol.mjs`. |
| 5 | + * `ObjectStackProtocolImplementation`: the bodies of `getData`, `cloneData`, |
| 6 | + * `probeRecord` moved out of `protocol.ts` whole by |
| 7 | + * `scripts/codemod-split-protocol.mjs`. |
7 | 8 | * |
8 | 9 | * A MOVE, not a redesign. `ProtocolDataCrudFacet` is a stateless facet over the host |
9 | 10 | * (ruling 6624345766): each static method below is the body of the class |
|
21 | 22 | * not move. |
22 | 23 | */ |
23 | 24 |
|
| 25 | +import { recordNotFoundError } from '@objectstack/core'; |
| 26 | +import { staleSummaryRefusalOrThrow, withEarnedAnswer } from '@objectstack/types'; |
| 27 | +import type { SummaryRecomputeRefusal } from '@objectstack/types'; |
| 28 | +import { omitInternalFieldsFromWriteResponse } from './write-response-internal-fields.js'; |
| 29 | +import type { DroppedFieldsEvent, EngineQueryOptions, ValidationAdvisoryEvent } from '@objectstack/spec/data'; |
| 30 | +import { |
| 31 | + redactStoredMetadataRow, |
| 32 | + serveStoredMetadataHashColumns, |
| 33 | + storedMetadataBodyProjection, |
| 34 | +} from './metadata-redaction.js'; |
| 35 | +import { CLONE_STRIP_FIELDS } from './protocol-write-constants.js'; |
| 36 | +import { projectionFieldsValue } from './protocol-list-query-params.js'; |
24 | 37 | import type { ProtocolHost } from './protocol-host.js'; |
25 | 38 |
|
26 | 39 | export class ProtocolDataCrudFacet { |
| 40 | + /** The body of `ObjectStackProtocolImplementation#getData`; the method's docblock there is its contract. */ |
| 41 | + static async getData(host: Pick<ProtocolHost, 'assertExpandTargetsExist' | 'assertObjectRegistered' | 'assertProjectionFieldsExist' | 'engine' | 'servedExpand' | 'storedHashDigest'>, request: { object: string, id: string, expand?: string | string[], select?: string | string[], context?: any }): Promise<{ |
| 42 | + object: string; |
| 43 | + id: string; |
| 44 | + record: Record<string, any>; |
| 45 | + }> { |
| 46 | + host.assertObjectRegistered(request.object); // [#3770] |
| 47 | + const queryOptions: any = { |
| 48 | + where: { id: request.id } |
| 49 | + }; |
| 50 | + if (request.context !== undefined) { |
| 51 | + queryOptions.context = request.context; |
| 52 | + } |
| 53 | + |
| 54 | + // Support fields for single-record retrieval |
| 55 | + // |
| 56 | + // [#4226] Gated exactly as on the list path. `GET /data/:object/:id` and |
| 57 | + // `GET /data/:object` read the same `select`/`expand` against the same |
| 58 | + // field map, so answering one with a 400 and the other with a silently |
| 59 | + // widened projection would recreate, one route over, the very split |
| 60 | + // ("two routes, opposite answers for one input") this issue was filed |
| 61 | + // about. |
| 62 | + // |
| 63 | + // [#26644] …including the empty projection: a blank `?select=` was |
| 64 | + // falsy and skipped, a comma-only one became `[]` — both answered every |
| 65 | + // column. Asked on any value present, as the list path asks it. |
| 66 | + if (request.select != null) { |
| 67 | + queryOptions.fields = typeof request.select === 'string' || Array.isArray(request.select) |
| 68 | + ? projectionFieldsValue(request.select, 'select') |
| 69 | + : request.select; |
| 70 | + host.assertProjectionFieldsExist(request.object, queryOptions.fields, 'select'); |
| 71 | + } |
| 72 | + // [#21086] Same read projection as the list path (`findData`): the row's |
| 73 | + // `type` is read even when `select` named only the body. |
| 74 | + const bodyProjection = storedMetadataBodyProjection(request.object, queryOptions.fields); |
| 75 | + if (bodyProjection.addedType) queryOptions.fields = bodyProjection.fields; |
| 76 | + |
| 77 | + // Support expand for single-record retrieval |
| 78 | + if (request.expand) { |
| 79 | + const expandNames = typeof request.expand === 'string' |
| 80 | + ? request.expand.split(',').map((s: string) => s.trim()).filter(Boolean) |
| 81 | + : request.expand; |
| 82 | + host.assertExpandTargetsExist(request.object, expandNames); |
| 83 | + const expand = {} as Record<string, any>; |
| 84 | + for (const rel of expandNames) { |
| 85 | + expand[rel] = { object: rel }; |
| 86 | + } |
| 87 | + // [#22661] The same exposure judgement as the list path: an entry |
| 88 | + // whose target does not serve `get` is withheld ({@link servedExpand}). |
| 89 | + const served = host.servedExpand(request.object, expand, 0); |
| 90 | + if (Object.keys(served).length > 0) queryOptions.expand = served; |
| 91 | + } |
| 92 | + |
| 93 | + // [#29764] The bag `engine.findOne` receives is typed as the engine |
| 94 | + // declares it. `queryOptions` stays the working bag: the projection |
| 95 | + // helpers above answer `unknown` (they serve the raw list query too), so |
| 96 | + // its `fields` has no declared type until it is handed on here. Keys are |
| 97 | + // copied only when present, so the engine sees the same bag as before. |
| 98 | + const findOneQuery: EngineQueryOptions = { |
| 99 | + where: queryOptions.where, |
| 100 | + ...(queryOptions.context !== undefined ? { context: queryOptions.context } : {}), |
| 101 | + ...(queryOptions.fields !== undefined ? { fields: queryOptions.fields } : {}), |
| 102 | + ...(queryOptions.expand !== undefined ? { expand: queryOptions.expand } : {}), |
| 103 | + }; |
| 104 | + const result = await host.engine.findOne(request.object, findOneQuery); |
| 105 | + if (result) { |
| 106 | + return { |
| 107 | + object: request.object, |
| 108 | + id: request.id, |
| 109 | + // [#21207] Same served form as the list path: the content-hash |
| 110 | + // columns keyed. |
| 111 | + record: await serveStoredMetadataHashColumns( |
| 112 | + request.object, |
| 113 | + redactStoredMetadataRow(request.object, result, { dropType: bodyProjection.addedType }), |
| 114 | + host.storedHashDigest(), |
| 115 | + ), |
| 116 | + }; |
| 117 | + } |
| 118 | + throw recordNotFoundError(request.object, request.id); |
| 119 | + } |
| 120 | + |
| 121 | + /** The body of `ObjectStackProtocolImplementation#cloneData`; the method's docblock there is its contract. */ |
| 122 | + static async cloneData(host: Pick<ProtocolHost, 'assertObjectRegistered' | 'engine'>, request: { object: string, id: string, overrides?: Record<string, any>, context?: any }): Promise<{ |
| 123 | + warnings?: { |
| 124 | + rule: string; |
| 125 | + severity: "info" | "warning"; |
| 126 | + field: string; |
| 127 | + code: string; |
| 128 | + message: string; |
| 129 | + }[] | undefined; |
| 130 | + droppedFields?: { |
| 131 | + object: string; |
| 132 | + fields: string[]; |
| 133 | + reason: "readonly" | "computed" | "readonly_when" | "primary_key" | "stored_expression"; |
| 134 | + }[] | undefined; |
| 135 | + object: string; |
| 136 | + id: any; |
| 137 | + sourceId: string; |
| 138 | + record: any; |
| 139 | + }> { |
| 140 | + // [#3770] This object-existence check used to be open-coded here and |
| 141 | + // was the ONLY one on the whole data plane; it is now the shared gate |
| 142 | + // every data entry point runs. Same error envelope as before. |
| 143 | + host.assertObjectRegistered(request.object); |
| 144 | + const schema: any = host.engine.registry?.getObject(request.object); |
| 145 | + // `enable.clone` defaults to true in the spec; treat an absent block / |
| 146 | + // absent flag as enabled and only block on an explicit `false`. |
| 147 | + if (schema?.enable?.clone === false) { |
| 148 | + const err: any = new Error(`Cloning is disabled for object '${request.object}'`); |
| 149 | + err.code = 'CLONE_DISABLED'; |
| 150 | + err.status = 403; |
| 151 | + err.object = request.object; |
| 152 | + throw err; |
| 153 | + } |
| 154 | + |
| 155 | + const ctx = request.context; |
| 156 | + const ctxOpt = ctx !== undefined ? { context: ctx } : undefined; |
| 157 | + |
| 158 | + const source = await host.engine.findOne( |
| 159 | + request.object, |
| 160 | + { where: { id: request.id }, ...ctxOpt }, |
| 161 | + ); |
| 162 | + if (!source) throw recordNotFoundError(request.object, request.id); |
| 163 | + |
| 164 | + // Copy the source, then strip the columns the engine owns so the insert |
| 165 | + // path re-derives them rather than carrying the source's values over. |
| 166 | + const data: Record<string, any> = { ...source }; |
| 167 | + for (const f of CLONE_STRIP_FIELDS) delete data[f]; |
| 168 | + const fields: Record<string, any> = schema?.fields || {}; |
| 169 | + for (const [name, def] of Object.entries(fields)) { |
| 170 | + if (!def) continue; |
| 171 | + // Engine-/automation-owned values: injected system/audit columns, |
| 172 | + // engine-generated autonumbers, and computed formula/summary fields. |
| 173 | + if ((def as any).system === true |
| 174 | + || (def as any).type === 'autonumber' |
| 175 | + || (def as any).type === 'formula' |
| 176 | + || (def as any).type === 'summary') { |
| 177 | + delete data[name]; |
| 178 | + continue; |
| 179 | + } |
| 180 | + // [#29200] A read-only column the source left EMPTY is not carried |
| 181 | + // into the insert. Carried, it reached `engine.insert`'s strip as a |
| 182 | + // present key and was reported in `droppedFields` (and the |
| 183 | + // `X-ObjectStack-Dropped-Fields` header) although neither the caller |
| 184 | + // nor the source supplied a value. Leaving it out stores the same |
| 185 | + // row: the strip would have taken it from a non-system caller, and |
| 186 | + // the insert's defaults treat an explicit `null` exactly as an |
| 187 | + // omitted key. A read-only column that HOLDS a value is still |
| 188 | + // carried, stripped and reported (#15703), and so is one the caller |
| 189 | + // sets through `overrides`, which are applied below. |
| 190 | + if ((def as any).readonly && data[name] == null) delete data[name]; |
| 191 | + } |
| 192 | + // Caller overrides win (new name, cleared unique field, reset status…). |
| 193 | + if (request.overrides && typeof request.overrides === 'object') { |
| 194 | + Object.assign(data, request.overrides); |
| 195 | + } |
| 196 | + |
| 197 | + // [#3043/#14147] A clone is a create: a non-system caller must not carry |
| 198 | + // over (or override in) a read-only column — copying the source's |
| 199 | + // `approval_status` or forging one via `overrides` would mint an approved |
| 200 | + // record. That strip is `engine.insert`'s since #14147, so the payload |
| 201 | + // goes over whole and the insert re-derives the field's `defaultValue`, |
| 202 | + // symmetric with createData. `overrides` are applied ABOVE this line, so |
| 203 | + // a readonly key smuggled through them is still judged by the strip. |
| 204 | + // |
| 205 | + // [#15703] And the verdict is REPORTED, the same listener `createData` |
| 206 | + // wires: a clone is the one create shape that carries a read-only column |
| 207 | + // without the caller typing it (the source's `approval_status` travels in |
| 208 | + // the copy), so the 201 body says which keys the engine dropped instead of |
| 209 | + // leaving the caller to diff `record` against the source. Maintainer |
| 210 | + // ruling 2026-09-08 (option 1); `CloneDataResponseSchema` declares the |
| 211 | + // member in the same change, because that schema is declared AS PRODUCED. |
| 212 | + const dropped: DroppedFieldsEvent[] = []; |
| 213 | + // [#22726] A clone is a create: its advisory rule hits are answered as |
| 214 | + // `warnings`, the same listener `createData` wires. |
| 215 | + const warnings: ValidationAdvisoryEvent[] = []; |
| 216 | + const opts: any = { |
| 217 | + onFieldsDropped: (e: DroppedFieldsEvent) => { dropped.push(e); }, |
| 218 | + onValidationAdvisory: (e: ValidationAdvisoryEvent) => { warnings.push(e); }, |
| 219 | + }; |
| 220 | + if (ctx !== undefined) opts.context = ctx; |
| 221 | + // [#28782] A copy the engine stored but whose parent roll-up it could |
| 222 | + // not recompute carries this method's answer on the refusal, as |
| 223 | + // `createData` does since #28781 (`withEarnedAnswer`). |
| 224 | + let stale: SummaryRecomputeRefusal | undefined; |
| 225 | + const result = await host.engine.insert(request.object, data, opts) |
| 226 | + .catch((e: unknown) => (stale = staleSummaryRefusalOrThrow(e)).written as any); |
| 227 | + // [#7823] Same ingress strip as `createData` — a clone's 201 body is |
| 228 | + // the same generic-data-path surface. (The SOURCE row was read through |
| 229 | + // the engine's find path, which already omits internal fields, so the |
| 230 | + // copy never carried one in; this guards the INSERT RESULT, which the |
| 231 | + // engine returns whole by design.) |
| 232 | + omitInternalFieldsFromWriteResponse(schema, result); |
| 233 | + const answer = { |
| 234 | + object: request.object, |
| 235 | + id: result.id, |
| 236 | + sourceId: request.id, |
| 237 | + record: result, |
| 238 | + ...(dropped.length > 0 ? { droppedFields: dropped } : {}), |
| 239 | + ...(warnings.length > 0 ? { warnings } : {}), |
| 240 | + }; |
| 241 | + if (stale) throw withEarnedAnswer(stale, answer); |
| 242 | + return answer; |
| 243 | + } |
| 244 | + |
27 | 245 | /** |
28 | 246 | * [#4435] Does this row EXIST? A fact about the database — deliberately |
29 | 247 | * NOT "may this caller see it". |
|
0 commit comments