forest-express-sequelize 9.6.12 → 9.6.14

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.
@@ -0,0 +1,223 @@
1
+ import Sequelize from 'sequelize';
2
+ import Interface, { scopeManager } from 'forest-express';
3
+ import LineStatGetter from '../../src/services/line-stat-getter';
4
+
5
+ describe('services > line-stat-getter > chart inputs', () => {
6
+ const user = { renderingId: 1 };
7
+ const dialects = ['postgres', 'mysql', 'mariadb', 'mssql', 'sqlite'];
8
+ const aggregators = ['Count', 'Sum', 'Avg', 'Min', 'Max'];
9
+ const defaultFields = [
10
+ { field: 'id', type: 'Number' },
11
+ { field: 'createdAt', type: 'Date' },
12
+ ];
13
+
14
+ const setup = (dialect, fields = defaultFields) => {
15
+ jest.restoreAllMocks();
16
+ const dialectModule = ['sqlite', 'mariadb'].includes(dialect) ? {} : undefined;
17
+ const sequelize = new Sequelize({ dialect, dialectModule });
18
+ const model = sequelize.define('user', {
19
+ id: { type: Sequelize.INTEGER, primaryKey: true },
20
+ createdAt: { type: Sequelize.DATE },
21
+ });
22
+
23
+ Interface.Schemas = {
24
+ schemas: {
25
+ user: {
26
+ name: 'user',
27
+ idField: 'id',
28
+ primaryKeys: ['id'],
29
+ fields,
30
+ },
31
+ },
32
+ };
33
+
34
+ const findAll = jest.spyOn(model, 'findAll').mockResolvedValue([]);
35
+ jest.spyOn(scopeManager, 'getScopeForUser').mockResolvedValue(null);
36
+
37
+ const buildSql = () => {
38
+ const [[findAllOptions]] = findAll.mock.calls;
39
+ return sequelize.getQueryInterface().queryGenerator
40
+ .selectQuery(model.getTableName(), findAllOptions, model);
41
+ };
42
+
43
+ return { model, findAll, buildSql };
44
+ };
45
+
46
+ const lineParams = (extra) => ({
47
+ type: 'Line',
48
+ sourceCollectionName: 'user',
49
+ groupByFieldName: 'createdAt',
50
+ aggregator: 'Count',
51
+ timeRange: 'Day',
52
+ timezone: 'Europe/Paris',
53
+ filter: null,
54
+ ...extra,
55
+ });
56
+
57
+ const deeplyNested = () => JSON.parse(`${'{"x":'.repeat(10000)}0${'}'.repeat(10000)}`);
58
+
59
+ const perform = ({ model, params }) =>
60
+ new LineStatGetter(model, params, { Sequelize }, user).perform();
61
+
62
+ describe('when the group by field is not a column of the collection', () => {
63
+ [
64
+ ['an unknown field name', 'unknownField', '"unknownField"'],
65
+ ['a name with quotes and parentheses', 'createdAt", (SELECT secret FROM users) --',
66
+ '"createdAt\\", (SELECT secret FROM users) --"'],
67
+ ['a field of another collection', 'other:createdAt', '"other:createdAt"'],
68
+ ['an empty name', '', '""'],
69
+ ['a missing name', undefined, 'undefined'],
70
+ ['a non-string name', ['createdAt'], 'object'],
71
+ ['an object without toString', { toString: null }, 'object'],
72
+ ['a deeply nested object', deeplyNested(), 'object'],
73
+ ].forEach(([description, groupByFieldName, describedName]) => {
74
+ ['postgres', 'mysql', 'mssql'].forEach((dialect) => {
75
+ it(`refuses ${description} on ${dialect} without querying the database`, async () => {
76
+ expect.assertions(2);
77
+ const { model, findAll } = setup(dialect);
78
+
79
+ await expect(perform({
80
+ model,
81
+ params: lineParams({ groupByFieldName, timeRange: 'Week' }),
82
+ })).rejects.toMatchObject({
83
+ message: `Invalid group by field ${describedName}`,
84
+ status: 400,
85
+ });
86
+
87
+ expect(findAll).not.toHaveBeenCalled();
88
+ });
89
+ });
90
+ });
91
+ });
92
+
93
+ describe('when the group by field is not a real column', () => {
94
+ [
95
+ ['a smart field', 'displayName', [
96
+ ...defaultFields,
97
+ { field: 'displayName', type: 'String', isVirtual: true },
98
+ ]],
99
+ ['a relationship field', 'car', [
100
+ ...defaultFields,
101
+ { field: 'car', type: 'Number', reference: 'cars._id' },
102
+ ]],
103
+ ['a "collection:field" name', 'car:id', [
104
+ ...defaultFields,
105
+ { field: 'car', type: 'Number', reference: 'cars._id' },
106
+ ]],
107
+ ['a declared field whose name contains ":"', 'created:at', [
108
+ ...defaultFields,
109
+ { field: 'created:at', type: 'Date' },
110
+ ]],
111
+ ].forEach(([description, groupByFieldName, fields]) => {
112
+ it(`refuses ${description} without querying the database`, async () => {
113
+ expect.assertions(2);
114
+ const { model, findAll } = setup('postgres', fields);
115
+
116
+ await expect(perform({ model, params: lineParams({ groupByFieldName }) }))
117
+ .rejects.toMatchObject({
118
+ message: `Invalid group by field "${groupByFieldName}"`,
119
+ status: 400,
120
+ });
121
+
122
+ expect(findAll).not.toHaveBeenCalled();
123
+ });
124
+ });
125
+ });
126
+
127
+ describe('when the aggregator is not allowed', () => {
128
+ [
129
+ ['an expression instead of a function name', 'count("user"."id")), (SELECT secret FROM users) --'],
130
+ ['an unknown aggregator', 'Counts'],
131
+ ['an aggregator with trailing spaces', 'count '],
132
+ ['a missing aggregator', undefined],
133
+ ['a non-string aggregator', { name: 'count' }],
134
+ ['an object without toString', { toString: null }],
135
+ ['an array of objects without toString', [{ toString: null }]],
136
+ ['a deeply nested object', deeplyNested()],
137
+ ].forEach(([description, aggregator]) => {
138
+ it(`refuses ${description} without querying the database`, async () => {
139
+ expect.assertions(2);
140
+ const { model, findAll } = setup('postgres');
141
+
142
+ await expect(perform({ model, params: lineParams({ aggregator }) }))
143
+ .rejects.toMatchObject({ status: 400 });
144
+
145
+ expect(findAll).not.toHaveBeenCalled();
146
+ });
147
+ });
148
+
149
+ it('answers a 400 BadRequestError with a neutral message', async () => {
150
+ expect.assertions(1);
151
+ const { model } = setup('postgres');
152
+
153
+ await expect(perform({ model, params: lineParams({ aggregator: 'Median' }) }))
154
+ .rejects.toMatchObject({
155
+ name: 'BadRequestError',
156
+ message: 'Invalid aggregator "Median"',
157
+ });
158
+ });
159
+ });
160
+
161
+ describe('when the chart is valid', () => {
162
+ aggregators.forEach((aggregator) => {
163
+ dialects.forEach((dialect) => {
164
+ it(`builds the ${aggregator} chart on ${dialect} as before`, async () => {
165
+ expect.assertions(2);
166
+ const { model, findAll, buildSql } = setup(dialect);
167
+
168
+ await perform({ model, params: lineParams({ aggregator }) });
169
+
170
+ expect(findAll).toHaveBeenCalledTimes(1);
171
+ expect(buildSql()).toContain(`${aggregator.toLowerCase()}(`);
172
+ });
173
+ });
174
+ });
175
+
176
+ [
177
+ ['postgres', 'Day', 'to_char(date_trunc(\'Day\', timezone(\'Europe/Paris\', '
178
+ + '"user"."createdAt")), \'YYYY-MM-DD 00:00:00\') AS "date"'],
179
+ ['postgres', 'Week', 'to_char(date_trunc(\'Week\', timezone(\'Europe/Paris\', '
180
+ + '"user"."createdAt")), \'YYYY-MM-DD 00:00:00\') AS "date"'],
181
+ ['mysql', 'Day', 'DATE_FORMAT(`user`.`createdAt`, \'%Y-%m-%d 00:00:00\') AS `date`'],
182
+ ['mysql', 'Week', 'DATE_FORMAT(DATE_SUB(`user`.`createdAt`, INTERVAL '
183
+ + '((7 + WEEKDAY(`user`.`createdAt`)) % 7) DAY), \'%Y-%m-%d 00:00:00\') AS `date`'],
184
+ ['mssql', 'Day', 'FORMAT([user].[createdAt], N\'yyyy-MM-dd 00:00:00\') AS [date]'],
185
+ ['mssql', 'Week', 'FORMAT(DATEADD(DAY, -DATEPART(dw,[user].[createdAt]),'
186
+ + '[user].[createdAt]), \'yyyy-MM-dd 00:00:00\') AS [date]'],
187
+ ['sqlite', 'Day', 'STRFTIME(\'%Y-%m-%d\', `user`.`createdAt`) AS `date`'],
188
+ ['sqlite', 'Week', 'STRFTIME(\'%Y-%W\', `user`.`createdAt`) AS `date`'],
189
+ ].forEach(([dialect, timeRange, expectedSql]) => {
190
+ it(`keeps the ${timeRange} date grouping on ${dialect}`, async () => {
191
+ expect.assertions(1);
192
+ const { model, buildSql } = setup(dialect);
193
+
194
+ await perform({ model, params: lineParams({ timeRange }) });
195
+
196
+ expect(buildSql()).toContain(expectedSql);
197
+ });
198
+ });
199
+
200
+ it('keeps accepting an aggregator whatever its case', async () => {
201
+ expect.assertions(2);
202
+ const { model, findAll, buildSql } = setup('postgres');
203
+
204
+ await perform({ model, params: lineParams({ aggregator: 'COUNT' }) });
205
+
206
+ expect(findAll).toHaveBeenCalledTimes(1);
207
+ expect(buildSql()).toContain('count(');
208
+ });
209
+
210
+ it('keeps grouping by the column name when it differs from the field name', async () => {
211
+ expect.assertions(2);
212
+ const { model, buildSql } = setup('postgres', [
213
+ { field: 'id', type: 'Number' },
214
+ { field: 'createdAt', type: 'Date', columnName: 'creation_date' },
215
+ ]);
216
+
217
+ await perform({ model, params: lineParams({}) });
218
+
219
+ expect(buildSql()).toContain('"user"."creation_date"');
220
+ expect(buildSql()).not.toContain('createdAt');
221
+ });
222
+ });
223
+ });
@@ -0,0 +1,173 @@
1
+ import Sequelize from 'sequelize';
2
+ import Interface, { scopeManager } from 'forest-express';
3
+ import LineStatGetter from '../../src/services/line-stat-getter';
4
+
5
+ describe('services > line-stat-getter', () => {
6
+ const user = { renderingId: 1 };
7
+ const supportedTimezones = ['Europe/Paris', 'America/New_York', 'UTC', 'Etc/GMT+2'];
8
+
9
+ const setup = (dialect) => {
10
+ jest.restoreAllMocks();
11
+ const dialectModule = ['sqlite', 'mariadb'].includes(dialect) ? {} : undefined;
12
+ const sequelize = new Sequelize({ dialect, dialectModule });
13
+ const model = sequelize.define('user', {
14
+ id: { type: Sequelize.INTEGER, primaryKey: true },
15
+ createdAt: { type: Sequelize.DATE },
16
+ });
17
+
18
+ Interface.Schemas = {
19
+ schemas: {
20
+ user: {
21
+ name: 'user',
22
+ idField: 'id',
23
+ primaryKeys: ['id'],
24
+ fields: [{ field: 'id', type: 'Number' }, { field: 'createdAt', type: 'Date' }],
25
+ },
26
+ },
27
+ };
28
+
29
+ const findAll = jest.spyOn(model, 'findAll').mockResolvedValue([]);
30
+ jest.spyOn(scopeManager, 'getScopeForUser').mockResolvedValue(null);
31
+
32
+ const buildSql = () => {
33
+ const [[findAllOptions]] = findAll.mock.calls;
34
+ return sequelize.getQueryInterface().queryGenerator
35
+ .selectQuery(model.getTableName(), findAllOptions, model);
36
+ };
37
+
38
+ return { model, findAll, buildSql };
39
+ };
40
+
41
+ const lineParams = (extra) => ({
42
+ type: 'Line',
43
+ sourceCollectionName: 'user',
44
+ groupByFieldName: 'createdAt',
45
+ aggregator: 'Count',
46
+ timeRange: 'Day',
47
+ filter: null,
48
+ ...extra,
49
+ });
50
+
51
+ describe('with postgres', () => {
52
+ [...supportedTimezones, 'America/Ciudad_Juarez', 'America/Coyhaique'].forEach((timezone) => {
53
+ it(`groups the dates in the ${timezone} time zone`, async () => {
54
+ expect.assertions(2);
55
+ const { model, findAll, buildSql } = setup('postgres');
56
+
57
+ await new LineStatGetter(model, lineParams({ timezone }), { Sequelize }, user).perform();
58
+
59
+ expect(findAll).toHaveBeenCalledTimes(1);
60
+ expect(buildSql()).toContain(
61
+ `to_char(date_trunc('Day', timezone('${timezone}', "user"."createdAt")), 'YYYY-MM-DD 00:00:00') AS "date"`,
62
+ );
63
+ });
64
+ });
65
+
66
+ it('accepts a zone name whatever its case', async () => {
67
+ expect.assertions(1);
68
+ const { model, buildSql } = setup('postgres');
69
+
70
+ await new LineStatGetter(model, lineParams({ timezone: 'europe/paris' }), { Sequelize }, user).perform();
71
+
72
+ expect(buildSql()).toContain('timezone(\'europe/paris\', "user"."createdAt")');
73
+ });
74
+
75
+ it('groups the dates in the requested zone on a host whose own zone Intl cannot name', async () => {
76
+ expect.assertions(1);
77
+ const { model, buildSql } = setup('postgres');
78
+ const { DateTimeFormat } = Intl;
79
+ // Node reports no host zone when started with TZ=UTC0 or TZ=:/etc/localtime.
80
+ jest.spyOn(Intl, 'DateTimeFormat').mockImplementation((...args) => (args.length
81
+ ? new DateTimeFormat(...args)
82
+ : { resolvedOptions: () => ({ timeZone: undefined }) }));
83
+
84
+ await new LineStatGetter(model, lineParams({ timezone: 'Asia/Tokyo' }), { Sequelize }, user).perform();
85
+
86
+ expect(buildSql()).toContain('timezone(\'Asia/Tokyo\', "user"."createdAt")');
87
+ });
88
+
89
+ it('reads a one-item timezone list as that zone', async () => {
90
+ expect.assertions(1);
91
+ const { model, buildSql } = setup('postgres');
92
+
93
+ await new LineStatGetter(model, lineParams({ timezone: ['Europe/Paris'] }), { Sequelize }, user).perform();
94
+
95
+ expect(buildSql()).toContain('timezone(\'Europe/Paris\', "user"."createdAt")');
96
+ });
97
+
98
+ [
99
+ ['no timezone', undefined, 'Missing timezone'],
100
+ ['an empty timezone', '', 'Missing timezone'],
101
+ ['an unknown zone name', 'Europe/Atlantis', 'Invalid timezone: "Europe/Atlantis"'],
102
+ ['a timezone containing a space', 'Europe Paris', 'Invalid timezone: "Europe Paris"'],
103
+ ['several timezones', ['Europe/Paris', 'UTC'], 'Invalid timezone: "Europe/Paris,UTC"'],
104
+ ['a timezone that is not a string', { name: 'Europe/Paris' }, 'Invalid timezone: "[object Object]"'],
105
+ ].forEach(([description, timezone, message]) => {
106
+ it(`refuses ${description} without querying the database`, async () => {
107
+ expect.assertions(2);
108
+ const { model, findAll } = setup('postgres');
109
+
110
+ await expect(
111
+ new LineStatGetter(model, lineParams({ timezone }), { Sequelize }, user).perform(),
112
+ ).rejects.toThrow(message);
113
+ expect(findAll).not.toHaveBeenCalled();
114
+ });
115
+ });
116
+
117
+ it('answers "Missing timezone" with a 400 status when a date filter comes without timezone', async () => {
118
+ expect.assertions(2);
119
+ const { model, findAll } = setup('postgres');
120
+ const filter = { field: 'createdAt', operator: 'today', value: null };
121
+
122
+ await expect(
123
+ new LineStatGetter(model, lineParams({ filter }), { Sequelize }, user).perform(),
124
+ ).rejects.toMatchObject({ message: 'Missing timezone', status: 400 });
125
+ expect(findAll).not.toHaveBeenCalled();
126
+ });
127
+
128
+ it('answers "Missing timezone" with a 400 status when a date scope comes without timezone', async () => {
129
+ expect.assertions(2);
130
+ const { model, findAll } = setup('postgres');
131
+ scopeManager.getScopeForUser.mockResolvedValue({ field: 'createdAt', operator: 'today', value: null });
132
+
133
+ await expect(
134
+ new LineStatGetter(model, lineParams({}), { Sequelize }, user).perform(),
135
+ ).rejects.toMatchObject({ message: 'Missing timezone', status: 400 });
136
+ expect(findAll).not.toHaveBeenCalled();
137
+ });
138
+
139
+ it('answers an invalid timezone with a 400 status', async () => {
140
+ expect.assertions(1);
141
+ const { model } = setup('postgres');
142
+
143
+ await expect(
144
+ new LineStatGetter(model, lineParams({ timezone: 'Europe/Atlantis' }), { Sequelize }, user).perform(),
145
+ ).rejects.toMatchObject({ name: 'BadRequestError', status: 400 });
146
+ });
147
+
148
+ it('answers a missing timezone with a 400 status', async () => {
149
+ expect.assertions(1);
150
+ const { model } = setup('postgres');
151
+
152
+ await expect(
153
+ new LineStatGetter(model, lineParams({}), { Sequelize }, user).perform(),
154
+ ).rejects.toMatchObject({ name: 'BadRequestError', status: 400 });
155
+ });
156
+ });
157
+
158
+ ['mysql', 'mariadb', 'mssql', 'sqlite'].forEach((dialect) => {
159
+ describe(`with ${dialect}`, () => {
160
+ [...supportedTimezones, undefined, 'Europe Paris'].forEach((timezone) => {
161
+ it(`builds the chart query when the timezone is ${JSON.stringify(timezone)}`, async () => {
162
+ expect.assertions(2);
163
+ const { model, findAll, buildSql } = setup(dialect);
164
+
165
+ await new LineStatGetter(model, lineParams({ timezone }), { Sequelize }, user).perform();
166
+
167
+ expect(findAll).toHaveBeenCalledTimes(1);
168
+ expect(buildSql()).not.toContain('timezone(');
169
+ });
170
+ });
171
+ });
172
+ });
173
+ });