forest-express-sequelize 7.12.2 → 7.12.3

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/.releaserc.js CHANGED
@@ -1,4 +1,5 @@
1
1
  module.exports = {
2
+ branches: ['main', '+([0-9])?(.{+([0-9]),x}).x'],
2
3
  plugins: [
3
4
  [
4
5
  '@semantic-release/commit-analyzer', {
package/CHANGELOG.md CHANGED
@@ -1,3 +1,12 @@
1
+ ## [7.12.3](https://github.com/ForestAdmin/forest-express-sequelize/compare/v7.12.2...v7.12.3) (2021-10-20)
2
+
3
+
4
+ ### Bug Fixes
5
+
6
+ * **retrocompatibility:** handle sequelize includables on smart field search ([#850](https://github.com/ForestAdmin/forest-express-sequelize/issues/850)) ([3c1a677](https://github.com/ForestAdmin/forest-express-sequelize/commit/3c1a6770a5f77ab2575e626a32d5c483089691ca))
7
+ * **smart-field:** smart field should allow to request all fields ([#861](https://github.com/ForestAdmin/forest-express-sequelize/issues/861)) ([80c4fcc](https://github.com/ForestAdmin/forest-express-sequelize/commit/80c4fcc75544cbc8e9e3c1132452edbf64f61713))
8
+ * allow async search on smart field ([#860](https://github.com/ForestAdmin/forest-express-sequelize/issues/860)) ([bdf9edd](https://github.com/ForestAdmin/forest-express-sequelize/commit/bdf9edd6b75dddb0da9cb2005f775ad3bbb16981))
9
+
1
10
  ## [7.12.2](https://github.com/ForestAdmin/forest-express-sequelize/compare/v7.12.1...v7.12.2) (2021-07-06)
2
11
 
3
12
 
@@ -211,7 +211,7 @@ class QueryOptions {
211
211
  const {
212
212
  conditions,
213
213
  include
214
- } = helper.performWithSmartFields(this._options.tableAlias);
214
+ } = await helper.performWithSmartFields(this._options.tableAlias);
215
215
 
216
216
  if (conditions) {
217
217
  this._where.push(conditions);
@@ -220,7 +220,11 @@ class QueryOptions {
220
220
  }
221
221
 
222
222
  if (include) {
223
- this._customerIncludes.push(...include);
223
+ if (Array.isArray(include)) {
224
+ this._customerIncludes.push(...include);
225
+ } else {
226
+ this._customerIncludes.push(include);
227
+ }
224
228
  }
225
229
 
226
230
  return helper.getFieldsSearched();
@@ -37,6 +37,21 @@ function extractRequestedFieldsForAssociation(associationName, requestedFields,
37
37
  return `${associationName}.${fieldName}`;
38
38
  });
39
39
  }
40
+
41
+ function extractRequestedSmartField(requestedFields, schema) {
42
+ const schemaSmartFields = schema.fields.filter(function ({
43
+ isVirtual
44
+ }) {
45
+ return isVirtual;
46
+ });
47
+ return requestedFields[schema.name].split(',').filter(function (fieldName) {
48
+ return schemaSmartFields.some(function ({
49
+ field
50
+ }) {
51
+ return field === fieldName;
52
+ });
53
+ });
54
+ }
40
55
  /**
41
56
  * @param {Record<string, string>} requestedFields
42
57
  * @param {*} modelOrAssociation
@@ -65,7 +80,8 @@ function extractRequestedFields(requestedFields, modelOrAssociation, schemas) {
65
80
  const modelFields = requestedFields[modelOrAssociation.name].split(',').filter(function (fieldName) {
66
81
  return !requestedFields[fieldName];
67
82
  });
68
- return Array.from(new Set([...primaryKeyArray, ...modelFields, ...allAssociationFields]));
83
+ const smartFields = extractRequestedSmartField(requestedFields, schemas[modelOrAssociation.name]);
84
+ return Array.from(new Set([...primaryKeyArray, ...modelFields, ...smartFields, ...allAssociationFields]));
69
85
  }
70
86
 
71
87
  module.exports = extractRequestedFields;
@@ -2,6 +2,8 @@
2
2
 
3
3
  require("core-js/modules/es.array.iterator");
4
4
 
5
+ require("core-js/modules/es.promise");
6
+
5
7
  const _ = require('lodash');
6
8
 
7
9
  const Interface = require('forest-express');
@@ -98,7 +100,7 @@ function SearchBuilder(model, opts, params, fieldNamesRequested) {
98
100
  return hasExtendedConditions;
99
101
  };
100
102
 
101
- this.performWithSmartFields = function (associationName) {
103
+ this.performWithSmartFields = async function (associationName) {
102
104
  // Retrocompatibility: customers which implement search on smart fields are expected to
103
105
  // inject their conditions at .where[Op.and][0][Op.or].push(searchCondition)
104
106
  // https://docs.forestadmin.com/documentation/reference-guide/fields/create-and-manage-smart-fields
@@ -108,15 +110,19 @@ function SearchBuilder(model, opts, params, fieldNamesRequested) {
108
110
  [OPERATORS.AND]: [_this.perform(associationName)]
109
111
  }
110
112
  };
111
- schema.fields.filter(function (field) {
113
+ const fieldsWithSearch = schema.fields.filter(function (field) {
112
114
  return field.search;
113
- }).forEach(function (field) {
115
+ });
116
+ await Promise.all(fieldsWithSearch.map(async function (field) {
114
117
  try {
115
- field.search(query, params.search);
118
+ await field.search(query, params.search);
116
119
  } catch (error) {
117
- Interface.logger.error(`Cannot search properly on Smart Field ${field.field}`, error);
120
+ const errorMessage = `Cannot search properly on Smart Field ${field.field}`;
121
+ Interface.logger.error(errorMessage, error);
118
122
  }
119
- });
123
+
124
+ return Promise.resolve();
125
+ }));
120
126
  return {
121
127
  include: query.include,
122
128
  conditions: query.where[OPERATORS.AND][0][OPERATORS.OR].length ? query.where[OPERATORS.AND][0] : null
@@ -12,8 +12,6 @@ var _objectTools = _interopRequireDefault(require("./object-tools"));
12
12
 
13
13
  var _operators = _interopRequireDefault(require("./operators"));
14
14
 
15
- var _orm = require("./orm");
16
-
17
15
  var _query = _interopRequireDefault(require("./query"));
18
16
 
19
17
  function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
@@ -101,9 +99,13 @@ function normalizeInclude(model, include) {
101
99
 
102
100
 
103
101
  if (include.include) {
104
- include.include = include.include.map(function (childInclude) {
105
- return normalizeInclude(include.model, childInclude);
106
- });
102
+ if (Array.isArray(include.include)) {
103
+ include.include = include.include.map(function (childInclude) {
104
+ return normalizeInclude(include.model, childInclude);
105
+ });
106
+ } else {
107
+ include.include = [normalizeInclude(include.model, include.include)];
108
+ }
107
109
  }
108
110
 
109
111
  return include;
@@ -160,15 +162,10 @@ exports.postProcess = function (model, rawOptions) {
160
162
  Sequelize: model.sequelize.constructor
161
163
  });
162
164
 
163
- if ((0, _orm.isVersionLessThan)(model.sequelize.constructor, '5.0.0')) {
164
- options.include = options.include.map(function (include) {
165
- return normalizeInclude(model, include);
166
- });
167
- bubbleWheresInPlace(operators, options);
168
- removeDuplicateAssociations(model, options.include);
169
- } else {
170
- bubbleWheresInPlace(operators, options);
171
- }
172
-
165
+ options.include = options.include.map(function (include) {
166
+ return normalizeInclude(model, include);
167
+ });
168
+ bubbleWheresInPlace(operators, options);
169
+ removeDuplicateAssociations(model, options.include);
173
170
  return options;
174
171
  };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "forest-express-sequelize",
3
3
  "description": "Official Express/Sequelize Liana for Forest",
4
- "version": "7.12.2",
4
+ "version": "7.12.3",
5
5
  "author": "Sandro Munda <sandro@munda.me>",
6
6
  "contributors": [
7
7
  "Arnaud Besnier <arnaudibesnier@gmail.com>",
@@ -3,21 +3,32 @@ import Interface from 'forest-express';
3
3
  import QueryOptions from '../../src/services/query-options';
4
4
 
5
5
  describe('services > query-options', () => {
6
- describe('order', () => {
7
- const buildModelMock = (dialect) => {
8
- // Sequelize is created here without connection to a database
9
- const sequelize = new Sequelize({ dialect });
6
+ const resetSchema = () => {
7
+ Interface.Schemas = {
8
+ schemas: {
9
+ actor: {
10
+ idField: 'id',
11
+ fields: [{ field: 'smartField' }, { field: 'secondSmartField' }],
12
+ },
13
+ },
14
+ };
15
+ };
10
16
 
11
- const modelActor = sequelize.define('actor', {});
12
- const modelMovie = sequelize.define('movie', {});
17
+ const buildModelMock = (dialect) => {
18
+ // Sequelize is created here without connection to a database
19
+ const sequelize = new Sequelize({ dialect });
13
20
 
14
- modelActor.belongsTo(modelMovie);
21
+ const modelActor = sequelize.define('actor', {});
22
+ const modelMovie = sequelize.define('movie', {});
15
23
 
16
- Interface.Schemas = { schemas: { actor: { idField: 'id' } } };
24
+ resetSchema();
17
25
 
18
- return modelActor;
19
- };
26
+ modelActor.belongsTo(modelMovie);
20
27
 
28
+ return modelActor;
29
+ };
30
+
31
+ describe('order', () => {
21
32
  describe('with mssql', () => {
22
33
  const model = buildModelMock('mssql');
23
34
 
@@ -56,4 +67,80 @@ describe('services > query-options', () => {
56
67
  });
57
68
  });
58
69
  });
70
+
71
+ describe('search', () => {
72
+ const model = buildModelMock('postgres');
73
+
74
+ describe('when search on smart field is async', () => {
75
+ describe('when promise reject', () => {
76
+ it('should display an error message', async () => {
77
+ expect.assertions(1);
78
+
79
+ const loggerErrorSpy = jest.spyOn(Interface.logger, 'error');
80
+
81
+ const errorThrown = new Error('unexpected error');
82
+ Interface.Schemas.schemas.actor.fields[0].search = async () =>
83
+ Promise.reject(errorThrown);
84
+
85
+ const options = new QueryOptions(model);
86
+ await options.search('search string', null);
87
+ expect(loggerErrorSpy).toHaveBeenCalledWith('Cannot search properly on Smart Field smartField', errorThrown);
88
+
89
+ loggerErrorSpy.mockClear();
90
+ resetSchema();
91
+ });
92
+ });
93
+
94
+ it('should add the search includes', async () => {
95
+ expect.assertions(1);
96
+
97
+ Interface.Schemas.schemas.actor.fields[0].search = async (query) => {
98
+ await Promise.resolve();
99
+ query.include.push('movie');
100
+ };
101
+ Interface.Schemas.schemas.actor.fields[1].search = async (query) => {
102
+ await Promise.resolve();
103
+ query.include.push('toto');
104
+ };
105
+
106
+ const options = new QueryOptions(model);
107
+ await options.search('search string', null);
108
+ expect(options._customerIncludes).toStrictEqual(['movie', 'toto']);
109
+
110
+ resetSchema();
111
+ });
112
+ });
113
+
114
+ describe('when search on smart field throw an error', () => {
115
+ it('should display an error message', async () => {
116
+ expect.assertions(1);
117
+
118
+ const loggerErrorSpy = jest.spyOn(Interface.logger, 'error');
119
+
120
+ const errorThrown = new Error('unexpected error');
121
+ Interface.Schemas.schemas.actor.fields[0].search = () => { throw errorThrown; };
122
+
123
+ const options = new QueryOptions(model);
124
+ await options.search('search string', null);
125
+ expect(loggerErrorSpy).toHaveBeenCalledWith('Cannot search properly on Smart Field smartField', errorThrown);
126
+
127
+ loggerErrorSpy.mockClear();
128
+ resetSchema();
129
+ });
130
+ });
131
+
132
+ describe('when smartField return none array include', () => {
133
+ it('should transform include to array', async () => {
134
+ expect.assertions(1);
135
+
136
+ Interface.Schemas.schemas.actor.fields[0].search = (query) => { query.include = 'movie'; };
137
+
138
+ const options = new QueryOptions(model);
139
+ await options.search('search string', null);
140
+ expect(options._customerIncludes).toStrictEqual(['movie']);
141
+
142
+ resetSchema();
143
+ });
144
+ });
145
+ });
59
146
  });
@@ -25,7 +25,17 @@ describe('services > requested-fields-extractor', () => {
25
25
  associations: {},
26
26
  };
27
27
 
28
- const result = extractRequestedFields(fields, model);
28
+ const schemas = {
29
+ user: {
30
+ name: 'user',
31
+ fields: [{
32
+ field: 'name',
33
+ isVirtual: false,
34
+ }],
35
+ },
36
+ };
37
+
38
+ const result = extractRequestedFields(fields, model, schemas);
29
39
 
30
40
  expect(result).toStrictEqual(['id', 'name']);
31
41
  });
@@ -43,7 +53,17 @@ describe('services > requested-fields-extractor', () => {
43
53
  associations: {},
44
54
  };
45
55
 
46
- const result = extractRequestedFields(fields, model);
56
+ const schemas = {
57
+ user: {
58
+ name: 'user',
59
+ fields: [{
60
+ field: 'name',
61
+ isVirtual: false,
62
+ }],
63
+ },
64
+ };
65
+
66
+ const result = extractRequestedFields(fields, model, schemas);
47
67
 
48
68
  expect(result).toStrictEqual(['id', 'name']);
49
69
  });
@@ -70,7 +90,15 @@ describe('services > requested-fields-extractor', () => {
70
90
  };
71
91
 
72
92
  const schemas = {
93
+ user: {
94
+ name: 'user',
95
+ fields: [{
96
+ field: 'name',
97
+ isVirtual: false,
98
+ }],
99
+ },
73
100
  addresses: {
101
+ name: 'addresses',
74
102
  fields: [{
75
103
  field: 'street',
76
104
  isVirtual: false,
@@ -105,7 +133,15 @@ describe('services > requested-fields-extractor', () => {
105
133
  };
106
134
 
107
135
  const schemas = {
136
+ user: {
137
+ name: 'user',
138
+ fields: [{
139
+ field: 'name',
140
+ isVirtual: false,
141
+ }],
142
+ },
108
143
  addresses: {
144
+ name: 'addresses',
109
145
  fields: [
110
146
  {
111
147
  field: 'street',
@@ -147,7 +183,15 @@ describe('services > requested-fields-extractor', () => {
147
183
  };
148
184
 
149
185
  const schemas = {
186
+ user: {
187
+ name: 'user',
188
+ fields: [{
189
+ field: 'name',
190
+ isVirtual: false,
191
+ }],
192
+ },
150
193
  addresses: {
194
+ name: 'addresses',
151
195
  fields: [
152
196
  {
153
197
  field: 'street',
@@ -166,4 +210,38 @@ describe('services > requested-fields-extractor', () => {
166
210
  'homeAddress',
167
211
  ]);
168
212
  });
213
+
214
+ it('should include requested smart field', () => {
215
+ expect.assertions(1);
216
+
217
+ const fields = {
218
+ user: 'smartField',
219
+ };
220
+
221
+ const model = {
222
+ name: 'user',
223
+ primaryKeys: { id: null, uid: null },
224
+ associations: {},
225
+ };
226
+
227
+ const schemas = {
228
+ user: {
229
+ name: 'user',
230
+ fields: [{
231
+ field: 'smartField',
232
+ isVirtual: true,
233
+ }, {
234
+ field: 'anotherSmartField',
235
+ isVirtual: true,
236
+ }],
237
+ },
238
+ };
239
+
240
+ const result = extractRequestedFields(fields, model, schemas);
241
+
242
+ expect(result).toStrictEqual([
243
+ 'id',
244
+ 'smartField',
245
+ ]);
246
+ });
169
247
  });
@@ -107,7 +107,7 @@ describe('utils > sequelize-compatibility', () => {
107
107
  });
108
108
  });
109
109
 
110
- it('shoud add attributes when both sides are defined', () => {
110
+ it('should add attributes when both sides are defined', () => {
111
111
  expect.assertions(1);
112
112
 
113
113
  const options = postProcess(Model, {
@@ -122,7 +122,7 @@ describe('utils > sequelize-compatibility', () => {
122
122
  });
123
123
  });
124
124
 
125
- it('shoud drop attributes when either side is undefined', () => {
125
+ it('should drop attributes when either side is undefined', () => {
126
126
  expect.assertions(1);
127
127
 
128
128
  const options = postProcess(Model, {
@@ -233,5 +233,23 @@ describe('utils > sequelize-compatibility', () => {
233
233
  },
234
234
  });
235
235
  });
236
+
237
+
238
+ it('should add attributes when sub include is not an array', () => {
239
+ expect.assertions(1);
240
+
241
+ const options = postProcess(Model, {
242
+ include: [{ as: 'submodelAlias', attributes: ['id'], include: 'subsubmodel1Alias' }],
243
+ });
244
+
245
+ expect(options).toStrictEqual({
246
+ include: [{
247
+ as: 'submodelAlias',
248
+ model: SubModel,
249
+ attributes: ['id'],
250
+ include: [{ as: 'subsubmodel1Alias', model: SubSubModel1 }],
251
+ }],
252
+ });
253
+ });
236
254
  });
237
255
  });
package/types/index.d.ts CHANGED
@@ -153,12 +153,12 @@ export interface SmartFieldValueSetter<M extends Sequelize.Model = any> {
153
153
  }
154
154
 
155
155
  export interface SmartFieldSearchQuery {
156
- include: string[],
156
+ include: Sequelize.Includeable | Sequelize.Includeable[],
157
157
  where: Sequelize.WhereOptions,
158
158
  }
159
159
 
160
160
  export interface SmartFieldSearcher {
161
- (query: SmartFieldSearchQuery, search: string): SmartFieldSearchQuery;
161
+ (query: SmartFieldSearchQuery, search: string): SmartFieldSearchQuery | Promise<SmartFieldSearchQuery>;
162
162
  }
163
163
 
164
164
  export interface SmartFieldFiltererFilter {