@natlibfi/melinda-record-matching 2.0.1 → 2.0.7-alpha.1

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 (96) hide show
  1. package/.github/CODEOWNERS +2 -0
  2. package/.github/dependabot.yml +40 -0
  3. package/.github/workflows/melinda-node-tests.yml +70 -0
  4. package/README.md +1 -1
  5. package/dist/candidate-search/candidate-search-utils.js +3 -6
  6. package/dist/candidate-search/candidate-search-utils.js.map +1 -1
  7. package/dist/candidate-search/index.js +115 -50
  8. package/dist/candidate-search/index.js.map +1 -1
  9. package/dist/candidate-search/index.spec.js +41 -48
  10. package/dist/candidate-search/index.spec.js.map +1 -1
  11. package/dist/candidate-search/query-list/bib.js +154 -64
  12. package/dist/candidate-search/query-list/bib.js.map +1 -1
  13. package/dist/candidate-search/query-list/bib.spec.js +1 -10
  14. package/dist/candidate-search/query-list/bib.spec.js.map +1 -1
  15. package/dist/candidate-search/query-list/index.js +4 -10
  16. package/dist/candidate-search/query-list/index.js.map +1 -1
  17. package/dist/index.js +498 -50
  18. package/dist/index.js.map +1 -1
  19. package/dist/index.spec.js +60 -34
  20. package/dist/index.spec.js.map +1 -1
  21. package/dist/match-detection/features/bib/all-source-ids.js +16 -19
  22. package/dist/match-detection/features/bib/all-source-ids.js.map +1 -1
  23. package/dist/match-detection/features/bib/authors.js +31 -35
  24. package/dist/match-detection/features/bib/authors.js.map +1 -1
  25. package/dist/match-detection/features/bib/bibliographic-level.js +3 -3
  26. package/dist/match-detection/features/bib/bibliographic-level.js.map +1 -1
  27. package/dist/match-detection/features/bib/host-component.js +3 -3
  28. package/dist/match-detection/features/bib/host-component.js.map +1 -1
  29. package/dist/match-detection/features/bib/index.js +28 -13
  30. package/dist/match-detection/features/bib/index.js.map +1 -1
  31. package/dist/match-detection/features/bib/index.spec.js +9 -13
  32. package/dist/match-detection/features/bib/index.spec.js.map +1 -1
  33. package/dist/match-detection/features/bib/isbn.js +28 -6
  34. package/dist/match-detection/features/bib/isbn.js.map +1 -1
  35. package/dist/match-detection/features/bib/issn.js +0 -4
  36. package/dist/match-detection/features/bib/issn.js.map +1 -1
  37. package/dist/match-detection/features/bib/language.js +69 -41
  38. package/dist/match-detection/features/bib/language.js.map +1 -1
  39. package/dist/match-detection/features/bib/media-type.js +83 -0
  40. package/dist/match-detection/features/bib/media-type.js.map +1 -0
  41. package/dist/match-detection/features/bib/melinda-id.js +0 -4
  42. package/dist/match-detection/features/bib/melinda-id.js.map +1 -1
  43. package/dist/match-detection/features/bib/melinda-identifier-factory.js +6 -17
  44. package/dist/match-detection/features/bib/melinda-identifier-factory.js.map +1 -1
  45. package/dist/match-detection/features/bib/other-standard-identifier.js +1 -4
  46. package/dist/match-detection/features/bib/other-standard-identifier.js.map +1 -1
  47. package/dist/match-detection/features/bib/publication-time-allow-cons-years-multi.js +256 -0
  48. package/dist/match-detection/features/bib/publication-time-allow-cons-years-multi.js.map +1 -0
  49. package/dist/match-detection/features/bib/publication-time-allow-cons-years.js +71 -0
  50. package/dist/match-detection/features/bib/publication-time-allow-cons-years.js.map +1 -0
  51. package/dist/match-detection/features/bib/publication-time.js +9 -8
  52. package/dist/match-detection/features/bib/publication-time.js.map +1 -1
  53. package/dist/match-detection/features/bib/record-type.js +6 -3
  54. package/dist/match-detection/features/bib/record-type.js.map +1 -1
  55. package/dist/match-detection/features/bib/standard-identifier-factory.js +129 -39
  56. package/dist/match-detection/features/bib/standard-identifier-factory.js.map +1 -1
  57. package/dist/match-detection/features/bib/title-version-original.js +79 -0
  58. package/dist/match-detection/features/bib/title-version-original.js.map +1 -0
  59. package/dist/match-detection/features/bib/title.js +29 -22
  60. package/dist/match-detection/features/bib/title.js.map +1 -1
  61. package/dist/match-detection/features/index.js +0 -4
  62. package/dist/match-detection/features/index.js.map +1 -1
  63. package/dist/match-detection/index.js +94 -47
  64. package/dist/match-detection/index.js.map +1 -1
  65. package/dist/match-detection/index.spec.js +25 -15
  66. package/dist/match-detection/index.spec.js.map +1 -1
  67. package/dist/matching-utils.js +63 -15
  68. package/dist/matching-utils.js.map +1 -1
  69. package/package.json +27 -24
  70. package/src/candidate-search/index.js +93 -31
  71. package/src/candidate-search/index.spec.js +27 -24
  72. package/src/candidate-search/query-list/bib.js +149 -22
  73. package/src/candidate-search/query-list/index.js +1 -1
  74. package/src/index.js +310 -38
  75. package/src/index.spec.js +49 -21
  76. package/src/match-detection/features/bib/all-source-ids.js +3 -3
  77. package/src/match-detection/features/bib/authors.js +23 -16
  78. package/src/match-detection/features/bib/bibliographic-level.js +1 -1
  79. package/src/match-detection/features/bib/host-component.js +1 -1
  80. package/src/match-detection/features/bib/index.js +4 -0
  81. package/src/match-detection/features/bib/index.spec.js +10 -2
  82. package/src/match-detection/features/bib/isbn.js +21 -2
  83. package/src/match-detection/features/bib/language.js +63 -22
  84. package/src/match-detection/features/bib/media-type.js +77 -0
  85. package/src/match-detection/features/bib/melinda-identifier-factory.js +2 -3
  86. package/src/match-detection/features/bib/other-standard-identifier.js +2 -0
  87. package/src/match-detection/features/bib/publication-time-allow-cons-years-multi.js +268 -0
  88. package/src/match-detection/features/bib/publication-time-allow-cons-years.js +67 -0
  89. package/src/match-detection/features/bib/publication-time.js +9 -4
  90. package/src/match-detection/features/bib/record-type.js +5 -1
  91. package/src/match-detection/features/bib/standard-identifier-factory.js +107 -22
  92. package/src/match-detection/features/bib/title-version-original.js +78 -0
  93. package/src/match-detection/features/bib/title.js +27 -7
  94. package/src/match-detection/index.js +60 -22
  95. package/src/match-detection/index.spec.js +18 -4
  96. package/src/matching-utils.js +62 -5
