@ellipticltd/aml-utils 0.16.27 → 0.16.29

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.
Files changed (99) hide show
  1. package/README.md +11 -43
  2. package/lib/errors/errors.js +19 -30
  3. package/lib/errors/errors.js.map +1 -0
  4. package/{dist → lib}/file-parser/errors.js +1 -1
  5. package/lib/file-parser/errors.js.map +1 -0
  6. package/{dist → lib}/file-parser/file-parser.d.ts +2 -4
  7. package/lib/file-parser/file-parser.js +59 -0
  8. package/lib/file-parser/file-parser.js.map +1 -0
  9. package/{dist/structured-file-parser → lib/file-parser}/parse-row.js +2 -1
  10. package/lib/file-parser/parse-row.js.map +1 -0
  11. package/{dist/file-parser/sanitzeRows.d.ts → lib/file-parser/sanitizeRows.d.ts} +3 -1
  12. package/lib/file-parser/sanitizeRows.js +15 -0
  13. package/lib/file-parser/sanitizeRows.js.map +1 -0
  14. package/lib/formatting/formatting.js +11 -12
  15. package/lib/formatting/formatting.js.map +1 -0
  16. package/{dist → lib}/index.d.ts +1 -1
  17. package/lib/index.js +21 -0
  18. package/lib/index.js.map +1 -0
  19. package/lib/middleware/middleware.js +14 -17
  20. package/lib/middleware/middleware.js.map +1 -0
  21. package/lib/orm-helpers/ormHelpers.js +12 -13
  22. package/lib/orm-helpers/ormHelpers.js.map +1 -0
  23. package/{dist → lib}/structured-file-parser/errors.js +1 -0
  24. package/lib/structured-file-parser/errors.js.map +1 -0
  25. package/{dist/file-parser → lib/structured-file-parser}/parse-row.js +2 -1
  26. package/lib/structured-file-parser/parse-row.js.map +1 -0
  27. package/{dist → lib}/structured-file-parser/sanitize-rows.js +3 -4
  28. package/lib/structured-file-parser/sanitize-rows.js.map +1 -0
  29. package/{dist → lib}/structured-file-parser/structured-file-parser.d.ts +2 -2
  30. package/lib/structured-file-parser/structured-file-parser.js +95 -0
  31. package/lib/structured-file-parser/structured-file-parser.js.map +1 -0
  32. package/{dist → lib}/types/types.d.ts +0 -6
  33. package/lib/types/types.js +191 -203
  34. package/lib/types/types.js.map +1 -0
  35. package/{dist → lib}/validations/validations.d.ts +133 -82
  36. package/lib/validations/validations.js +673 -458
  37. package/lib/validations/validations.js.map +1 -0
  38. package/package.json +7 -61
  39. package/.circleci/config.yml +0 -87
  40. package/.claude/settings.local.json +0 -7
  41. package/.eslintrc +0 -45
  42. package/.huskyrc +0 -5
  43. package/.mocharc.json +0 -3
  44. package/.nvmrc +0 -1
  45. package/.nycrc.json +0 -11
  46. package/.releaserc.json +0 -18
  47. package/.snyk +0 -12
  48. package/codecov.yml +0 -29
  49. package/commitlint.config.js +0 -1
  50. package/dist/errors/errors.js +0 -42
  51. package/dist/errors/errors.spec.d.ts +0 -1
  52. package/dist/errors/errors.spec.js +0 -23
  53. package/dist/file-parser/__tests/file-parser.spec.d.ts +0 -1
  54. package/dist/file-parser/__tests/file-parser.spec.js +0 -109
  55. package/dist/file-parser/__tests/parse-row.spec.d.ts +0 -1
  56. package/dist/file-parser/__tests/parse-row.spec.js +0 -29
  57. package/dist/file-parser/__tests/sanitize-rows.spec.d.ts +0 -1
  58. package/dist/file-parser/__tests/sanitize-rows.spec.js +0 -78
  59. package/dist/file-parser/file-parser.js +0 -55
  60. package/dist/file-parser/sanitzeRows.js +0 -18
  61. package/dist/formatting/formatting.js +0 -17
  62. package/dist/formatting/formatting.spec.d.ts +0 -1
  63. package/dist/formatting/formatting.spec.js +0 -37
  64. package/dist/index.js +0 -22
  65. package/dist/middleware/middleware.js +0 -22
  66. package/dist/orm-helpers/ormHelpers.js +0 -17
  67. package/dist/orm-helpers/ormHelpers.spec.d.ts +0 -1
  68. package/dist/orm-helpers/ormHelpers.spec.js +0 -38
  69. package/dist/structured-file-parser/structured-file-parser.js +0 -98
  70. package/dist/types/types.js +0 -203
  71. package/dist/validations/validations.js +0 -470
  72. package/dist/validations/validations.spec.d.ts +0 -1
  73. package/dist/validations/validations.spec.js +0 -463
  74. package/lib/errors/errors.spec.js +0 -37
  75. package/lib/file-parser/__tests/file-parser.spec.js +0 -107
  76. package/lib/file-parser/__tests/parse-row.spec.js +0 -35
  77. package/lib/file-parser/__tests/sanitize-rows.spec.js +0 -88
  78. package/lib/file-parser/errors.ts +0 -7
  79. package/lib/file-parser/file-parser.ts +0 -84
  80. package/lib/file-parser/parse-row.ts +0 -52
  81. package/lib/file-parser/sanitzeRows.ts +0 -32
  82. package/lib/formatting/formatting.spec.js +0 -45
  83. package/lib/index.ts +0 -19
  84. package/lib/orm-helpers/ormHelpers.spec.js +0 -41
  85. package/lib/structured-file-parser/errors.ts +0 -25
  86. package/lib/structured-file-parser/parse-row.ts +0 -52
  87. package/lib/structured-file-parser/sanitize-rows.ts +0 -24
  88. package/lib/structured-file-parser/structured-file-parser.ts +0 -155
  89. package/lib/validations/validations.spec.js +0 -603
  90. package/tsconfig.json +0 -26
  91. /package/{dist → lib}/errors/errors.d.ts +0 -0
  92. /package/{dist → lib}/file-parser/errors.d.ts +0 -0
  93. /package/{dist → lib}/file-parser/parse-row.d.ts +0 -0
  94. /package/{dist → lib}/formatting/formatting.d.ts +0 -0
  95. /package/{dist → lib}/middleware/middleware.d.ts +0 -0
  96. /package/{dist → lib}/orm-helpers/ormHelpers.d.ts +0 -0
  97. /package/{dist → lib}/structured-file-parser/errors.d.ts +0 -0
  98. /package/{dist → lib}/structured-file-parser/parse-row.d.ts +0 -0
  99. /package/{dist → lib}/structured-file-parser/sanitize-rows.d.ts +0 -0
