@stonyx/orm 0.2.1-alpha.12 → 0.2.1-alpha.13

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.
@@ -3,7 +3,6 @@ import { getMysqlType } from './type-map.js';
3
3
  import { camelCaseToKebabCase } from '@stonyx/utils/string';
4
4
  import { getPluralName } from '../plural-registry.js';
5
5
  import { dbKey } from '../db.js';
6
- import { AggregateProperty } from '../aggregates.js';
7
6
 
8
7
  function getRelationshipInfo(property) {
9
8
  if (typeof property !== 'function') return null;
@@ -145,166 +144,6 @@ export function getTopologicalOrder(schemas) {
145
144
  return order;
146
145
  }
147
146
 
148
- export function introspectViews() {
149
- const orm = Orm.instance;
150
- if (!orm.views) return {};
151
-
152
- const schemas = {};
153
-
154
- for (const [viewKey, viewClass] of Object.entries(orm.views)) {
155
- const name = camelCaseToKebabCase(viewKey.slice(0, -4)); // Remove 'View' suffix
156
-
157
- const source = viewClass.source;
158
- if (!source) continue;
159
-
160
- const model = new viewClass(name);
161
- const columns = {};
162
- const foreignKeys = {};
163
- const aggregates = {};
164
- const relationships = { belongsTo: {}, hasMany: {} };
165
-
166
- for (const [key, property] of Object.entries(model)) {
167
- if (key.startsWith('__')) continue;
168
- if (key === 'id') continue;
169
-
170
- if (property instanceof AggregateProperty) {
171
- aggregates[key] = property;
172
- continue;
173
- }
174
-
175
- const relType = getRelationshipInfo(property);
176
-
177
- if (relType === 'belongsTo') {
178
- relationships.belongsTo[key] = true;
179
- const modelName = camelCaseToKebabCase(key);
180
- const fkColumn = `${key}_id`;
181
- foreignKeys[fkColumn] = {
182
- references: getPluralName(modelName),
183
- column: 'id',
184
- };
185
- } else if (relType === 'hasMany') {
186
- relationships.hasMany[key] = true;
187
- } else if (property?.constructor?.name === 'ModelProperty') {
188
- const transforms = Orm.instance.transforms;
189
- columns[key] = getMysqlType(property.type, transforms[property.type]);
190
- }
191
- }
192
-
193
- schemas[name] = {
194
- viewName: getPluralName(name),
195
- source,
196
- groupBy: viewClass.groupBy || undefined,
197
- columns,
198
- foreignKeys,
199
- aggregates,
200
- relationships,
201
- isView: true,
202
- memory: viewClass.memory !== false ? false : false, // Views default to memory:false
203
- };
204
- }
205
-
206
- return schemas;
207
- }
208
-
209
- export function buildViewDDL(name, viewSchema, modelSchemas = {}) {
210
- if (!viewSchema.source) {
211
- throw new Error(`View '${name}' must define a source model`);
212
- }
213
-
214
- const sourceModelName = viewSchema.source;
215
- const sourceSchema = modelSchemas[sourceModelName];
216
- const sourceTable = sourceSchema
217
- ? sourceSchema.table
218
- : getPluralName(sourceModelName);
219
-
220
- const selectColumns = [];
221
- const joins = [];
222
- const hasAggregates = Object.keys(viewSchema.aggregates || {}).length > 0;
223
- const groupByField = viewSchema.groupBy;
224
-
225
- // ID column: groupBy field or source table PK
226
- if (groupByField) {
227
- selectColumns.push(`\`${sourceTable}\`.\`${groupByField}\` AS \`id\``);
228
- } else {
229
- selectColumns.push(`\`${sourceTable}\`.\`id\` AS \`id\``);
230
- }
231
-
232
- // Aggregate columns
233
- for (const [key, aggProp] of Object.entries(viewSchema.aggregates || {})) {
234
- if (aggProp.relationship === undefined) {
235
- // Field-level aggregate (groupBy views)
236
- if (aggProp.aggregateType === 'count') {
237
- selectColumns.push(`COUNT(*) AS \`${key}\``);
238
- } else {
239
- selectColumns.push(`${aggProp.mysqlFunction}(\`${sourceTable}\`.\`${aggProp.field}\`) AS \`${key}\``);
240
- }
241
- } else {
242
- // Relationship aggregate
243
- const relName = aggProp.relationship;
244
- const relModelName = camelCaseToKebabCase(relName);
245
- const relTable = getPluralName(relModelName);
246
-
247
- if (aggProp.aggregateType === 'count') {
248
- selectColumns.push(`${aggProp.mysqlFunction}(\`${relTable}\`.\`id\`) AS \`${key}\``);
249
- } else {
250
- const field = aggProp.field;
251
- selectColumns.push(`${aggProp.mysqlFunction}(\`${relTable}\`.\`${field}\`) AS \`${key}\``);
252
- }
253
-
254
- // Add LEFT JOIN for the relationship if not already added
255
- const joinKey = `${relTable}`;
256
- if (!joins.find(j => j.table === joinKey)) {
257
- const fkColumn = `${sourceModelName}_id`;
258
- joins.push({
259
- table: relTable,
260
- condition: `\`${relTable}\`.\`${fkColumn}\` = \`${sourceTable}\`.\`id\``
261
- });
262
- }
263
- }
264
- }
265
-
266
- // Regular columns (from resolve map string paths or direct attr fields)
267
- for (const [key, mysqlType] of Object.entries(viewSchema.columns || {})) {
268
- selectColumns.push(`\`${sourceTable}\`.\`${key}\` AS \`${key}\``);
269
- }
270
-
271
- // Build JOIN clauses
272
- const joinClauses = joins.map(j =>
273
- `LEFT JOIN \`${j.table}\` ON ${j.condition}`
274
- ).join('\n ');
275
-
276
- // Build GROUP BY
277
- let groupBy = '';
278
- if (groupByField) {
279
- groupBy = `\nGROUP BY \`${sourceTable}\`.\`${groupByField}\``;
280
- } else if (hasAggregates) {
281
- groupBy = `\nGROUP BY \`${sourceTable}\`.\`id\``;
282
- }
283
-
284
- const viewName = viewSchema.viewName;
285
- const sql = `CREATE OR REPLACE VIEW \`${viewName}\` AS\nSELECT\n ${selectColumns.join(',\n ')}\nFROM \`${sourceTable}\`${joinClauses ? '\n ' + joinClauses : ''}${groupBy}`;
286
-
287
- return sql;
288
- }
289
-
290
- export function viewSchemasToSnapshot(viewSchemas) {
291
- const snapshot = {};
292
-
293
- for (const [name, schema] of Object.entries(viewSchemas)) {
294
- snapshot[name] = {
295
- viewName: schema.viewName,
296
- source: schema.source,
297
- ...(schema.groupBy ? { groupBy: schema.groupBy } : {}),
298
- columns: { ...schema.columns },
299
- foreignKeys: { ...schema.foreignKeys },
300
- isView: true,
301
- viewQuery: buildViewDDL(name, schema),
302
- };
303
- }
304
-
305
- return snapshot;
306
- }
307
-
308
147
  export function schemasToSnapshot(schemas) {
309
148
  const snapshot = {};
310
149
 
@@ -323,27 +323,21 @@ export default class OrmRequest extends Request {
323
323
  };
324
324
 
325
325
  // Wrap handlers with hooks
326
- const isView = Orm.instance?.isView?.(model);
327
-
328
326
  this.handlers = {
329
327
  get: {
330
328
  '/': this._withHooks('list', getCollectionHandler),
331
329
  '/:id': this._withHooks('get', getSingleHandler),
332
330
  ...this._generateRelationshipRoutes(model, pluralizedModel, modelRelationships)
333
331
  },
334
- };
335
-
336
- // Views are read-only — no write endpoints
337
- if (!isView) {
338
- this.handlers.patch = {
332
+ patch: {
339
333
  '/:id': this._withHooks('update', updateHandler)
340
- };
341
- this.handlers.post = {
334
+ },
335
+ post: {
342
336
  '/': this._withHooks('create', createHandler)
343
- };
344
- this.handlers.delete = {
337
+ },
338
+ delete: {
345
339
  '/:id': this._withHooks('delete', deleteHandler)
346
- };
340
+ }
347
341
  }
348
342
  }
349
343
 
package/src/serializer.js CHANGED
@@ -71,8 +71,8 @@ export default class Serializer {
71
71
  const handler = model[key];
72
72
  const data = query(rawData, pathPrefix, subPath);
73
73
 
74
- // Ignore null/undefined values on updates (TODO: What if we want it set to null?)
75
- if ((data === null || data === undefined) && options.update) continue;
74
+ // Skip fields not present in the update payload (undefined = not provided)
75
+ if (data === undefined && options.update) continue;
76
76
 
77
77
  // Relationship handling
78
78
  if (typeof handler === 'function') {
@@ -86,13 +86,6 @@ export default class Serializer {
86
86
  continue;
87
87
  }
88
88
 
89
- // Aggregate property handling — use the rawData value, not the aggregate descriptor
90
- if (handler?.constructor?.name === 'AggregateProperty') {
91
- parsedData[key] = data;
92
- record[key] = data;
93
- continue;
94
- }
95
-
96
89
  // Direct assignment handling
97
90
  if (handler?.constructor?.name !== 'ModelProperty') {
98
91
  parsedData[key] = handler;
@@ -41,7 +41,7 @@ export default async function(route, accessPath, metaRoute) {
41
41
  // Remove "/" prefix and name mount point accordingly
42
42
  const name = route === '/' ? 'index' : (route[0] === '/' ? route.slice(1) : route);
43
43
 
44
- // Configure endpoints for models and views with access configuration
44
+ // Configure endpoints for models with access configuration
45
45
  for (const [model, access] of Object.entries(accessFiles)) {
46
46
  const pluralizedModel = getPluralName(model);
47
47
  const modelName = name === 'index' ? pluralizedModel : `${name}/${pluralizedModel}`;
package/src/store.js CHANGED
@@ -1,6 +1,5 @@
1
- import Orm, { relationships } from '@stonyx/orm';
1
+ import { relationships } from '@stonyx/orm';
2
2
  import { TYPES } from './relationships.js';
3
- import ViewResolver from './view-resolver.js';
4
3
 
5
4
  export default class Store {
6
5
  constructor() {
@@ -29,12 +28,6 @@ export default class Store {
29
28
  * @returns {Promise<Record|undefined>}
30
29
  */
31
30
  async find(modelName, id) {
32
- // For views in non-MySQL mode, use view resolver
33
- if (Orm.instance?.isView?.(modelName) && !this._mysqlDb) {
34
- const resolver = new ViewResolver(modelName);
35
- return resolver.resolveOne(id);
36
- }
37
-
38
31
  // For memory: true models, the store is authoritative
39
32
  if (this._isMemoryModel(modelName)) {
40
33
  return this.get(modelName, id);
@@ -57,18 +50,6 @@ export default class Store {
57
50
  * @returns {Promise<Record[]>}
58
51
  */
59
52
  async findAll(modelName, conditions) {
60
- // For views in non-MySQL mode, use view resolver
61
- if (Orm.instance?.isView?.(modelName) && !this._mysqlDb) {
62
- const resolver = new ViewResolver(modelName);
63
- const records = await resolver.resolveAll();
64
-
65
- if (!conditions || Object.keys(conditions).length === 0) return records;
66
-
67
- return records.filter(record =>
68
- Object.entries(conditions).every(([key, value]) => record.__data[key] === value)
69
- );
70
- }
71
-
72
53
  // For memory: true models without conditions, return from store
73
54
  if (this._isMemoryModel(modelName) && !conditions) {
74
55
  const modelStore = this.get(modelName);
@@ -144,11 +125,6 @@ export default class Store {
144
125
  }
145
126
 
146
127
  remove(key, id) {
147
- // Guard: read-only views cannot have records removed
148
- if (Orm.instance?.isView?.(key)) {
149
- throw new Error(`Cannot remove records from read-only view '${key}'`);
150
- }
151
-
152
128
  if (id) return this.unloadRecord(key, id);
153
129
 
154
130
  this.unloadAllRecords(key);
package/.claude/views.md DELETED
@@ -1,292 +0,0 @@
1
- # Views
2
-
3
- Views are read-only, model-like structures that compute derived data from existing models. They work in both JSON file mode (in-memory computation) and MySQL mode (auto-generated SQL VIEWs).
4
-
5
- ## What Views Are
6
-
7
- A View defines a read-only projection over source model data. Use views when you need:
8
- - Aggregated data (counts, averages, sums) derived from model relationships
9
- - Computed read-only summaries that shouldn't be persisted as separate records
10
- - MySQL VIEWs that are auto-generated from your JavaScript definition
11
-
12
- ## Defining a View
13
-
14
- Views extend the `View` base class and are placed in the `views/` directory (configurable via `paths.view`).
15
-
16
- ```javascript
17
- // views/owner-stats.js
18
- import { View, attr, belongsTo, count, avg } from '@stonyx/orm';
19
-
20
- export default class OwnerStatsView extends View {
21
- static source = 'owner'; // The model whose records are iterated
22
-
23
- animalCount = count('pets'); // COUNT of hasMany relationship
24
- averageAge = avg('pets', 'age'); // AVG of a field on related records
25
- owner = belongsTo('owner'); // Link back to the source record
26
- }
27
- ```
28
-
29
- ### File Naming
30
-
31
- - File: `owner-stats.js` → Class: `OwnerStatsView` → Store name: `'owner-stats'`
32
- - Directory: configured via `paths.view` (default: `'./views'`)
33
- - Environment variable: `ORM_VIEW_PATH`
34
-
35
- ### Key Static Properties
36
-
37
- | Property | Default | Description |
38
- |----------|---------|-------------|
39
- | `source` | `undefined` | **(Required)** The model name whose records produce view records |
40
- | `groupBy` | `undefined` | Field name to group source records by (one view record per unique value) |
41
- | `resolve` | `undefined` | Optional escape-hatch map for custom derivations |
42
- | `memory` | `false` | `false` = computed on demand; `true` = cached on startup |
43
- | `readOnly` | `true` | **Enforced** — cannot be overridden to `false` |
44
- | `pluralName` | `undefined` | Custom plural name (same as Model) |
45
-
46
- ## Aggregate Helpers
47
-
48
- Aggregate helpers define fields that compute values from related records. Each helper knows both its JavaScript computation logic and its MySQL SQL translation.
49
-
50
- | Helper | JS Behavior | MySQL Translation |
51
- |--------|-------------|-------------------|
52
- | `count(relationship)` | `relatedRecords.length` | `COUNT(table.id)` |
53
- | `avg(relationship, field)` | Average of field values | `AVG(table.field)` |
54
- | `sum(relationship, field)` | Sum of field values | `SUM(table.field)` |
55
- | `min(relationship, field)` | Minimum field value | `MIN(table.field)` |
56
- | `max(relationship, field)` | Maximum field value | `MAX(table.field)` |
57
-
58
- ### Empty/Null Handling
59
-
60
- - `count` with empty/null relationship → `0`
61
- - `avg` with empty/null relationship → `0`
62
- - `sum` with empty/null relationship → `0`
63
- - `min` with empty/null relationship → `null`
64
- - `max` with empty/null relationship → `null`
65
- - Non-numeric values are filtered/treated as 0
66
-
67
- ## Resolve Map (Escape Hatch)
68
-
69
- For computed fields that can't be expressed as aggregates, use `static resolve`:
70
-
71
- ```javascript
72
- export default class OwnerStatsView extends View {
73
- static source = 'owner';
74
-
75
- static resolve = {
76
- gender: 'gender', // String path: maps from source record data
77
- score: (owner) => { // Function: custom computation
78
- return owner.__data.age * 10;
79
- },
80
- nestedVal: 'details.nested', // Nested string paths supported
81
- };
82
-
83
- // Must also define as attr() for the serializer to process
84
- gender = attr('string');
85
- score = attr('number');
86
- nestedVal = attr('passthrough');
87
-
88
- animalCount = count('pets');
89
- }
90
- ```
91
-
92
- **Important:** Each resolve map entry needs a corresponding `attr()` field definition on the view.
93
-
94
- ## GroupBy Views
95
-
96
- GroupBy views produce one view record per unique value of a field on the source model, with aggregates computed within each group.
97
-
98
- ### Defining a GroupBy View
99
-
100
- ```javascript
101
- import { View, attr, count, avg, sum } from '@stonyx/orm';
102
-
103
- export default class AnimalCountBySizeView extends View {
104
- static source = 'animal';
105
- static groupBy = 'size'; // Group animals by their size field
106
-
107
- id = attr('string'); // The group key becomes the id
108
- animalCount = count(); // Count records in each group
109
- averageAge = avg('age'); // Average of 'age' field within each group
110
- }
111
- ```
112
-
113
- ### Aggregate Helpers in GroupBy Views
114
-
115
- In groupBy views, aggregate helpers operate on the group's records rather than on relationships:
116
-
117
- | Helper | GroupBy Behavior | MySQL Translation |
118
- |--------|-----------------|-------------------|
119
- | `count()` | Number of records in the group | `COUNT(*)` |
120
- | `sum('field')` | Sum of field across group records | `SUM(source.field)` |
121
- | `avg('field')` | Average of field across group records | `AVG(source.field)` |
122
- | `min('field')` | Minimum field value in the group | `MIN(source.field)` |
123
- | `max('field')` | Maximum field value in the group | `MAX(source.field)` |
124
-
125
- Relationship aggregates (e.g., `count('traits')`) also work — they flatten related records across all group members and aggregate the combined set.
126
-
127
- ### Resolve Map in GroupBy Views
128
-
129
- The resolve map behaves differently in groupBy views:
130
- - **Function resolvers** receive the **array of group records** (not a single record)
131
- - **String path resolvers** take the value from the **first record** in the group
132
-
133
- ```javascript
134
- export default class LeagueStatsView extends View {
135
- static source = 'game-stats';
136
- static groupBy = 'competition';
137
-
138
- static resolve = {
139
- totalGoals: (groupRecords) => {
140
- return groupRecords.reduce((sum, r) => {
141
- const fs = r.__data.finalScore;
142
- return fs ? sum + fs[0] + fs[1] : sum;
143
- }, 0);
144
- },
145
- };
146
-
147
- matchCount = count();
148
- totalGoals = attr('number');
149
- }
150
- ```
151
-
152
- ### MySQL DDL for GroupBy Views
153
-
154
- ```sql
155
- CREATE OR REPLACE VIEW `animal-count-by-sizes` AS
156
- SELECT
157
- `animals`.`size` AS `id`,
158
- COUNT(*) AS `animalCount`,
159
- AVG(`animals`.`age`) AS `averageAge`
160
- FROM `animals`
161
- GROUP BY `animals`.`size`
162
- ```
163
-
164
- ## Querying Views
165
-
166
- Views use the same store API as models:
167
-
168
- ```javascript
169
- // All view records (computed fresh each call in JSON mode)
170
- const stats = await store.findAll('owner-stats');
171
-
172
- // Single view record by source ID
173
- const stat = await store.find('owner-stats', ownerId);
174
-
175
- // With conditions
176
- const filtered = await store.findAll('owner-stats', { animalCount: 5 });
177
- ```
178
-
179
- ## Read-Only Enforcement
180
-
181
- Views are strictly read-only at all layers:
182
-
183
- ```javascript
184
- // All of these throw errors:
185
- createRecord('owner-stats', data); // Error: Cannot create records for read-only view
186
- updateRecord(viewRecord, data); // Error: Cannot update records for read-only view
187
- store.remove('owner-stats', id); // Error: Cannot remove records from read-only view
188
-
189
- // Internal use only — bypasses guard:
190
- createRecord('owner-stats', data, { isDbRecord: true }); // Used by resolver/loader
191
- ```
192
-
193
- ## REST API Behavior
194
-
195
- When a view is included in an access configuration, only GET endpoints are mounted:
196
-
197
- - `GET /view-plural-name` — Returns list of view records
198
- - `GET /view-plural-name/:id` — Returns single view record
199
- - `GET /view-plural-name/:id/{relationship}` — Related resources
200
- - No POST, PATCH, DELETE endpoints
201
-
202
- ## JSON Mode (In-Memory Resolver)
203
-
204
- In JSON/non-MySQL mode, the ViewResolver:
205
-
206
- 1. Iterates all records of the `source` model from the store
207
- 2. For each source record:
208
- - Computes aggregate properties from relationships
209
- - Applies resolve map entries (string paths or functions)
210
- - Maps regular attr fields from source data
211
- 3. Creates view records via `createRecord` with `isDbRecord: true`
212
- 4. Returns computed array
213
-
214
- ## MySQL Mode
215
-
216
- In MySQL mode:
217
-
218
- 1. **Schema introspection** generates VIEW metadata via `introspectViews()`
219
- 2. **DDL generation** creates `CREATE OR REPLACE VIEW` SQL from aggregates and relationships
220
- 3. **Queries** use `SELECT * FROM \`view_name\`` just like tables
221
- 4. **Migrations** include `CREATE OR REPLACE VIEW` after table statements
222
- 5. **persist()** is a no-op for views
223
- 6. **loadMemoryRecords()** loads views with `memory: true` from the MySQL VIEW
224
-
225
- ### Generated SQL Example
226
-
227
- For `OwnerStatsView` with `count('pets')` and `avg('pets', 'age')`:
228
-
229
- ```sql
230
- CREATE OR REPLACE VIEW `owner-stats` AS
231
- SELECT
232
- `owners`.`id` AS `id`,
233
- COUNT(`animals`.`id`) AS `animalCount`,
234
- AVG(`animals`.`age`) AS `avgAge`
235
- FROM `owners`
236
- LEFT JOIN `animals` ON `animals`.`owner_id` = `owners`.`id`
237
- GROUP BY `owners`.`id`
238
- ```
239
-
240
- ## Migration Support
241
-
242
- Views are handled in migrations alongside tables:
243
-
244
- - **Added views** → `CREATE OR REPLACE VIEW ...` in UP, `DROP VIEW IF EXISTS ...` in DOWN
245
- - **Removed views** → Commented `DROP VIEW` warning in UP (matching model removal pattern)
246
- - **Changed views** → `CREATE OR REPLACE VIEW ...` in UP (replaces automatically)
247
- - Views appear AFTER table statements in migrations (dependency order)
248
- - Snapshots include view entries with `isView: true` and `viewQuery`
249
-
250
- ## Memory Flag
251
-
252
- - `static memory = false` (default) — View records are computed fresh on each query
253
- - `static memory = true` — View records are loaded from MySQL VIEW on startup and cached
254
-
255
- ## Testing Views
256
-
257
- ```javascript
258
- import QUnit from 'qunit';
259
- import { store } from '@stonyx/orm';
260
-
261
- QUnit.test('view returns computed data', async function(assert) {
262
- // Create source data
263
- createRecord('owner', { id: 1, name: 'Alice' }, { serialize: false });
264
- createRecord('animal', { id: 1, age: 3, owner: 1 }, { serialize: false });
265
-
266
- // Query the view
267
- const results = await store.findAll('owner-stats');
268
- const stat = results.find(r => r.id === 1);
269
-
270
- assert.strictEqual(stat.__data.animalCount, 1);
271
- });
272
- ```
273
-
274
- ## Architecture
275
-
276
- ### Source Files
277
-
278
- | File | Purpose |
279
- |------|---------|
280
- | `src/view.js` | View base class |
281
- | `src/aggregates.js` | AggregateProperty class + helper functions |
282
- | `src/view-resolver.js` | In-memory view resolver |
283
- | `src/mysql/schema-introspector.js` | `introspectViews()`, `buildViewDDL()` |
284
- | `src/mysql/migration-generator.js` | `diffViewSnapshots()`, view migration generation |
285
-
286
- ### Key Design Decisions
287
-
288
- 1. **View does NOT extend Model** — conceptually separate; shared behavior is minimal
289
- 2. **Driver-agnostic API** — No SQL in view definitions; MySQL driver generates SQL automatically
290
- 3. **Aggregate helpers follow the transform pattern** — Each knows both JS computation and MySQL mapping
291
- 4. **Resolve map mirrors Serializer.map** — String paths or function resolvers
292
- 5. **View schemas are separate** — `introspectViews()` is separate from `introspectModels()`
package/src/aggregates.js DELETED
@@ -1,93 +0,0 @@
1
- export class AggregateProperty {
2
- constructor(aggregateType, relationship, field) {
3
- this.aggregateType = aggregateType;
4
- this.relationship = relationship;
5
- this.field = field;
6
- this.mysqlFunction = aggregateType.toUpperCase();
7
- this.resultType = aggregateType === 'avg' ? 'float' : 'number';
8
- }
9
-
10
- compute(relatedRecords) {
11
- if (!relatedRecords || !Array.isArray(relatedRecords) || relatedRecords.length === 0) {
12
- if (this.aggregateType === 'min' || this.aggregateType === 'max') return null;
13
- return 0;
14
- }
15
-
16
- switch (this.aggregateType) {
17
- case 'count':
18
- return relatedRecords.length;
19
-
20
- case 'sum':
21
- return relatedRecords.reduce((acc, record) => {
22
- const val = parseFloat(record?.__data?.[this.field] ?? record?.[this.field]);
23
- return acc + (isNaN(val) ? 0 : val);
24
- }, 0);
25
-
26
- case 'avg': {
27
- let sum = 0;
28
- let count = 0;
29
- for (const record of relatedRecords) {
30
- const val = parseFloat(record?.__data?.[this.field] ?? record?.[this.field]);
31
- if (!isNaN(val)) {
32
- sum += val;
33
- count++;
34
- }
35
- }
36
- return count === 0 ? 0 : sum / count;
37
- }
38
-
39
- case 'min': {
40
- let min = null;
41
- for (const record of relatedRecords) {
42
- const val = parseFloat(record?.__data?.[this.field] ?? record?.[this.field]);
43
- if (!isNaN(val) && (min === null || val < min)) min = val;
44
- }
45
- return min;
46
- }
47
-
48
- case 'max': {
49
- let max = null;
50
- for (const record of relatedRecords) {
51
- const val = parseFloat(record?.__data?.[this.field] ?? record?.[this.field]);
52
- if (!isNaN(val) && (max === null || val > max)) max = val;
53
- }
54
- return max;
55
- }
56
-
57
- default:
58
- return null;
59
- }
60
- }
61
- }
62
-
63
- export function count(relationship) {
64
- return new AggregateProperty('count', relationship);
65
- }
66
-
67
- export function avg(relationshipOrField, field) {
68
- if (field !== undefined) {
69
- return new AggregateProperty('avg', relationshipOrField, field);
70
- }
71
- return new AggregateProperty('avg', undefined, relationshipOrField);
72
- }
73
-
74
- export function sum(relationshipOrField, field) {
75
- if (field !== undefined) {
76
- return new AggregateProperty('sum', relationshipOrField, field);
77
- }
78
- return new AggregateProperty('sum', undefined, relationshipOrField);
79
- }
80
-
81
- export function min(relationshipOrField, field) {
82
- if (field !== undefined) {
83
- return new AggregateProperty('min', relationshipOrField, field);
84
- }
85
- return new AggregateProperty('min', undefined, relationshipOrField);
86
- }
87
-
88
- export function max(relationshipOrField, field) {
89
- if (field !== undefined) {
90
- return new AggregateProperty('max', relationshipOrField, field);
91
- }
92
- return new AggregateProperty('max', undefined, relationshipOrField);
93
- }