@@ -3,21 +3,22 @@
3
3
  Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
+ exports.extractSubfieldsFromField = extractSubfieldsFromField;
7
+ exports.getMatchCounts = getMatchCounts;
6
8
  exports.getMelindaIdsF035 = getMelindaIdsF035;
7
9
  exports.getSubfieldValues = getSubfieldValues;
10
+ exports.testStringOrNumber = testStringOrNumber;
11
+ exports.uniqueSubfields = uniqueSubfields;
8
12
  exports.validateSidFieldSubfieldCounts = validateSidFieldSubfieldCounts;
9
-
10
13
  var _debug = _interopRequireDefault(require("debug"));
11
-
12
14
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
13
-
14
15
  /**
15
16
  *
16
17
  * @licstart The following is the entire license notice for the JavaScript code in this file.
17
18
  *
18
19
  * Melinda record matching modules for Javascript
19
20
  *
20
- * Copyright (C) 2020 University Of Helsinki (The National Library Of Finland)
21
+ * Copyright (C) 2020-2022 University Of Helsinki (The National Library Of Finland)
21
22
  *
22
23
  * This file is part of melinda-record-matching-js
23
24
  *
@@ -38,36 +39,32 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de
38
39
  * for the JavaScript code in this file.
39
40
  *
40
41
  */
41
- const debug = (0, _debug.default)('@natlibfi/melinda-record-matching:utils');
42
- const debugData = debug.extend('data'); // eslint-disable-next-line max-statements
43
42
 
43
+ const debug = (0, _debug.default)('@natlibfi/melinda-record-matching:utils');
44
+ const debugData = debug.extend('data');
44
45
  function getMelindaIdsF035(record) {
45
46
  const debug = (0, _debug.default)('@natlibfi/melinda-record-matching:melinda-id');
46
47
  const debugData = debug.extend('data');
47
48
  const f035s = record.getFields('035');
48
-
49
49
  if (f035s.length < 1) {
50
50
  debug(`No f035s found.`);
51
51
  return [];
52
52
  }
53
-
54
53
  const allF035MelindaIds = [].concat(...f035s.map(toMelindaIds));
55
54
  const f035MelindaIds = [...new Set(allF035MelindaIds)];
56
55
  debugData(`Fields (${f035s.length}): ${JSON.stringify(f035s)}`);
57
56
  debugData(`Ids (${allF035MelindaIds.length}): ${JSON.stringify(allF035MelindaIds)}`);
58
57
  debugData(`Unique ids (${f035MelindaIds.length}): ${JSON.stringify(f035MelindaIds)}`);
59
58
  return f035MelindaIds;
60
-
61
59
  function toMelindaIds({
62
60
  subfields
63
61
  }) {
64
62
  const melindaIdRegExp = /^(?<prefix>\(FI-MELINDA\)|FCC)(?<id>\d{9})$/u;
65
- return subfields.filter(sub => ['a', 'z'].includes(sub.code)).filter(sub => melindaIdRegExp.test(sub.value)).map(({
63
+ return subfields.filter(sub => ['a', 'z'].includes(sub.code)).filter(sub => testStringOrNumber(sub.value) && melindaIdRegExp.test(String(sub.value))).map(({
66
64
  value
67
- }) => value.replace(melindaIdRegExp, '$<id>'));
65
+ }) => testStringOrNumber(value) ? String(value).replace(melindaIdRegExp, '$<id>') : '');
68
66
  }
69
67
  }