@@ -1,35 +0,0 @@
1
- import { expect } from 'chai';
2
- import parseRow from '../parse-row';
3
-
4
- describe('parse-row', () => {
5
- it('should handle tabs', () => {
6
- const input = 'asdas \t asdar \t aaaaa \t bbb bb';
7
-
8
- const result = parseRow(input);
9
- expect(result).to.have.length(4);
10
- });
11
-
12
- it('should handle comas', () => {
13
- const input = 'asdas, asdar, aaaaa, bbb bb';
14
-
15
- const result = parseRow(input);
16
-
17
- expect(result).to.have.length(4);
18
- });
19
-
20
- it('should handle spaces', () => {
21
- const input = 'asdas asdar aaaaa bbb bb';
22
-
23
- const result = parseRow(input);
24
-
25
- expect(result).to.have.length(4);
26
- });
27
-
28
- it('should handle spaces', () => {
29
- const input = 'asdas asdar aaaaa bbb bb';
30
-
31
- const result = parseRow(input);
32
-
33
- expect(result).to.have.length(5);
34
- });
35
- });
@@ -1,88 +0,0 @@
1
- import { expect } from 'chai';
2
- import sinon from 'sinon';
3
- import sanitizeRows from '../sanitzeRows';
4
-
5
- describe('sanitize-rows', () => {
6
- it('should remove empty rows at the start of the array', () => {
7
- const input = [
8
- ['', '', ''],
9
- ['this', 'is', 'valid'],
10
- ['this', 'is', 'valid'],
11
- ];
12
-
13
- const result = sanitizeRows(input, () => ({
14
- isValid: true,
15
- }));
16
-
17
- expect(result).to.have.length(2);
18
- });
19
-
20
- it('should remove empty rows at the end of the array', () => {
21
- const input = [
22
- ['this', 'is', 'valid'],
23
- ['this', 'is', 'valid'],
24
- ['', '', ''],
25
- ];
26
-
27
- const result = sanitizeRows(input, () => ({
28
- isValid: true,
29
- }));
30
-
31
- expect(result).to.have.length(2);
32
- });
33
-
34
- it('should remove empty rows at the start and end of the array', () => {
35
- const input = [
36
- ['', '', ''],
37
- ['', '', ''],
38
- ['', '', ''],
39
- ['this', 'is', 'valid'],
40
- ['this', 'is', 'valid'],
41
- ['', '', ''],
42
- ['', '', ''],
43
- ['', '', ''],
44
- ];
45
-
46
- const result = sanitizeRows(input, () => ({
47
- isValid: true,
48
- }));
49
-
50
- expect(result).to.have.length(2);
51
- });
52
-
53
- it('should remove the first row if it is not empty and not valid', () => {
54
- const input = [
55
- ['', '', ''],
56
- ['this', 'is', 'invalid'],
57
- ['this', 'is', 'valid'],
58
- ['this', 'is', 'valid'],
59
- ['', '', ''],
60
- ['', '', ''],
61
- ['', '', ''],
62
- ];
63
-
64
- const returnsFalseOnce = sinon.stub();
65
- returnsFalseOnce.returns(true);
66
- returnsFalseOnce.onFirstCall().returns(false);
67
-
68
- const result = sanitizeRows(input, returnsFalseOnce);
69
- expect(result).to.have.length(2);
70
- });
71
-
72
- it('should allow rows with some empty values', () => {
73
- const input = [
74
- ['this', 'is', 'invalid'],
75
- ['this', 'is', 'valid'],
76
- ['this', 'is', 'valid'],
77
- ['valid', '', ''],
78
- ['', '', ''],
79
- ['', '', ''],
80
- ];
81
-
82
- const result = sanitizeRows(input, () => ({
83
- isValid: true,
84
- }));
85
-
86
- expect(result).to.have.length(4);
87
- });
88
- });
@@ -1,7 +0,0 @@
1
- // eslint-disable-next-line import/prefer-default-export
2
- export class TooManyRowsError extends Error {
3
- constructor() {
4
- super('More than configured number of rows imported');
5
- this.name = 'TooManyRowsError';
6
- }
7
- }
@@ -1,84 +0,0 @@
1
- import parseRow from './parse-row';
2
- import { TooManyRowsError } from './errors';
3
- import sanitizeRows from './sanitzeRows';
4
-
5
- export type ProcessingEntry = {
6
- isValid: boolean,
7
- };
8
-
9
- type Dependencies<T extends ProcessingEntry> = {
10
- processRow: (cells: string[]) => T,
11
- };
12
-
13
- function chunk<T>(array: T[], size: number): T[][] {
14
- if (!array.length) {
15
- return [];
16
- }
17
- const head = array.slice(0, size);
18
- const tail = array.slice(size);
19
-
20
- return [head, ...chunk(tail, size)];
21
- }
22
-
23
- async function processChunk<T extends ProcessingEntry>(
24
- parsedRows: string[][],
25
- dependencies: Dependencies<T>,
26
- ): Promise<T[]> {
27
- const { processRow } = dependencies;
28
- return new Promise(
29
- (
30
- resolve: (value: T[] | undefined) => void,
31
- reject: (error: Error) => void,
32
- ): void => {
33
- setTimeout(
34
- () => {
35
- try {
36
- const processedRows = parsedRows.map(processRow);
37
- resolve(processedRows);
38
- } catch (ex) {
39
- reject(ex);
40
- }
41
- },
42
- 0,
43
- );
44
- },
45
- );
46
- }
47
-
48
- async function parseFile<T extends ProcessingEntry>(
49
- fileContent: string,
50
- maxRows: number,
51
- dependencies: Dependencies<T>,
52
- ): Promise<T[]> {
53
- const { processRow } = dependencies;
54
-
55
- if (fileContent === 'invalidFileType') {
56
- throw Error('Invalid file type');
57
- }
58
-
59
- const rows = fileContent.split('\n');
60
- const parsedRows = rows.map(parseRow);
61
-
62
- const sanitizedRows = sanitizeRows(parsedRows, processRow);
63
-
64
- if (sanitizedRows.length > maxRows) {
65
- throw new TooManyRowsError();
66
- }
67
-
68
- if (sanitizedRows.length === 0) {
69
- throw new Error('No rows');
70
- }
71
-
72
- const parsedRowChunks = chunk(sanitizedRows, 30);
73
- let results: T[] = [];
74
- // eslint-disable-next-line no-restricted-syntax
75
- for (const currentRowChunk of parsedRowChunks) {
76
- // eslint-disable-next-line no-await-in-loop
77
- const chunkResult = await processChunk(currentRowChunk, dependencies);
78
- results = results.concat(chunkResult);
79
- }
80
-
81
- return results;
82
- }
83
-
84
- export default parseFile;
@@ -1,52 +0,0 @@
1
- import { pipe } from 'lodash/fp';
2
-
3
- const parseRow = (row: string): string[] => {
4
- const trySplitByTab = (line: string | string[]): string | string[] => {
5
- if (typeof line === 'string' && line.match('\t')) {
6
- return line.split('\t');
7
- }
8
- return line;
9
- };
10
-
11
- const trySplitByComa = (line: string | string[]): string | string[] => {
12
- if (typeof line === 'string' && line.match(',')) {
13
- return line.split(',');
14
- }
15
- return line;
16
- };
17
-
18
- const trySplitByMultipleSpaces = (line: string | string[]): string | string[] => {
19
- if (typeof line === 'string' && line.match(/ {3,}/)) {
20
- return line.split(/ {3,}/);
21
- }
22
- return line;
23
- };
24
-
25
- const trySplitBySpace = (line: string | string[]): string | string[] => {
26
- if (typeof line === 'string' && line.match(' ')) {
27
- return line.split(' ');
28
- }
29
- return line;
30
- };
31
-
32
- const trySplitByNothing = (line: string | string[]): string[] => {
33
- if (typeof line === 'string') {
34
- return [line];
35
- }
36
- return line;
37
- };
38
-
39
- const splitRow = pipe(
40
- trySplitByTab,
41
- trySplitByComa,
42
- trySplitByMultipleSpaces,
43
- trySplitBySpace,
44
- trySplitByNothing,
45
- );
46
-
47
- const cells = splitRow(row);
48
-
49
- return cells.map((c: string) => c.trim());
50
- };
51
-
52
- export default parseRow;
@@ -1,32 +0,0 @@
1
- import { ProcessingEntry } from './file-parser';
2
-
3
- const sensicalRowCheck = (cells: string[]): boolean => (
4
- cells.some((cell: string) => !!cell)
5
- );
6
-
7
- function sanitizeRows<T extends ProcessingEntry>(
8
- parsedRows: string[][],
9
- processRow: (row: string[]) => T,
10
- ): string[][] {
11
- const firstSensicalRowIndex = parsedRows
12
- .findIndex(sensicalRowCheck);
13
-
14
- const lastSensicalRowIndex = [...parsedRows]
15
- .reverse()
16
- .findIndex(sensicalRowCheck);
17
-
18
- const sanitizedRows = parsedRows
19
- .splice(
20
- firstSensicalRowIndex,
21
- parsedRows.length - firstSensicalRowIndex - lastSensicalRowIndex,
22
- );
23
-
24
- const firstRow = processRow(sanitizedRows[0]);
25
-
26
- if (firstRow.isValid) {
27
- return sanitizedRows;
28
- }
29
- return sanitizedRows.splice(1);
30
- }
31
-
32
- export default sanitizeRows;
@@ -1,45 +0,0 @@
1
- const chai = require('chai');
2
- const { sqlEscapeWildcard, rethrowError } = require('./formatting');
3
-
4
- const { expect } = chai;
5
-
6
- describe('formatting.sqlEscapeWildcard', () => {
7
- describe('when passed an empty string', () => {
8
- it('returns an empty string', () => sqlEscapeWildcard('').should.equal(''));
9
- });
10
- describe('when passed a string with no sql wildcards', () => {
11
- it('returns the same string', () => {
12
- const str = 'foo bar';
13
- return sqlEscapeWildcard(str).should.equal(str);
14
- });
15
- });
16
- return describe('when passed a string with sql wildcards', () => {
17
- it('returns the string with \\ % _ escaped', () => {
18
- const str = 'foo\\dfs_erwr%rewr';
19
- return sqlEscapeWildcard(str).should.equal('foo\\\\dfs\\_erwr\\%rewr');
20
- });
21
- });
22
- });
23
-
24
- describe('rethrowError', () => {
25
- it('returns an error when given a string', (
26
-
27
- ) => rethrowError('myFunc', { error: 'Oh dear, myFunc is broken' })
28
- .should.equal('myFunc - undefined: undefined - Oh dear, myFunc is broken'));
29
-
30
- it('returns an error when passed an error object', () => rethrowError('myFunc', {
31
- name: "I'm a teapot",
32
- statusCode: 418,
33
- error: "I'm a little teapot, short and stout",
34
- }).should.equal("myFunc - I'm a teapot: 418 - I'm a little teapot, short and stout"));
35
-
36
- it('accepts an array containing an error', () => {
37
- const thrownError = rethrowError('myFunc', {
38
- error: ["I'm a teapot", 418, "I'm a little teapot, short and stout"],
39
- });
40
-
41
- const expected = JSON.stringify('myFunc - undefined: undefined - \n[\n "I\'m a teapot",\n 418,\n "I\'m a little teapot, short and stout"\n]');
42
-
43
- expect(JSON.stringify(thrownError)).to.equal(expected);
44
- });
45
- });
package/lib/index.ts DELETED
@@ -1,19 +0,0 @@
1
- import types from './types/types';
2
- import validations from './validations/validations';
3
- import errors from './errors/errors';
4
- import formatting from './formatting/formatting';
5
- import middleware from './middleware/middleware';
6
- import ormHelpers from './orm-helpers/ormHelpers';
7
- import fileParser from './file-parser/file-parser';
8
- import structuredFileParser from './structured-file-parser/structured-file-parser';
9
-
10
- export {
11
- types,
12
- validations,
13
- errors,
14
- formatting,
15
- fileParser,
16
- structuredFileParser,
17
- middleware,
18
- ormHelpers,
19
- };
@@ -1,41 +0,0 @@
1
- const { includeNested } = require('./ormHelpers');
2
-
3
- describe('ormIncludeNested', () => {
4
- const orm = {
5
- a: 'a',
6
- b: 'b',
7
- c: 'c',
8
- d: 'd',
9
- };
10
-
11
- describe('when passed an empty object', () => {
12
- it('returns an empty array', () => includeNested(orm, {}).should.deep.equal([]));
13
- });
14
-
15
- describe('when passed an object with no inclusions', () => {
16
- it('returns an array of just the key', () => includeNested(orm, {
17
- a: {},
18
- }).should.deep.equal(['a']));
19
- });
20
-
21
- describe('when passed a hierarchy of inclusions', () => {
22
- it('should nest them in sequelize style', () => includeNested(orm, {
23
- a: {
24
- b: {
25
- c: {},
26
- d: {},
27
- },
28
- },
29
- }).should.deep.equal([
30
- {
31
- model: 'a',
32
- include: [
33
- {
34
- model: 'b',
35
- include: ['c', 'd'],
36
- },
37
- ],
38
- },
39
- ]));
40
- });
41
- });
@@ -1,25 +0,0 @@
1
- /* eslint-disable max-classes-per-file */
2
- export class InvalidFileError extends Error {
3
- constructor() {
4
- super('Invalid file type');
5
- this.name = 'InvalidFileError';
6
- }
7
- }
8
- export class TooManyRowsError extends Error {
9
- constructor() {
10
- super('More than configured number of rows imported');
11
- this.name = 'TooManyRowsError';
12
- }
13
- }
14
- export class NoRowsError extends Error {
15
- constructor() {
16
- super('No rows');
17
- this.name = 'NoRowsError';
18
- }
19
- }
20
- export class InvalidHeadersError extends Error {
21
- constructor() {
22
- super('Invalid or incomplete headers list');
23
- this.name = 'InvalidHeadersError';
24
- }
25
- }
@@ -1,52 +0,0 @@
1
- import { pipe } from 'lodash/fp';
2
-
3
- const parseRow = (row: string): string[] => {
4
- const trySplitByTab = (line: string | string[]): string | string[] => {
5
- if (typeof line === 'string' && line.match('\t')) {
6
- return line.split('\t');
7
- }
8
- return line;
9
- };
10
-
11
- const trySplitByComa = (line: string | string[]): string | string[] => {
12
- if (typeof line === 'string' && line.match(',')) {
13
- return line.split(',');
14
- }
15
- return line;
16
- };
17
-
18
- const trySplitByMultipleSpaces = (line: string | string[]): string | string[] => {
19
- if (typeof line === 'string' && line.match(/ {3,}/)) {
20
- return line.split(/ {3,}/);
21
- }
22
- return line;
23
- };
24
-
25
- const trySplitBySpace = (line: string | string[]): string | string[] => {
26
- if (typeof line === 'string' && line.match(' ')) {
27
- return line.split(' ');
28
- }
29
- return line;
30
- };
31
-
32
- const trySplitByNothing = (line: string | string[]): string[] => {
33
- if (typeof line === 'string') {
34
- return [line];
35
- }
36
- return line;
37
- };
38
-
39
- const splitRow = pipe(
40
- trySplitByTab,
41
- trySplitByComa,
42
- trySplitByMultipleSpaces,
43
- trySplitBySpace,
44
- trySplitByNothing,
45
- );
46
-
47
- const cells = splitRow(row);
48
-
49
- return cells.map((c: string) => c.trim());
50
- };
51
-
52
- export default parseRow;
@@ -1,24 +0,0 @@
1
- const sensicalRowCheck = (cells: string[]): boolean => (
2
- cells.some((cell: string) => !!cell)
3
- );
4
-
5
- function sanitizeRows(parsedRows: string[][]): string[][] {
6
- const firstSensicalRowIndex = parsedRows.findIndex(sensicalRowCheck);
7
-
8
- const lastSensicalRowIndex = [...parsedRows]
9
- .reverse()
10
- .findIndex(sensicalRowCheck);
11
-
12
- if (firstSensicalRowIndex < 0) {
13
- return [];
14
- }
15
-
16
- const sanitizedRows = [...parsedRows].splice(
17
- firstSensicalRowIndex,
18
- parsedRows.length - firstSensicalRowIndex - lastSensicalRowIndex,
19
- );
20
-
21
- return sanitizedRows;
22
- }
23
-
24
- export default sanitizeRows;
@@ -1,155 +0,0 @@
1
- /* eslint-disable no-await-in-loop */
2
- /* eslint-disable no-restricted-syntax */
3
- import parseRow from './parse-row';
4
- import {
5
- InvalidFileError,
6
- TooManyRowsError,
7
- NoRowsError,
8
- InvalidHeadersError,
9
- } from './errors';
10
- import sanitizeRows from './sanitize-rows';
11
-
12
- export type ProcessingEntry = {
13
- isValid: boolean;
14
- };
15
-
16
- type Dependencies<T extends ProcessingEntry> = {
17
- processRow: (cells: string[], headers: string[]) => T;
18
- };
19
-
20
- type CompleteDependencies<T extends ProcessingEntry, U extends string[]> = {
21
- processRow: (cells: string[], headers: U) => T;
22
- headers: U;
23
- };
24
-
25
- function chunk<T>(array: T[], size: number): T[][] {
26
- if (!array.length) {
27
- return [];
28
- }
29
- const head = array.slice(0, size);
30
- const tail = array.slice(size);
31
-
32
- return [head, ...chunk(tail, size)];
33
- }
34
-
35
- async function processChunk<T extends ProcessingEntry, U extends string[]>(
36
- parsedRows: string[][],
37
- dependencies: CompleteDependencies<T, U>,
38
- ): Promise<T[]> {
39
- const { processRow, headers } = dependencies;
40
- // @ts-ignore
41
- return new Promise(
42
- (
43
- resolve: (value: T[] | undefined) => void,
44
- reject: (error: Error) => void,
45
- ): void => {
46
- setTimeout(() => {
47
- try {
48
- const processedRows = parsedRows.map((row) => processRow(row, headers));
49
- resolve(processedRows);
50
- } catch (ex) {
51
- // @ts-ignore
52
- reject(ex);
53
- }
54
- }, 0);
55
- },
56
- );
57
- }
58
-
59
- // a row is said to contain headers if two valid header names are present
60
- export const hasHeaderRow = (
61
- rows: string[][],
62
- requiredHeaderNames: string[],
63
- ): boolean => {
64
- const firstRow = rows[0];
65
- if (!firstRow) {
66
- return false;
67
- }
68
- const foundIndex = firstRow.findIndex(
69
- (value) => requiredHeaderNames.includes(value.toLowerCase()),
70
- );
71
- if (foundIndex < 0) {
72
- return false;
73
- }
74
- const containsSecondHeader = firstRow
75
- .filter((_val, i) => i !== foundIndex)
76
- .some((value) => requiredHeaderNames.includes(value.toLowerCase()));
77
- return containsSecondHeader;
78
- };
79
-
80
- export const isHeaderRowValid = (
81
- rows: string[][],
82
- requiredHeaderNames: string[],
83
- ): boolean => {
84
- const firstRow = rows[0];
85
- if (!firstRow) {
86
- return false;
87
- }
88
- return (
89
- requiredHeaderNames.every(
90
- (header) => firstRow.map((value) => value.toLowerCase()).includes(header),
91
- ) && requiredHeaderNames.length === firstRow.length
92
- );
93
- };
94
-
95
- async function parseFile<T extends ProcessingEntry>(
96
- fileContent: string,
97
- maxRows: number,
98
- requiredHeaderNames: string[],
99
- dependencies: Dependencies<T>,
100
- ): Promise<T[]> {
101
- if (fileContent === 'invalidFileType') {
102
- throw new InvalidFileError();
103
- }
104
-
105
- const rows = fileContent.split('\n');
106
- const parsedRows = rows.map(parseRow);
107
-
108
- const sanitizedRows = sanitizeRows(parsedRows);
109
-
110
- if (sanitizedRows.length > maxRows) {
111
- throw new TooManyRowsError();
112
- }
113
-
114
- if (sanitizedRows.length === 0) {
115
- throw new NoRowsError();
116
- }
117
-
118
- const containsHeaders = hasHeaderRow(sanitizedRows, requiredHeaderNames);
119
- if (
120
- containsHeaders
121
- && !isHeaderRowValid(sanitizedRows, requiredHeaderNames)
122
- ) {
123
- throw new InvalidHeadersError();
124
- }
125
-
126
- const firstSanitizedRow = sanitizedRows[0];
127
-
128
- if (!firstSanitizedRow) {
129
- throw new NoRowsError();
130
- }
131
-
132
- const headers = containsHeaders
133
- ? firstSanitizedRow.map((value) => value.toLowerCase())
134
- : requiredHeaderNames;
135
-
136
- const dataRows = containsHeaders ? sanitizedRows.splice(1) : sanitizedRows;
137
-
138
- if (dataRows.length === 0) {
139
- throw new NoRowsError();
140
- }
141
-
142
- const parsedRowChunks = chunk(dataRows, 30);
143
- let results: T[] = [];
144
- for (const currentRowChunk of parsedRowChunks) {
145
- const chunkResult = await processChunk(currentRowChunk, {
146
- ...dependencies,
147
- headers,
148
- });
149
- results = results.concat(chunkResult);
150
- }
151
-
152
- return results;
153
- }
154
-
155
- export default parseFile;