RelationProperty.js 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. const { asArray, isObject, uniqBy, get, set } = require('../utils/objectUtils');
  2. const { ref: createRef } = require('../queryBuilder/ReferenceBuilder');
  3. const { raw: createRaw } = require('../queryBuilder/RawBuilder');
  4. const { propToStr, PROP_KEY_PREFIX } = require('../model/modelValues');
  5. class ModelNotFoundError extends Error {
  6. constructor(tableName) {
  7. super();
  8. this.name = this.constructor.name;
  9. this.tableName = tableName;
  10. }
  11. }
  12. class InvalidReferenceError extends Error {
  13. constructor() {
  14. super();
  15. this.name = this.constructor.name;
  16. }
  17. }
  18. // A pair of these define how two tables are related to each other.
  19. // Both the owner and the related table have one of these.
  20. //
  21. // A relation property can be a single column, an array of columns
  22. // (composite key) a json column reference, an array of json column
  23. // references or any combination of the above.
  24. class RelationProperty {
  25. // references must be a reference string like `Table.column:maybe.some.json[1].path`.
  26. // or an array of such references (composite key).
  27. //
  28. // modelClassResolver must be a function that takes a table name
  29. // and returns a model class.
  30. constructor(references, modelClassResolver) {
  31. const refs = createRefs(asArray(references));
  32. const paths = createPaths(refs, modelClassResolver);
  33. const modelClass = resolveModelClass(paths);
  34. this._refs = refs;
  35. this._modelClass = modelClass;
  36. this._props = paths.map(it => it.path[0]);
  37. this._cols = refs.map(it => it.column);
  38. this._propGetters = paths.map(it => createGetter(it.path));
  39. this._propSetters = paths.map(it => createSetter(it.path));
  40. }
  41. static get ModelNotFoundError() {
  42. return ModelNotFoundError;
  43. }
  44. static get InvalidReferenceError() {
  45. return InvalidReferenceError;
  46. }
  47. // The number of columns.
  48. get size() {
  49. return this._refs.length;
  50. }
  51. // The model class that owns the property.
  52. get modelClass() {
  53. return this._modelClass;
  54. }
  55. // An array of property names. Contains multiple values in case of composite key.
  56. // This may be different from `cols` if the model class has some kind of conversion
  57. // between database and "external" formats, for example a snake_case to camelCase
  58. // conversion.
  59. get props() {
  60. return this._props;
  61. }
  62. // An array of column names. Contains multiple values in case of composite key.
  63. // This may be different from `props` if the model class has some kind of conversion
  64. // between database and "external" formats, for example a snake_case to camelCase
  65. // conversion.
  66. get cols() {
  67. return this._cols;
  68. }
  69. // Creates a concatenated string from the property values of the given object.
  70. propKey(obj) {
  71. const size = this.size;
  72. var key = PROP_KEY_PREFIX;
  73. for (let i = 0; i < size; ++i) {
  74. key += propToStr(this.getProp(obj, i));
  75. if (i !== size - 1) {
  76. key += ',';
  77. }
  78. }
  79. return key;
  80. }
  81. // Returns the property values of the given object as an array.
  82. getProps(obj) {
  83. const size = this.size;
  84. const props = new Array(size);
  85. for (let i = 0; i < size; ++i) {
  86. props[i] = this.getProp(obj, i);
  87. }
  88. return props;
  89. }
  90. // Returns the index:th property value of the given object.
  91. getProp(obj, index) {
  92. return this._propGetters[index](obj);
  93. }
  94. // Sets the index:th property value of the given object.
  95. setProp(obj, index, value) {
  96. return this._propSetters[index](obj, value);
  97. }
  98. // Returns the index:th column name with table reference. Something like
  99. // 'Table.someColumn'.
  100. fullCol(builder, index) {
  101. const table = builder.tableRefFor(this.modelClass);
  102. return `${table}.${this.cols[index]}`;
  103. }
  104. // Returns an instance of ReferenceBuilder that points to the index:th
  105. // value of a row.
  106. ref(builder, index) {
  107. const table = builder.tableRefFor(this.modelClass);
  108. return this._refs[index].clone().table(table);
  109. }
  110. // Returns an array of reference builder. `ref(builder, i)` for each i.
  111. refs(builder) {
  112. const refs = new Array(this.size);
  113. for (let i = 0, l = refs.length; i < l; ++i) {
  114. refs[i] = this.ref(builder, i);
  115. }
  116. return refs;
  117. }
  118. // Appends an update operation for the index:th column into `patch` object.
  119. patch(patch, index, value) {
  120. const ref = this._refs[index];
  121. if (ref.isPlainColumnRef) {
  122. patch[this._cols[index]] = value;
  123. } else {
  124. // Objection `patch`, `update` etc. methods understand field expressions.
  125. patch[ref.expression] = value;
  126. }
  127. }
  128. // String representation of this property's index:th column for logging.
  129. propDescription(index) {
  130. return this._refs[index].expression;
  131. }
  132. }
  133. function createRefs(refs) {
  134. try {
  135. return refs.map(it => {
  136. if (!isObject(it) || !it.isObjectionReferenceBuilder) {
  137. return createRef(it);
  138. } else {
  139. return it;
  140. }
  141. });
  142. } catch (err) {
  143. throw new InvalidReferenceError();
  144. }
  145. }
  146. function createPaths(refs, modelClassResolver) {
  147. return refs.map(ref => {
  148. if (!ref.tableName) {
  149. throw new InvalidReferenceError();
  150. }
  151. const modelClass = modelClassResolver(ref.tableName);
  152. if (!modelClass) {
  153. throw new ModelNotFoundError(ref.tableName);
  154. }
  155. const prop = modelClass.columnNameToPropertyName(ref.column);
  156. const jsonPath = ref.reference.access.map(it => it.ref);
  157. return {
  158. path: [prop].concat(jsonPath),
  159. modelClass
  160. };
  161. });
  162. }
  163. function resolveModelClass(paths) {
  164. const modelClasses = paths.map(it => it.modelClass);
  165. const uniqueModelClasses = uniqBy(modelClasses);
  166. if (uniqueModelClasses.length !== 1) {
  167. throw new InvalidReferenceError();
  168. }
  169. return modelClasses[0];
  170. }
  171. function createGetter(path) {
  172. if (path.length === 1) {
  173. const prop = path[0];
  174. return obj => obj[prop];
  175. } else {
  176. return obj => get(obj, path);
  177. }
  178. }
  179. function createSetter(path) {
  180. if (path.length === 1) {
  181. const prop = path[0];
  182. return (obj, value) => (obj[prop] = value);
  183. } else {
  184. return (obj, value) => set(obj, path, value);
  185. }
  186. }
  187. module.exports = RelationProperty;