70
-
71
68
  function validateSidFieldSubfieldCounts(field) {
72
69
  // Valid SID-fields have just one $c and one $b
73
70
  debugData(`Validating SID field ${JSON.stringify(field)}`);
@@ -76,20 +73,71 @@ function validateSidFieldSubfieldCounts(field) {
76
73
  debug(`Found ${countC} sf $cs and ${countB} sf $bs. IsValid: ${countC === 1 && countB === 1}`);
77
74
  return countC === 1 && countB === 1;
78
75
  }
79
-
80
76
  function countSubfields(field, subfieldCode) {
81
77
  // debug(`Counting subfields ${subfieldCode}`);
82
78
  return field.subfields.filter(({
83
79
  code
84
80
  }) => code === subfieldCode).length;
85
81
  }
86
-
87
82
  function getSubfieldValues(field, subfieldCode) {
88
83
  debugData(`Get subfield(s) $${subfieldCode} from ${JSON.stringify(field)}`);
89
84
  return field.subfields.filter(({
90
85
  code
91
86
  }) => code === subfieldCode).map(({
92
87
  value
93
- }) => value);
88
+ }) => testStringOrNumber(value) ? String(value) : '').filter(value => value);
89
+ }
90
+ function testStringOrNumber(value) {
91
+ if (typeof value === 'string' || typeof value === 'number') {
92
+ return true;
93
+ }
94
+ return false;
95
+ }
96
+ function extractSubfieldsFromField(field, subfieldCodes) {
97
+ if (field === undefined || field.subfields === undefined) {
98
+ return [];
99
+ }
100
+ const resultSubfields = field.subfields.filter(({
101
+ code
102
+ }) => subfieldCodes.includes(code)).map(({
103
+ code,
104
+ value
105
+ }) => ({
106
+ code,
107
+ value: testStringOrNumber(value) ? String(value) : ''
108
+ })).filter(value => value);
109
+ return resultSubfields;
110
+ }
111
+ function uniqueSubfields(subfields) {
112
+ return subfields.reduce((arr, e) => {
113
+ if (!arr.find(item => item.code === e.code && item.value === e.value)) {
114
+ const newArr = arr.concat(e);
115
+ return newArr;
116
+ }
117
+ return arr;
118
+ }, []);
119
+ }
120
+ function getMatchCounts(aValues, bValues) {
121
+ const matchingValues = getMatchingValuesAmount(aValues, bValues);
122
+ return {
123
+ maxValues: aValues.length > bValues.length ? aValues.length : bValues.length,
124
+ // possibleMatchingValues: amount of identifiers in set of less identifiers (we cannot more values than these)
125
+ possibleMatchValues: aValues.length > bValues.length ? bValues.length : aValues.length,
126
+ matchingValues
127
+ };
128
+ function getMatchingValuesAmount(aValues, bValues) {
129
+ if (bValues.length > aValues.length) {
130
+ return aValues.filter(aValue => bValues.some(bValue => aValue === bValue)).length;
131
+ }
132
+ if (aValues.length > bValues.length) {
133
+ return bValues.filter(bValue => aValues.some(aValue => bValue === aValue)).length;
134
+ }
135
+
136
+ // If we have same amount of values, we'll check matches both ways, to avoid mixups in cases
137
+ // there would be duplicate values
138
+ const aToB = aValues.filter(aValue => bValues.some(bValue => aValue === bValue)).length;
139
+ const bToA = bValues.filter(bValue => aValues.some(aValue => bValue === aValue)).length;
140
+ return aToB < bToA ? aToB : bToA;
141
+ }
94
142
  }
95
143
  //# sourceMappingURL=matching-utils.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/matching-utils.js"],"names":["debug","debugData","extend","getMelindaIdsF035","record","f035s","getFields","length","allF035MelindaIds","concat","map","toMelindaIds","f035MelindaIds","Set","JSON","stringify","subfields","melindaIdRegExp","filter","sub","includes","code","test","value","replace","validateSidFieldSubfieldCounts","field","countC","countSubfields","countB","subfieldCode","getSubfieldValues"],"mappings":";;;;;;;;;AA4BA;;;;AA5BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAIA,MAAMA,KAAK,GAAG,oBA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G,CAACI,KAAzB,CAFV,EAGJb,GAHI,CAGA,CAAC;AAACa,MAAAA;AAAD,KAAD,KAAaA,KAAK,CAACC,OAAN,CAAcP,eAAd,EAA+B,OAA/B,CAHb,CAAP;AAKD;AACF;;AAEM,SAASQ,8BAAT,CAAwCC,KAAxC,EAA+C;AACpD;AACAzB,EAAAA,SAAS,CAAE,wBAAuBa,IAAI,CAACC,SAAL,CAAeW,KAAf,CAAsB,EAA/C,CAAT;AACA,QAAMC,MAAM,GAAGC,cAAc,CAACF,KAAD,EAAQ,GAAR,CAA7B;AACA,QAAMG,MAAM,GAAGD,cAAc,CAACF,KAAD,EAAQ,GAAR,CAA7B;AACA1B,EAAAA,KAAK,CAAE,SAAQ2B,MAAO,eAAcE,MAAO,qBAAoBF,MAAM,KAAK,CAAX,IAAgBE,MAAM,KAAK,CAAE,EAAvF,CAAL;AAEA,SAAOF,MAAM,KAAK,CAAX,IAAgBE,MAAM,KAAK,CAAlC;AACD;;AAED,SAASD,cAAT,CAAwBF,KAAxB,EAA+BI,YAA/B,EAA6C;AAC3C;AACA,SAAOJ,KAAK,CAACV,SAAN,CAAgBE,MAAhB,CAAuB,CAAC;AAACG,IAAAA;AAAD,GAAD,KAAYA,IAAI,KAAKS,YAA5C,EAA0DvB,MAAjE;AACD;;AAEM,SAASwB,iBAAT,CAA2BL,KAA3B,EAAkCI,YAAlC,EAAgD;AACrD7B,EAAAA,SAAS,CAAE,oBAAmB6B,YAAa,SAAQhB,IAAI,CAACC,SAAL,CAAeW,KAAf,CAAsB,EAAhE,CAAT;AACA,SAAOA,KAAK,CAACV,SAAN,CAAgBE,MAAhB,CAAuB,CAAC;AAACG,IAAAA;AAAD,GAAD,KAAYA,IAAI,KAAKS,YAA5C,EAA0DpB,GAA1D,CAA8D,CAAC;AAACa,IAAAA;AAAD,GAAD,KAAaA,KAA3E,CAAP;AACD","sourcesContent":["/**\n*\n* @licstart The following is the entire license notice for the JavaScript code in this file.\n*\n* Melinda record matching modules for Javascript\n*\n* Copyright (C) 2020 University Of Helsinki (The National Library Of Finland)\n*\n* This file is part of melinda-record-matching-js\n*\n* melinda-record-matching-js program is free software: you can redistribute it and/or modify\n* it under the terms of the GNU Lesser General Public License as\n* published by the Free Software Foundation, either version 3 of the\n* License, or (at your option) any later version.\n*\n* melinda-record-matching-js is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n* GNU Lesser General Public License for more details.\n*\n* You should have received a copy of the GNU Affero General Public License\n* along with this program. If not, see <http://www.gnu.org/licenses/>.\n*\n* @licend The above is the entire license notice\n* for the JavaScript code in this file.\n*\n*/\n\nimport createDebugLogger from 'debug';\n\nconst debug = createDebugLogger('@natlibfi/melinda-record-matching:utils');\nconst debugData = debug.extend('data');\n\n// eslint-disable-next-line max-statements\nexport function getMelindaIdsF035(record) {\n\n const debug = createDebugLogger('@natlibfi/melinda-record-matching:melinda-id');\n const debugData = debug.extend('data');\n\n const f035s = record.getFields('035');\n\n if (f035s.length < 1) {\n debug(`No f035s found.`);\n return [];\n }\n\n const allF035MelindaIds = [].concat(...f035s.map(toMelindaIds));\n const f035MelindaIds = [...new Set(allF035MelindaIds)];\n\n debugData(`Fields (${f035s.length}): ${JSON.stringify(f035s)}`);\n debugData(`Ids (${allF035MelindaIds.length}): ${JSON.stringify(allF035MelindaIds)}`);\n debugData(`Unique ids (${f035MelindaIds.length}): ${JSON.stringify(f035MelindaIds)}`);\n\n return f035MelindaIds;\n\n function toMelindaIds({subfields}) {\n const melindaIdRegExp = /^(?<prefix>\\(FI-MELINDA\\)|FCC)(?<id>\\d{9})$/u;\n\n return subfields\n .filter(sub => ['a', 'z'].includes(sub.code))\n .filter(sub => melindaIdRegExp.test(sub.value))\n .map(({value}) => value.replace(melindaIdRegExp, '$<id>'));\n\n }\n}\n\nexport function validateSidFieldSubfieldCounts(field) {\n // Valid SID-fields have just one $c and one $b\n debugData(`Validating SID field ${JSON.stringify(field)}`);\n const countC = countSubfields(field, 'c');\n const countB = countSubfields(field, 'b');\n debug(`Found ${countC} sf $cs and ${countB} sf $bs. IsValid: ${countC === 1 && countB === 1}`);\n\n return countC === 1 && countB === 1;\n}\n\nfunction countSubfields(field, subfieldCode) {\n // debug(`Counting subfields ${subfieldCode}`);\n return field.subfields.filter(({code}) => code === subfieldCode).length;\n}\n\nexport function getSubfieldValues(field, subfieldCode) {\n debugData(`Get subfield(s) $${subfieldCode} from ${JSON.stringify(field)}`);\n return field.subfields.filter(({code}) => code === subfieldCode).map(({value}) => value);\n}\n\n"],"file":"matching-utils.js"}
