objection 3.4.1 → 3.5.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.
@@ -208,7 +208,11 @@ class GraphInsertAction extends GraphAction {
208
208
  return Promise.all(
209
209
  nodes.map((node) => {
210
210
  if (node.parentEdge) {
211
- return node.parentEdge.relation.beforeInsert(node.obj, parentBuilder.context());
211
+ return node.parentEdge.relation.beforeInsert(
212
+ node.obj,
213
+ parentBuilder.context(),
214
+ node.parentNode.obj,
215
+ );
212
216
  } else {
213
217
  return null;
214
218
  }
@@ -63,7 +63,12 @@ class InsertGraphOperation extends DelegateOperation {
63
63
  if (this.relation) {
64
64
  // We still need to call the relation before insert hook if the the
65
65
  // delegate operation is a RelationInsertOperation.
66
- return this.relation.executeBeforeInsert(this.models, builder.context(), result);
66
+ return this.relation.executeBeforeInsert(
67
+ this.models,
68
+ builder.context(),
69
+ result,
70
+ this.delegate.ownerModel,
71
+ );
67
72
  } else {
68
73
  return result;
69
74
  }
@@ -219,8 +219,12 @@ class Relation {
219
219
  });
220
220
  }
221
221
 
222
- executeBeforeInsert(models, queryContext, result) {
223
- return mapAfterAllReturn(models, (model) => this.beforeInsert(model, queryContext), result);
222
+ executeBeforeInsert(models, queryContext, result, owner) {
223
+ return mapAfterAllReturn(
224
+ models,
225
+ (model) => this.beforeInsert(model, queryContext, owner),
226
+ result,
227
+ );
224
228
  }
225
229
 
226
230
  createError(message) {
@@ -11,9 +11,21 @@ class RelationInsertOperation extends InsertOperation {
11
11
  this.assignResultToOwner = true;
12
12
  }
13
13
 
14
+ get ownerModel() {
15
+ // The owner model passed to the relation's `beforeInsert` hook. Only known
16
+ // if the query was started from a single model instance.
17
+ const { owner } = this;
18
+ return owner && owner.isModels && owner.modelArray.length === 1 ? owner.model : undefined;
19
+ }
20
+
14
21
  async onBefore2(builder, result) {
15
22
  const queryContext = builder.context();
16
- result = await this.relation.executeBeforeInsert(this.models, queryContext, result);
23
+ result = await this.relation.executeBeforeInsert(
24
+ this.models,
25
+ queryContext,
26
+ result,
27
+ this.ownerModel,
28
+ );
17
29
  return super.onBefore2(builder, result);
18
30
  }
19
31
 
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- const { isObject } = require('./objectUtils');
3
+ const { isObject, isPlainObject } = require('./objectUtils');
4
4
 
5
5
  // Super fast memoize for single argument functions.
6
6
  function memoize(func) {
@@ -149,8 +149,9 @@ function mapLastPart(mapper, separator) {
149
149
  }
150
150
 
151
151
  // Returns a function that takes an object as an input and maps the object's keys
152
- // using `mapper`. If the input is not an object, the input is returned unchanged.
153
- function keyMapper(mapper) {
152
+ // using `mapper`, and its values using the optional `valueMapper`. If the input
153
+ // is not an object, the input is returned unchanged.
154
+ function keyMapper(mapper, valueMapper) {
154
155
  return (obj) => {
155
156
  if (!isObject(obj) || Array.isArray(obj)) {
156
157
  return obj;
@@ -161,7 +162,7 @@ function keyMapper(mapper) {
161
162
 
162
163
  for (let i = 0, l = keys.length; i < l; ++i) {
163
164
  const key = keys[i];
164
- out[mapper(key)] = obj[key];
165
+ out[mapper(key)] = valueMapper ? valueMapper(obj[key]) : obj[key];
165
166
  }
166
167
 
167
168
  return out;
@@ -189,10 +190,16 @@ function snakeCaseMappers(opt = {}) {
189
190
  };
190
191
  }
191
192
 
192
- function knexIdentifierMappers({ parse, format, idSeparator = ':' } = {}) {
193
+ function knexIdentifierMappers({ parse, format, idSeparator = ':', mapNestedKeys = false } = {}) {
193
194
  const formatId = memoize(mapLastPart(format, idSeparator));
194
195
  const parseId = memoize(mapLastPart(parse, idSeparator));
195
196
  const parseKeys = keyMapper(parseId);
197
+ // With `mapNestedKeys`, also map the keys of plain objects one level down, as
198
+ // in the rows knex returns with its `nestTables: true` option on MySQL:
199
+ // `{ tableName: { columnName: value } }`.
200
+ const parseRow = mapNestedKeys
201
+ ? keyMapper(parseId, (value) => (isPlainObject(value) ? parseKeys(value) : value))
202
+ : parseKeys;
196
203
 
197
204
  return {
198
205
  wrapIdentifier(identifier, origWrap) {
@@ -204,12 +211,12 @@ function knexIdentifierMappers({ parse, format, idSeparator = ':' } = {}) {
204
211
  const output = new Array(result.length);
205
212
 
206
213
  for (let i = 0, l = result.length; i < l; ++i) {
207
- output[i] = parseKeys(result[i]);
214
+ output[i] = parseRow(result[i]);
208
215
  }
209
216
 
210
217
  return output;
211
218
  } else {
212
- return parseKeys(result);
219
+ return parseRow(result);
213
220
  }
214
221
  },
215
222
  };
@@ -219,10 +226,11 @@ function knexSnakeCaseMappers(opt = {}) {
219
226
  return knexIdentifierMappers({
220
227
  parse: (str) => camelCase(str, opt),
221
228
  format: (str) => snakeCase(str, opt),
229
+ mapNestedKeys: opt.mapNestedKeys,
222
230
  });
223
231
  }
224
232
 
225
- function knexIdentifierMapping(colToProp) {
233
+ function knexIdentifierMapping(colToProp, { mapNestedKeys } = {}) {
226
234
  const propToCol = Object.keys(colToProp).reduce((propToCol, column) => {
227
235
  propToCol[colToProp[column]] = column;
228
236
  return propToCol;
@@ -231,6 +239,7 @@ function knexIdentifierMapping(colToProp) {
231
239
  return knexIdentifierMappers({
232
240
  parse: (column) => colToProp[column] || column,
233
241
  format: (prop) => propToCol[prop] || prop,
242
+ mapNestedKeys,
234
243
  });
235
244
  }
236
245
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "objection",
3
- "version": "3.4.1",
3
+ "version": "3.5.0",
4
4
  "description": "An SQL-friendly ORM for Node.js",
5
5
  "main": "lib/objection.js",
6
6
  "license": "MIT",
@@ -19,6 +19,11 @@ import { Knex } from 'knex';
19
19
  // Export the entire Objection namespace.
20
20
  export = Objection;
21
21
 
22
+ // Phantom brand of the relation types, used by `TypedRelationMappings`.
23
+ declare const relationKind: unique symbol;
24
+ // Phantom brand of `Generated` properties.
25
+ declare const generated: unique symbol;
26
+
22
27
  declare namespace Objection {
23
28
  const raw: RawFunction;
24
29
  const val: ValueFunction;
@@ -462,6 +467,65 @@ declare namespace Objection {
462
467
  : Expression<F>
463
468
  : Expression<F>;
464
469
 
470
+ /**
471
+ * Marks a model property whose value the database generates, like an
472
+ * auto-incremented id, a timestamp or a column with a default value. It
473
+ * reads as T and accepts T, but `Insertable` and `InsertableGraph` treat
474
+ * the property as optional:
475
+ *
476
+ * id!: Generated<number>;
477
+ */
478
+ export type Generated<T> = T extends null | undefined ? T : T & GeneratedBrand;
479
+
480
+ interface GeneratedBrand {
481
+ readonly [generated]?: true;
482
+ }
483
+
484
+ /**
485
+ * Insert keys are optional for optional, nullable and generated properties.
486
+ */
487
+ type OptionalInsertPropertyNames<M> = {
488
+ [K in keyof M]-?: {} extends Pick<M, K>
489
+ ? K
490
+ : null extends M[K]
491
+ ? K
492
+ : typeof generated extends keyof NonNullable<M[K]>
493
+ ? K
494
+ : never;
495
+ }[keyof M];
496
+
497
+ type InsertablePropertyNames<M> = Exclude<DataPropertyNames<M>, RelationPropertyNames<M>>;
498
+
499
+ /**
500
+ * The data to insert a model M with `insert()`. Unlike `PartialModelObject`,
501
+ * all properties are required except optional, nullable and `Generated`
502
+ * ones. Relation properties are left out.
503
+ */
504
+ export type Insertable<M extends Model> = {
505
+ [K in Exclude<InsertablePropertyNames<M>, OptionalInsertPropertyNames<M>>]: Expression<M[K]>;
506
+ } & {
507
+ [K in Extract<InsertablePropertyNames<M>, OptionalInsertPropertyNames<M>>]?: Expression<M[K]>;
508
+ };
509
+
510
+ /**
511
+ * Like `Insertable`, but for `insertGraph()`: relation properties are
512
+ * optional and hold the insertable graphs of the related models, or
513
+ * references to existing ones through `#dbRef` or `#ref`.
514
+ */
515
+ export type InsertableGraph<M extends Model> = Insertable<M> &
516
+ Omit<GraphParameters, '#dbRef' | '#ref'> & {
517
+ [K in RelationPropertyNames<M>]?: InsertableGraphField<M[K]>;
518
+ };
519
+
520
+ type InsertableGraphReference = { '#dbRef': MaybeCompositeId } | { '#ref': string };
521
+
522
+ type InsertableGraphField<F> =
523
+ NonNullable<F> extends (infer I extends Model)[]
524
+ ? (InsertableGraph<I> | InsertableGraphReference)[]
525
+ : NonNullable<F> extends infer I extends Model
526
+ ? InsertableGraph<I> | InsertableGraphReference | Extract<F, null>
527
+ : never;
528
+
465
529
  /**
466
530
  * Extracts the property names (excluding relations) of a model class.
467
531
  */
@@ -1488,6 +1552,11 @@ declare namespace Objection {
1488
1552
  model: M,
1489
1553
  context: QueryContext,
1490
1554
  ) => Promise<void> | void;
1555
+ type RelationMappingBeforeInsertHook<M extends Model> = (
1556
+ model: M,
1557
+ context: QueryContext,
1558
+ owner?: Model,
1559
+ ) => Promise<void> | void;
1491
1560
  type StringOrReferenceBuilder = string | ReferenceBuilder;
1492
1561
  type RelationMappingColumnRef = StringOrReferenceBuilder | StringOrReferenceBuilder[];
1493
1562
 
@@ -1497,7 +1566,7 @@ declare namespace Objection {
1497
1566
  join: RelationJoin;
1498
1567
  modify?: Modifier<QueryBuilderType<M>>;
1499
1568
  filter?: Modifier<QueryBuilderType<M>>;
1500
- beforeInsert?: RelationMappingHook<M>;
1569
+ beforeInsert?: RelationMappingBeforeInsertHook<M>;
1501
1570
  }
1502
1571
 
1503
1572
  export interface RelationJoin {
@@ -1518,6 +1587,67 @@ declare namespace Objection {
1518
1587
 
1519
1588
  export interface RelationType extends Constructor<Relation> {}
1520
1589
 
1590
+ // The relation types are branded so that `TypedRelationMappings` can tell
1591
+ // them apart. The brand is optional, so any `RelationType` is assignable.
1592
+ export interface BelongsToOneRelationType extends RelationType {
1593
+ readonly [relationKind]?: 'BelongsToOne';
1594
+ }
1595
+ export interface HasOneRelationType extends RelationType {
1596
+ readonly [relationKind]?: 'HasOne';
1597
+ }
1598
+ export interface HasManyRelationType extends RelationType {
1599
+ readonly [relationKind]?: 'HasMany';
1600
+ }
1601
+ export interface ManyToManyRelationType extends RelationType {
1602
+ readonly [relationKind]?: 'ManyToMany';
1603
+ }
1604
+ export interface HasOneThroughRelationType extends RelationType {
1605
+ readonly [relationKind]?: 'HasOneThrough';
1606
+ }
1607
+
1608
+ /**
1609
+ * Names of the properties of M that hold related models.
1610
+ */
1611
+ type RelationPropertyNames<M> = {
1612
+ [K in keyof M]-?: NonNullable<M[K]> extends Model | Model[] ? K : never;
1613
+ }[keyof M];
1614
+
1615
+ type TypedModelClassSpecifier<M extends Model> =
1616
+ string | ModelConstructor<M> | (() => ModelConstructor<M>);
1617
+
1618
+ /**
1619
+ * A `RelationMapping` for related models of type M with relation type R.
1620
+ */
1621
+ export interface TypedRelationMapping<
1622
+ M extends Model,
1623
+ R extends RelationType = RelationType,
1624
+ > extends RelationMapping<M> {
1625
+ relation: R;
1626
+ modelClass: TypedModelClassSpecifier<M>;
1627
+ }
1628
+
1629
+ type TypedRelationMappingFor<T> =
1630
+ NonNullable<T> extends (infer I extends Model)[]
1631
+ ? TypedRelationMapping<I, HasManyRelationType | ManyToManyRelationType>
1632
+ : NonNullable<T> extends infer I extends Model
1633
+ ? TypedRelationMapping<
1634
+ I,
1635
+ BelongsToOneRelationType | HasOneRelationType | HasOneThroughRelationType
1636
+ >
1637
+ : never;
1638
+
1639
+ /**
1640
+ * Relation mappings checked against the relation properties of model M.
1641
+ * Use it with `satisfies`, so the inferred type of the mappings is kept:
1642
+ *
1643
+ * static relationMappings = {
1644
+ * pets: { ... },
1645
+ * } satisfies TypedRelationMappings<Person>;
1646
+ */
1647
+ export type TypedRelationMappings<M extends Model> = [RelationPropertyNames<M>] extends [never]
1648
+ ? Record<string, never>
1649
+ : { [K in RelationPropertyNames<M>]?: TypedRelationMappingFor<M[K]> };
1650
+
1521
1651
  export interface Relation {
1522
1652
  name: string;
1523
1653
  ownerModelClass: typeof Model;
@@ -1528,6 +1658,7 @@ declare namespace Objection {
1528
1658
  joinTable: string;
1529
1659
  joinTableOwnerProp: RelationProperty;
1530
1660
  joinTableRelatedProp: RelationProperty;
1661
+ isOneToOne(): boolean;
1531
1662
  }
1532
1663
 
1533
1664
  export interface RelationProperty {
@@ -1598,6 +1729,22 @@ declare namespace Objection {
1598
1729
  * Only used by `snakeCaseMappers`.
1599
1730
  */
1600
1731
  preserveJsonKeys?: boolean;
1732
+ /**
1733
+ * Also convert the keys of plain objects one level down in the results,
1734
+ * e.g. the rows of knex's `nestTables: true` option on MySQL. Also applies
1735
+ * to JSON columns parsed by the driver.
1736
+ * Only used by `knexSnakeCaseMappers`.
1737
+ */
1738
+ mapNestedKeys?: boolean;
1739
+ }
1740
+
1741
+ export interface KnexIdentifierMappingOptions {
1742
+ /**
1743
+ * Also convert the keys of plain objects one level down in the results,
1744
+ * e.g. the rows of knex's `nestTables: true` option on MySQL. Also applies
1745
+ * to JSON columns parsed by the driver.
1746
+ */
1747
+ mapNestedKeys?: boolean;
1601
1748
  }
1602
1749
 
1603
1750
  export interface ColumnNameMappers {
@@ -1619,7 +1766,7 @@ declare namespace Objection {
1619
1766
  }
1620
1767
 
1621
1768
  export interface KnexIdentifierMappingFactory {
1622
- (colToProp: Record<string, string>): KnexMappers;
1769
+ (colToProp: Record<string, string>, options?: KnexIdentifierMappingOptions): KnexMappers;
1623
1770
  }
1624
1771
 
1625
1772
  export type ValidationErrorType =
@@ -1732,11 +1879,11 @@ declare namespace Objection {
1732
1879
  ref: ReferenceFunction;
1733
1880
  fn: FunctionFunction;
1734
1881
 
1735
- BelongsToOneRelation: RelationType;
1736
- HasOneRelation: RelationType;
1737
- HasManyRelation: RelationType;
1738
- ManyToManyRelation: RelationType;
1739
- HasOneThroughRelation: RelationType;
1882
+ BelongsToOneRelation: BelongsToOneRelationType;
1883
+ HasOneRelation: HasOneRelationType;
1884
+ HasManyRelation: HasManyRelationType;
1885
+ ManyToManyRelation: ManyToManyRelationType;
1886
+ HasOneThroughRelation: HasOneThroughRelationType;
1740
1887
 
1741
1888
  defaultGraphOptions?: GraphOptions;
1742
1889
 
@@ -1843,11 +1990,11 @@ declare namespace Objection {
1843
1990
  static ref: ReferenceFunction;
1844
1991
  static fn: FunctionFunction;
1845
1992
 
1846
- static BelongsToOneRelation: RelationType;
1847
- static HasOneRelation: RelationType;
1848
- static HasManyRelation: RelationType;
1849
- static ManyToManyRelation: RelationType;
1850
- static HasOneThroughRelation: RelationType;
1993
+ static BelongsToOneRelation: BelongsToOneRelationType;
1994
+ static HasOneRelation: HasOneRelationType;
1995
+ static HasManyRelation: HasManyRelationType;
1996
+ static ManyToManyRelation: ManyToManyRelationType;
1997
+ static HasOneThroughRelation: HasOneThroughRelationType;
1851
1998
 
1852
1999
  static defaultGraphOptions?: GraphOptions;
1853
2000