1
+ {"version":3,"file":"matching-utils.js","names":["_debug","_interopRequireDefault","require","obj","__esModule","default","debug","createDebugLogger","debugData","extend","getMelindaIdsF035","record","f035s","getFields","length","allF035MelindaIds","concat","map","toMelindaIds","f035MelindaIds","Set","JSON","stringify","subfields","melindaIdRegExp","filter","sub","includes","code","testStringOrNumber","value","test","String","replace","validateSidFieldSubfieldCounts","field","countC","countSubfields","countB","subfieldCode","getSubfieldValues","extractSubfieldsFromField","subfieldCodes","undefined","resultSubfields","uniqueSubfields","reduce","arr","e","find","item","newArr","getMatchCounts","aValues","bValues","matchingValues","getMatchingValuesAmount","maxValues","possibleMatchValues","aValue","some","bValue","aToB","bToA"],"sources":["../src/matching-utils.js"],"sourcesContent":["/**\n*\n* @licstart The following is the entire license notice for the JavaScript code in this file.\n*\n* Melinda record matching modules for Javascript\n*\n* Copyright (C) 2020-2022 University Of Helsinki (The National Library Of Finland)\n*\n* This file is part of melinda-record-matching-js\n*\n* melinda-record-matching-js program is free software: you can redistribute it and/or modify\n* it under the terms of the GNU Lesser General Public License as\n* published by the Free Software Foundation, either version 3 of the\n* License, or (at your option) any later version.\n*\n* melinda-record-matching-js is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n* GNU Lesser General Public License for more details.\n*\n* You should have received a copy of the GNU Affero General Public License\n* along with this program. If not, see <http://www.gnu.org/licenses/>.\n*\n* @licend The above is the entire license notice\n* for the JavaScript code in this file.\n*\n*/\n\nimport createDebugLogger from 'debug';\n\nconst debug = createDebugLogger('@natlibfi/melinda-record-matching:utils');\nconst debugData = debug.extend('data');\n\nexport function getMelindaIdsF035(record) {\n\n const debug = createDebugLogger('@natlibfi/melinda-record-matching:melinda-id');\n const debugData = debug.extend('data');\n\n const f035s = record.getFields('035');\n\n if (f035s.length < 1) {\n debug(`No f035s found.`);\n return [];\n }\n\n const allF035MelindaIds = [].concat(...f035s.map(toMelindaIds));\n const f035MelindaIds = [...new Set(allF035MelindaIds)];\n\n debugData(`Fields (${f035s.length}): ${JSON.stringify(f035s)}`);\n debugData(`Ids (${allF035MelindaIds.length}): ${JSON.stringify(allF035MelindaIds)}`);\n debugData(`Unique ids (${f035MelindaIds.length}): ${JSON.stringify(f035MelindaIds)}`);\n\n return f035MelindaIds;\n\n function toMelindaIds({subfields}) {\n const melindaIdRegExp = /^(?<prefix>\\(FI-MELINDA\\)|FCC)(?<id>\\d{9})$/u;\n\n return subfields\n .filter(sub => ['a', 'z'].includes(sub.code))\n .filter(sub => testStringOrNumber(sub.value) && melindaIdRegExp.test(String(sub.value)))\n .map(({value}) => testStringOrNumber(value) ? String(value).replace(melindaIdRegExp, '$<id>') : '');\n\n }\n}\n\nexport function validateSidFieldSubfieldCounts(field) {\n // Valid SID-fields have just one $c and one $b\n debugData(`Validating SID field ${JSON.stringify(field)}`);\n const countC = countSubfields(field, 'c');\n const countB = countSubfields(field, 'b');\n debug(`Found ${countC} sf $cs and ${countB} sf $bs. IsValid: ${countC === 1 && countB === 1}`);\n\n return countC === 1 && countB === 1;\n}\n\nfunction countSubfields(field, subfieldCode) {\n // debug(`Counting subfields ${subfieldCode}`);\n return field.subfields.filter(({code}) => code === subfieldCode).length;\n}\n\nexport function getSubfieldValues(field, subfieldCode) {\n debugData(`Get subfield(s) $${subfieldCode} from ${JSON.stringify(field)}`);\n return field.subfields\n .filter(({code}) => code === subfieldCode)\n .map(({value}) => testStringOrNumber(value) ? String(value) : '')\n .filter(value => value);\n}\n\nexport function testStringOrNumber(value) {\n if (typeof value === 'string' || typeof value === 'number') {\n return true;\n }\n return false;\n}\n\nexport function extractSubfieldsFromField(field, subfieldCodes) {\n if (field === undefined || field.subfields === undefined) {\n return [];\n }\n const resultSubfields = field.subfields\n .filter(({code}) => subfieldCodes.includes(code))\n .map(({code, value}) => ({code, value: testStringOrNumber(value) ? String(value) : ''}))\n .filter(value => value);\n return resultSubfields;\n}\n\nexport function uniqueSubfields(subfields) {\n return subfields.reduce((arr, e) => {\n if (!arr.find(item => item.code === e.code && item.value === e.value)) {\n const newArr = arr.concat(e);\n return newArr;\n }\n return arr;\n }, []);\n}\n\nexport function getMatchCounts(aValues, bValues) {\n\n const matchingValues = getMatchingValuesAmount(aValues, bValues);\n\n return {\n maxValues: aValues.length > bValues.length ? aValues.length : bValues.length,\n // possibleMatchingValues: amount of identifiers in set of less identifiers (we cannot more values than these)\n possibleMatchValues: aValues.length > bValues.length ? bValues.length : aValues.length,\n matchingValues\n };\n\n function getMatchingValuesAmount(aValues, bValues) {\n if (bValues.length > aValues.length) {\n return aValues.filter(aValue => bValues.some(bValue => aValue === bValue)).length;\n }\n if (aValues.length > bValues.length) {\n return bValues.filter(bValue => aValues.some(aValue => bValue === aValue)).length;\n }\n\n // If we have same amount of values, we'll check matches both ways, to avoid mixups in cases\n // there would be duplicate values\n const aToB = aValues.filter(aValue => bValues.some(bValue => aValue === bValue)).length;\n const bToA = bValues.filter(bValue => aValues.some(aValue => bValue === aValue)).length;\n\n return aToB < bToA ? aToB : bToA;\n }\n}\n"],"mappings":";;;;;;;;;;;;AA4BA,IAAAA,MAAA,GAAAC,sBAAA,CAAAC,OAAA;AAAsC,SAAAD,uBAAAE,GAAA,WAAAA,GAAA,IAAAA,GAAA,CAAAC,UAAA,GAAAD,GAAA,KAAAE,OAAA,EAAAF,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C,MAAM,IAAIR,OAAO,CAACO,IAAI,CAACD,MAAM,IAAIE,MAAM,KAAKF,MAAM,CAAC,CAAC,CAAC7C,MAAM;IAEvF,OAAOgD,IAAI,GAAGC,IAAI,GAAGD,IAAI,GAAGC,IAAI;EAClC;AACF"}
package/package.json CHANGED
@@ -14,15 +14,16 @@
14
14
  "url": "git@github.com:natlibfi/melinda-record-matching-js.git"
15
15
  },
16
16
  "license": "LGPL-3.0+",
17
- "version": "2.0.1",
17
+ "version": "2.0.7-alpha.1",
18
18
  "main": "./dist/index.js",
19
19
  "engines": {
20
- "node": ">=14"
20
+ "node": ">=18"
21
21
  },
22
22
  "publishConfig": {
23
23
  "access": "public"
24
24
  },
25
25
  "scripts": {
26
+ "prepare": "npm run build",
26
27
  "start": "node dist/index.js",
27
28
  "cli": "node dist/cli.js",
28
29
  "lint": "eslint src",
@@ -35,34 +36,36 @@
35
36
  "watch:test": "cross-env DEBUG=1 NODE_ENV=test nodemon -w src -w test-fixtures --exec 'npm run test:dev'"
36
37
  },
37
38
  "dependencies": {
38
- "@natlibfi/marc-record": "^7.0.0",
39
- "@natlibfi/marc-record-serializers": "^8.0.4",
40
- "@natlibfi/sru-client": "^5.0.0",
41
- "debug": "^4.3.3",
42
- "moment": "^2.29.1",
43
- "natural": "^5.1.11",
44
- "uuid": "^8.3.2",
45
- "winston": "^3.3.3"
39
+ "@natlibfi/marc-record": "^7.3.0",
40
+ "@natlibfi/marc-record-serializers": "^10.1.0",
41
+ "@natlibfi/melinda-commons": "^13.0.5",
42
+ "@natlibfi/sru-client": "^6.0.4",
43
+ "debug": "^4.3.4",
44
+ "isbn3": "^1.1.40",
45
+ "moment": "^2.29.4",
46
+ "natural": "^6.5.0",
47
+ "uuid": "^9.0.0",
48
+ "winston": "^3.10.0"
46
49
  },
47
50
  "devDependencies": {
48
- "@babel/cli": "^7.16.0",
49
- "@babel/core": "^7.16.0",
50
- "@babel/node": "^7.16.0",
51
- "@babel/preset-env": "^7.16.4",
52
- "@babel/register": "^7.16.0",
53
- "@babel/eslint-parser": "^7.16.3",
54
- "@natlibfi/eslint-config-melinda-backend": "^1.1.1",
55
- "@natlibfi/fixugen": "^1.0.2",
56
- "@natlibfi/fixugen-http-client": "^1.1.3",
57
- "@natlibfi/fixura": "^2.2.1",
51
+ "@babel/cli": "^7.22.10",
52
+ "@babel/core": "^7.22.10",
53
+ "@babel/eslint-parser": "^7.22.10",
54
+ "@babel/node": "^7.22.10",
55
+ "@babel/preset-env": "^7.22.10",
56
+ "@babel/register": "^7.22.5",
57
+ "@natlibfi/eslint-config-melinda-backend": "^3.0.1",
58
+ "@natlibfi/fixugen": "^2.0.1",
59
+ "@natlibfi/fixugen-http-client": "^3.0.0",
60
+ "@natlibfi/fixura": "^3.0.1",
58
61
  "babel-plugin-istanbul": "^6.1.1",
59
62
  "babel-plugin-rewire": "^1.2.0",
60
- "chai": "^4.3.4",
63
+ "chai": "^4.3.7",
61
64
  "chai-as-promised": "^7.1.1",
62
65
  "cross-env": "^7.0.3",
63
- "eslint": "^7.32.0",
64
- "mocha": "^9.1.3",
65
- "nodemon": "^2.0.15",
66
+ "eslint": "^8.47.0",
67
+ "mocha": "^10.2.0",
68
+ "nodemon": "^3.0.1",
66
69
  "nyc": "^15.1.0"
67
70
  },
68
71
  "eslintConfig": {
@@ -4,7 +4,7 @@
4
4
  *
5
5
  * Melinda record matching modules for Javascript
6
6
  *
7
- * Copyright (C) 2020 University Of Helsinki (The National Library Of Finland)
7
+ * Copyright (C) 2020-2022 University Of Helsinki (The National Library Of Finland)
8
8
  *
9
9
  * This file is part of melinda-record-matching-js
10
10
  *
@@ -31,56 +31,95 @@ import createClient, {SruSearchError} from '@natlibfi/sru-client';
31
31
  import {MarcRecord} from '@natlibfi/marc-record';
32
32
  import {MARCXML} from '@natlibfi/marc-record-serializers';
33
33
  import generateQueryList from './query-list';
34
+ import {Error as MatchingError} from '@natlibfi/melinda-commons';
34
35
 
35
36
  export {searchTypes} from './query-list';
36
37
 
37
38
  export class CandidateSearchError extends Error {}
38
39
 
39
- export default ({record, searchSpec, url, maxRecordsPerRequest = 50}) => {
40
+ // serverMaxResults : maximum size of total search result available from the server, defaults to Aleph's 20000
41
+
42
+ export default ({record, searchSpec, url, maxCandidates, maxRecordsPerRequest = 50, serverMaxResult = 20000}) => {
40
43
  MarcRecord.setValidationOptions({subfieldValues: false});
41
44
 
42
45
  const debug = createDebugLogger('@natlibfi/melinda-record-matching:candidate-search');
46
+ const debugData = debug.extend('data');
47
+
48
+ debugData(`SearchSpec: ${JSON.stringify(searchSpec)}`);
49
+ debugData(`Url: ${url}`);
50
+ debugData(`MaxRecordsPerRequest ${maxRecordsPerRequest}`);
51
+ debugData(`ServerMaxResult: ${serverMaxResult}`);
52
+ debugData(`MaxCandidates: ${maxCandidates}`);
53
+
54
+ // Do not retrieve more candidates than defined in maxCandidates
55
+ const adjustedMaxRecordsPerRequest = maxRecordsPerRequest >= maxCandidates ? maxCandidates : maxRecordsPerRequest;
56
+
43
57
  const inputRecordId = getRecordId(record);
44
58
  const queryList = generateQueryList(record, searchSpec);
45
59
  const client = createClient({
46
- url, maxRecordsPerRequest,
60
+ url,
61
+ maxRecordsPerRequest: adjustedMaxRecordsPerRequest,
47
62
  version: '2.0',
48
63
  retrieveAll: false
49
64
  });
50
65
 
51
66
  debug(`Searching matches for ${inputRecordId}`);
52
67
  debug(`Generated queryList ${JSON.stringify(queryList)}`);
53
- if (queryList.length === 0) { // eslint-disable-line functional/no-conditional-statement
68
+
69
+ // if generateQueryList errored we should throw 422
70
+
71
+ if (queryList.length === 0) {
54
72
  throw new CandidateSearchError(`Generated query list contains no queries`);
55
73
  }
56
74
 
57
- // eslint-disable-next-line max-statements
58
- return async ({queryOffset = 0, resultSetOffset = 1}) => {
75
+ // state.totalRecords : amount of candidate records available to the current query (undefined, if there was no queries left)
76
+ // state.query : current query (undefined if there was no queries left)
77
+ // state.searchCounter : sequence for current search for current query (undefined, if there we no queries left)
78
+ // state.queryCandidateCounter: amount of candidates (records+failures) retrieved from SRU for matching for current query, including the current record+failure set (undefined if there were no queries left)
79
+ // state.queriesLeft : amount of queries left
80
+ // state.queryCounter : sequence for current query
81
+ // state.maxedQueries : queries that resulted in more than serverMaxResults hits
82
+
83
+
84
+ return async ({queryOffset = 0, resultSetOffset = 1, totalRecords = 0, searchCounter = 0, queryCandidateCounter = 0, queryCounter = 0, maxedQueries = []}) => {
59
85
  const query = queryList[queryOffset];
60
86
 
61
87
  if (query) {
62
- const {records, nextOffset} = await retrieveRecords();
88
+ const {records, failures, nextOffset, total} = await retrieveRecords();
89
+
90
+ // If resultSetOffset === 1 this is the first search for the current query
91
+ debugData(`ResultSetOffset: ${resultSetOffset}`);
92
+ const newTotalRecords = resultSetOffset === 1 ? total : totalRecords;
93
+ const newQueryCounter = resultSetOffset === 1 ? queryCounter + 1 : queryCounter;
94
+ const newSearchCounter = resultSetOffset === 1 ? 1 : searchCounter + 1;
95
+ const newQueryCandidateCounter = resultSetOffset === 1 ? records.length + failures.length : queryCandidateCounter + records.length + failures.length;
96
+
97
+ const maxedQuery = resultSetOffset === 1 ? checkMaxedQuery(query, total, serverMaxResult) : undefined;
98
+ const newMaxedQueries = maxedQuery ? maxedQueries.concat(maxedQuery) : maxedQueries;
63
99
 
64
100
  if (typeof nextOffset === 'number') {
65
- debug(`Running next search for query ${queryOffset} ${query}`);
66
- return {records, queryOffset, resultSetOffset: nextOffset, queriesLeft: queryList.length - (queryOffset + 1)};
101
+ debug(`Next search will be for query ${queryOffset} ${query}, starting from record ${nextOffset}`);
102
+ return {records, failures, queryOffset, resultSetOffset: nextOffset, queriesLeft: queryList.length - (queryOffset + 1), totalRecords: newTotalRecords, query, searchCounter: newSearchCounter, queryCandidateCounter: newQueryCandidateCounter, queryCounter: newQueryCounter, maxedQueries: newMaxedQueries};
67
103
  }
68
- debug(`Query ${queryOffset} ${query} done, moving to next query. (${queryList.length - (queryOffset + 1)} queries left)`);
69
- return {records, queryOffset: queryOffset + 1, queriesLeft: queryList.length - (queryOffset + 1)};
104
+ debug(`Query ${queryOffset} ${query} done.`);
105
+ debug(`There are (${queryList.length - (queryOffset + 1)} queries left)`);
106
+ return {records, failures, queryOffset: queryOffset + 1, queriesLeft: queryList.length - (queryOffset + 1), totalRecords: newTotalRecords, query, searchCounter: newSearchCounter, queryCandidateCounter: newQueryCandidateCounter, queryCounter: newQueryCounter, maxedQueries: newMaxedQueries};
70
107
  }
71
108
 
72
109
  debug(`All ${queryList.length} queries done, there's no query for ${queryOffset}`);
73
- return {records: []};
110
+ return {records: [], failures: [], queriesLeft: 0, queryCounter, maxedQueries};
74
111
 
75
112
  function retrieveRecords() {
76
113
  return new Promise((resolve, reject) => {
77
114
  const promises = [];
115
+ // eslint-disable-next-line functional/no-let
116
+ let totalRecords = 0;
78
117
 
79
118
  debug(`Searching for candidates with query: ${query} (Offset ${resultSetOffset})`);
80
119
 
81
120
  client.searchRetrieve(query, {startRecord: resultSetOffset})
82
121
  .on('error', err => {
83
- // eslint-disable-next-line functional/no-conditional-statement
122
+ // eslint-disable-next-line functional/no-conditional-statements
84
123
  if (err instanceof SruSearchError) {
85
124
  debug(`SRU SruSearchError for query: ${query}: ${err}`);
86
125
  reject(new CandidateSearchError(`SRU SruSearchError for query: ${query}: ${err}`));
@@ -88,37 +127,45 @@ export default ({record, searchSpec, url, maxRecordsPerRequest = 50}) => {
88
127
  debug(`SRU error for query: ${query}: ${err}`);
89
128
  reject(new CandidateSearchError(`SRU error for query: ${query}: ${err}`));
90
129
  })
130
+ .on('total', total => {
131
+ debug(`Got total: ${total}`);
132
+ totalRecords += total;
133
+ })
91
134
  .on('end', async nextOffset => {
92
135
  try {
93
- const records = await Promise.all(promises);
94
- const filtered = records.filter(r => r);
136
+ const recordPromises = await Promise.allSettled(promises);
137
+ debugData(`All recordPromises: ${JSON.stringify(recordPromises)}`);
138
+ const filtered = recordPromises.filter(r => r.status === 'fulfilled').map(r => r.value);
139
+ const failures = recordPromises.filter(r => r.status === 'rejected').map(r => ({status: r.reason.status, payload: r.reason.payload}));
140
+
141
+ debug(`Found ${recordPromises.length} records`);
142
+ debug(`Found ${filtered.length} convertable candidates`);
143
+ debug(`Found ${failures.length} NON-convertable candidates`);
144
+ debugData(`Converted: ${JSON.stringify(filtered)}.`);
145
+ debugData(`Not converted: ${JSON.stringify(failures)}.`);
95
146
 
96
- debug(`Found ${filtered.length} candidates`);
97
147
 
98
- resolve({nextOffset, records: filtered});
148
+ resolve({nextOffset, records: filtered, failures, total: totalRecords});
99
149
  } catch (err) {
150
+ debug(`Error caught on END`);
100
151
  reject(err);
101
152
  }
102
153
  })
103
- .on('record', foundRecord => {
154
+ .on('record', recordXML => {
104
155
  promises.push(handleRecord()); // eslint-disable-line functional/immutable-data
105
156
 
106
157
  async function handleRecord() {
107
158
  try {
108
- const foundRecordMarc = await MARCXML.from(foundRecord, {subfieldValues: false});
109
- const foundRecordId = getRecordId(foundRecordMarc);
110
-
111
- // This does not work and might cause problems:
112
- // Record *should* match itself AND in REST the input record is given id 000000001 always
113
- debug(`Checking ${inputRecordId} vs ${foundRecordId}`);
114
- if (inputRecordId === foundRecordId) {
115
- debug(`Input and candidate are the same record per 001. Discarding candidate`);
116
- return;
117
- }
118
-
119
- return {record: foundRecordMarc, id: foundRecordId};
159
+ const recordMarc = await MARCXML.from(recordXML, {subfieldValues: false});
160
+ const recordId = getRecordId(recordMarc);
161
+
162
+ return {record: recordMarc, id: recordId};
120
163
  } catch (err) {
121
- throw new Error(`Failed converting record: ${err}, record: ${foundRecord}`);
164
+ // What should this do?
165
+ const idFromXML = getRecordIdFromXML(recordXML);
166
+ debugData(`Failed converting record: ${err.message}, id: ${idFromXML}, data: ${recordXML}`);
167
+ //return {message: `Failed converting record: ${err.message}`, id: idFromXML, data: recordXML};
168
+ throw new MatchingError(422, {message: `Failed converting record: ${err.message}`, id: idFromXML || '000000000', data: recordXML});
122
169
  }
123
170
  }
124
171
  });
@@ -126,8 +173,23 @@ export default ({record, searchSpec, url, maxRecordsPerRequest = 50}) => {
126
173
  }
127
174
  };
128
175
 
176
+ function checkMaxedQuery(query, total, serverMaxResult) {
177
+ if (total >= serverMaxResult) {
178
+ debug(`WARNING: Query ${query} resulted in ${total} hits which meets the serverMaxResult (${serverMaxResult}) `);
179
+ return query;
180
+ }
181
+ }
182
+
183
+
129
184
  function getRecordId(record) {
130
185
  const [field] = record.get(/^001$/u);
131
186
  return field ? field.value : '';
132
187
  }
188
+
189
+ function getRecordIdFromXML(recordXML) {
190
+ //<controlfield tag=\"001\">015376846</controlfield
191
+ debug(`Cannot yet find possible database record id from recordXML (length ${recordXML.length})`);
192
+ return undefined;
193
+ }
194
+
133
195
  };
@@ -4,7 +4,7 @@
4
4
  *
5
5
  * Melinda record matching modules for Javascript
6
6
  *
7
- * Copyright (C) 2020 University Of Helsinki (The National Library Of Finland)
7
+ * Copyright (C) 2020-2022 University Of Helsinki (The National Library Of Finland)
8
8
  *
9
9
  * This file is part of melinda-record-matching-js
10
10
  *
@@ -30,7 +30,11 @@ import {expect} from 'chai';
30
30
  import {READERS} from '@natlibfi/fixura';
31
31
  import generateTests from '@natlibfi/fixugen-http-client';
32
32
  import {MarcRecord} from '@natlibfi/marc-record';
33
+ import {Error as MatchingError} from '@natlibfi/melinda-commons';
33
34
  import createSearchInterface, {CandidateSearchError} from '.';
35
+ import createDebugLogger from 'debug';
36
+
37
+ const debug = createDebugLogger('@natlibfi/melinda-record-matching:candidate-search:test');
34
38
 
35
39
  describe('candidate-search', () => {
36
40
  generateTests({
@@ -42,8 +46,7 @@ describe('candidate-search', () => {
42
46
  }
43
47
  });
44
48
 
45
- // eslint-disable-next-line max-statements
46
- async function callback({getFixture, factoryOptions, searchOptions, expectedFactoryError, expectedSearchError, enabled = true}) {
49
+ async function callback({getFixture, factoryOptions, searchOptions, expectedFactoryError = false, expectedSearchError = false, enabled = true}) {
47
50
  const url = 'http://foo.bar';
48
51
 
49
52
  if (!enabled) {
@@ -61,55 +64,55 @@ describe('candidate-search', () => {
61
64
  }
62
65
 
63
66
  const search = createSearchInterface({...formatFactoryOptions(), url});
64
- await iterate({searchOptions});
67
+ await iterate({searchOptions, expectedSearchError});
65
68
 
66
69
  function formatFactoryOptions() {
70
+ debug(`Using factoryOptions: ${JSON.stringify(factoryOptions)}`);
67
71
  return {
68
72
  ...factoryOptions,
69
- maxRecordsPerRequest: 1,
73
+ maxRecordsPerRequest: factoryOptions.maxRecordsPerRequest || 1,
74
+ maxServerResults: factoryOptions.maxServerResults || undefined,
70
75
  record: new MarcRecord(factoryOptions.record, {subfieldValues: false})
71
76
  };
72
77
  }
73
78
 
74
- // eslint-disable-next-line max-statements
75
- async function iterate({searchOptions, count = 1}) {
79
+ async function iterate({searchOptions, expectedSearchError, expectedErrorStatus, count = 1}) {
76
80
  const expectedResults = getFixture(`expectedResults${count}.json`);
77
81
 
78
- if (expectedSearchError) { // eslint-disable-line functional/no-conditional-statement
82
+ if (expectedSearchError) { // eslint-disable-line functional/no-conditional-statements
79
83
  try {
80
84
  await search(searchOptions);
81
85
  throw new Error('Expected an error');
82
86
  } catch (err) {
87
+ debug(`Got an error: ${err}`);
83
88
  expect(err).to.be.an('error');
84
- expect(err.message).to.match(new RegExp(expectedSearchError, 'u'));
89
+ const errorMessage = err instanceof MatchingError ? err.payload.message : err.message;
90
+ const errorStatus = err instanceof MatchingError ? err.status : undefined;
91
+ debug(`errorMessage: ${errorMessage}, errorStatus: ${errorStatus}`);
92
+ expect(errorMessage).to.match(new RegExp(expectedSearchError, 'u'));
93
+
94
+ if (expectedErrorStatus) {
95
+ expect(errorStatus).to.be(expectedErrorStatus);
96
+ return;
97
+ }
85
98
  return;
86
99
  }
87
100
  }
88
101
 
89
- const results = await search(searchOptions);
90
-
91
- expect(formatResults(results)).to.eql(expectedResults);
92
-
93
- if (results.records.length > 0) {
94
- return iterate({
95
- searchOptions: resultsToOptions(results),
96
- count: count + 1
97
- });
102
+ // eslint-disable-next-line functional/no-conditional-statements
103
+ if (!expectedSearchError) {
104
+ const results = await search(searchOptions);
105
+ expect(formatResults(results)).to.eql(expectedResults);
98
106
  }
99
107
 
100
108
  function formatResults(results) {
101
- // console.log(results); //eslint-disable-line
109
+ debug(results);
102
110
  return {
103
111
  ...results,
104
112
  records: results.records.map(({record, id}) => ({id, record: record.toObject()}))
105
113
  };
106
114
  }
107
115
 
108
- function resultsToOptions(results) {
109
- return Object.entries(results)
110
- .filter(([k]) => k === 'records' === false) // If key is 'records' return false
111
- .reduce((acc, [k, v]) => ({...acc, [k]: v}), {});
112
- }
113
116
  }
114
117
  }
115
118
  });