@natlibfi/melinda-record-matching 1.0.9 → 2.0.1-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 (60) hide show
  1. package/dist/candidate-search/candidate-search-utils.js +58 -0
  2. package/dist/candidate-search/candidate-search-utils.js.map +1 -0
  3. package/dist/candidate-search/index.js +16 -5
  4. package/dist/candidate-search/index.js.map +1 -1
  5. package/dist/candidate-search/index.spec.js +94 -86
  6. package/dist/candidate-search/index.spec.js.map +1 -1
  7. package/dist/candidate-search/query-list/bib.js +113 -23
  8. package/dist/candidate-search/query-list/bib.js.map +1 -1
  9. package/dist/candidate-search/query-list/bib.spec.js +25 -23
  10. package/dist/candidate-search/query-list/bib.spec.js.map +1 -1
  11. package/dist/candidate-search/query-list/index.js +6 -4
  12. package/dist/candidate-search/query-list/index.js.map +1 -1
  13. package/dist/index.js +3 -3
  14. package/dist/index.js.map +1 -1
  15. package/dist/index.spec.js +53 -46
  16. package/dist/index.spec.js.map +1 -1
  17. package/dist/match-detection/features/bib/all-source-ids.js +122 -0
  18. package/dist/match-detection/features/bib/all-source-ids.js.map +1 -0
  19. package/dist/match-detection/features/bib/authors.js.map +1 -1
  20. package/dist/match-detection/features/bib/bibliographic-level.js.map +1 -1
  21. package/dist/match-detection/features/bib/host-component.js.map +1 -1
  22. package/dist/match-detection/features/bib/index.js +32 -16
  23. package/dist/match-detection/features/bib/index.js.map +1 -1
  24. package/dist/match-detection/features/bib/index.spec.js +50 -42
  25. package/dist/match-detection/features/bib/index.spec.js.map +1 -1
  26. package/dist/match-detection/features/bib/isbn.js.map +1 -1
  27. package/dist/match-detection/features/bib/issn.js.map +1 -1
  28. package/dist/match-detection/features/bib/language.js.map +1 -1
  29. package/dist/match-detection/features/bib/melinda-id.js +52 -0
  30. package/dist/match-detection/features/bib/melinda-id.js.map +1 -0
  31. package/dist/match-detection/features/bib/melinda-identifier-factory.js +100 -0
  32. package/dist/match-detection/features/bib/melinda-identifier-factory.js.map +1 -0
  33. package/dist/match-detection/features/bib/other-standard-identifier.js.map +1 -1
  34. package/dist/match-detection/features/bib/publication-time.js.map +1 -1
  35. package/dist/match-detection/features/bib/record-type.js.map +1 -1
  36. package/dist/match-detection/features/bib/standard-identifier-factory.js.map +1 -1
  37. package/dist/match-detection/features/bib/title.js.map +1 -1
  38. package/dist/match-detection/features/index.js +2 -2
  39. package/dist/match-detection/index.js +10 -6
  40. package/dist/match-detection/index.js.map +1 -1
  41. package/dist/match-detection/index.spec.js +32 -25
  42. package/dist/match-detection/index.spec.js.map +1 -1
  43. package/dist/matching-utils.js +95 -0
  44. package/dist/matching-utils.js.map +1 -0
  45. package/package.json +26 -29
  46. package/src/candidate-search/candidate-search-utils.js +53 -0
  47. package/src/candidate-search/index.js +11 -1
  48. package/src/candidate-search/index.spec.js +64 -58
  49. package/src/candidate-search/query-list/bib.js +130 -20
  50. package/src/candidate-search/query-list/bib.spec.js +16 -14
  51. package/src/candidate-search/query-list/index.js +3 -1
  52. package/src/index.spec.js +46 -39
  53. package/src/match-detection/features/bib/all-source-ids.js +122 -0
  54. package/src/match-detection/features/bib/index.js +2 -0
  55. package/src/match-detection/features/bib/index.spec.js +32 -23
  56. package/src/match-detection/features/bib/melinda-id.js +34 -0
  57. package/src/match-detection/features/bib/melinda-identifier-factory.js +94 -0
  58. package/src/match-detection/index.js +7 -4
  59. package/src/match-detection/index.spec.js +27 -20
  60. package/src/matching-utils.js +86 -0
@@ -11,12 +11,14 @@ var features = _interopRequireWildcard(require("./features"));
11
11
 
12
12
  exports.features = features;
13
13
 
14
- function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
14
+ function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
15
15
 
16
- function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
16
+ function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
17
17
 
18
18
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
19
19
 
20
+ /* eslint-disable no-console */
21
+
20
22
  /**
21
23
  *
22
24
  * @licstart The following is the entire license notice for the JavaScript code in this file.
@@ -44,16 +46,18 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de
44
46
  * for the JavaScript code in this file.
45
47
  *
46
48
  */
49
+ // eslint-disable-next-line max-statements
47
50
  var _default = ({
48
51
  strategy,
49
52
  treshold = 0.9
50
53
  }) => (recordA, recordB) => {
51
54
  const minProbabilityQuantifier = 0.5;
52
55
  const debug = (0, _debug.default)('@natlibfi/melinda-record-matching:match-detection');
56
+ const debugData = debug.extend('data');
53
57
  const featuresA = extractFeatures(recordA);
54
58
  const featuresB = extractFeatures(recordB);
55
- debug(`Features (a): ${JSON.stringify(featuresA)}`);
56
- debug(`Features (b): ${JSON.stringify(featuresB)}`);
59
+ debugData(`Features (a): ${JSON.stringify(featuresA)}`);
60
+ debugData(`Features (b): ${JSON.stringify(featuresB)}`);
57
61
  const featurePairs = generateFeaturePairs();
58
62
  const similarityVector = generateSimilarityVector();
59
63
 
@@ -66,7 +70,7 @@ var _default = ({
66
70
  };
67
71
  }
68
72
 
69
- debug(`No feature yielded minimum probability amount of points (${minProbabilityQuantifier})`);
73
+ debugData(`No feature yielded minimum probability amount of points (${minProbabilityQuantifier})`);
70
74
  return {
71
75
  match: false,
72
76
  probability: 0.0
@@ -104,7 +108,7 @@ var _default = ({
104
108
  points
105
109
  };
106
110
  });
107
- debug(`Points: ${JSON.stringify(compared)}`);
111
+ debugData(`Points: ${JSON.stringify(compared)}`);
108
112
  return compared.map(({
109
113
  points
110
114
  }) => points);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/match-detection/index.js"],"names":["strategy","treshold","recordA","recordB","minProbabilityQuantifier","debug","featuresA","extractFeatures","featuresB","JSON","stringify","featurePairs","generateFeaturePairs","similarityVector","generateSimilarityVector","some","v","probability","calculateprobability","match","reduce","acc","record","name","extract","concat","value","compared","map","a","b","compare","find","featureName","points","pairs","generatePairs","missingFeatures","findMissing","index","filter","length"],"mappings":";;;;;;;AA4BA;;AACA;;;;;;;;;;AA7BA;;;;;;;;;;;;;;;;;;;;;;;;;;;eAiCe,CAAC;AAACA,EAAAA,QAAD;AAAWC,EAAAA,QAAQ,GAAG;AAAtB,CAAD,KAAgC,CAACC,OAAD,EAAUC,OAAV,KAAsB;AACnE,QAAMC,wBAAwB,GAAG,GAAjC;AAEA,QAAMC,KAAK,GAAG,oBAAkB,mDAAlB,CAAd;AACA,QAAMC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C,EAKD,EALC,EAMJc,MANI,CAMG,CAAC;AAACX,QAAAA,CAAD;AAAIC,QAAAA;AAAJ,OAAD,KAAY;AAClB,YAAID,CAAC,CAACY,MAAF,KAAa,CAAb,IAAkBX,CAAC,CAACW,MAAF,KAAa,CAAnC,EAAsC;AACpC,iBAAO,KAAP;AACD;;AAED,eAAO,IAAP;AACD,OAZI,CAAP;AAaD;;AAED,aAASH,WAAT,GAAuB;AACrB,aAAOhC,SAAS,CACbsB,GADI,CACA,CAAC;AAACL,QAAAA;AAAD,OAAD,KAAYA,IADZ,EAEJiB,MAFI,CAEGxB,CAAC,IAAImB,KAAK,CAACpB,IAAN,CAAW,CAAC;AAACQ,QAAAA;AAAD,OAAD,KAAYA,IAAI,KAAKP,CAAhC,MAAuC,KAF/C,CAAP;AAGD;AACF;AACF,C","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';\nimport * as features from './features';\n\nexport {features};\n\nexport default ({strategy, treshold = 0.9}) => (recordA, recordB) => {\n const minProbabilityQuantifier = 0.5;\n\n const debug = createDebugLogger('@natlibfi/melinda-record-matching:match-detection');\n const featuresA = extractFeatures(recordA);\n const featuresB = extractFeatures(recordB);\n\n debug(`Features (a): ${JSON.stringify(featuresA)}`);\n debug(`Features (b): ${JSON.stringify(featuresB)}`);\n\n const featurePairs = generateFeaturePairs();\n const similarityVector = generateSimilarityVector();\n\n if (similarityVector.some(v => v >= minProbabilityQuantifier)) {\n const probability = calculateprobability();\n debug(`probability: ${probability} (Treshold: ${treshold})`);\n return {match: probability >= treshold, probability};\n }\n\n debug(`No feature yielded minimum probability amount of points (${minProbabilityQuantifier})`);\n return {match: false, probability: 0.0};\n\n function calculateprobability() {\n const probability = similarityVector.reduce((acc, v) => acc + v, 0.0);\n return probability > 1.0 ? 1.0 : probability;\n }\n\n function extractFeatures(record) {\n return strategy.reduce((acc, {name, extract}) => acc.concat({name, value: extract(record)}), []);\n }\n\n function generateSimilarityVector() {\n const compared = featurePairs.map(({name, a, b}) => {\n const {compare} = strategy.find(({name: featureName}) => name === featureName);\n const points = compare(a, b);\n return {name, points};\n });\n\n debug(`Points: ${JSON.stringify(compared)}`);\n return compared.map(({points}) => points);\n }\n\n function generateFeaturePairs() {\n const pairs = generatePairs();\n const missingFeatures = findMissing();\n\n debug(`Not comparing the following features because one, or both records are missing features: ${JSON.stringify(missingFeatures)}`);\n return pairs;\n\n function generatePairs() {\n return featuresA\n .reduce((acc, {name, value}, index) => acc.concat({\n name,\n a: value,\n b: featuresB[index].value\n }), [])\n .filter(({a, b}) => {\n if (a.length === 0 || b.length === 0) {\n return false;\n }\n\n return true;\n });\n }\n\n function findMissing() {\n return featuresA\n .map(({name}) => name)\n .filter(v => pairs.some(({name}) => name === v) === false);\n }\n }\n};\n"],"file":"index.js"}
1
+ {"version":3,"sources":["../../src/match-detection/index.js"],"names":["strategy","treshold","recordA","recordB","minProbabilityQuantifier","debug","debugData","extend","featuresA","extractFeatures","featuresB","JSON","stringify","featurePairs","generateFeaturePairs","similarityVector","generateSimilarityVector","some","v","probability","calculateprobability","match","reduce","acc","record","name","extract","concat","value","compared","map","a","b","compare","find","featureName","points","pairs","generatePairs","missingFeatures","findMissing","index","filter","length"],"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e,GAAGC,WAAW,EAAnC;AAEAnC,IAAAA,KAAK,CAAE,2FAA0FM,IAAI,CAACC,SAAL,CAAe2B,eAAf,CAAgC,EAA5H,CAAL;AACA,WAAOF,KAAP;;AAEA,aAASC,aAAT,GAAyB;AACvB,aAAO9B,SAAS,CACbc,MADI,CACG,CAACC,GAAD,EAAM;AAACE,QAAAA,IAAD;AAAOG,QAAAA;AAAP,OAAN,EAAqBa,KAArB,KAA+BlB,GAAG,CAACI,MAAJ,CAAW;AAChDF,QAAAA,IADgD;AAEhDM,QAAAA,CAAC,EAAEH,KAF6C;AAGhDI,QAAAA,CAAC,EAAEtB,SAAS,CAAC+B,KAAD,CAAT,CAAiBb;AAH4B,OAAX,CADlC,EAKD,EALC,EAMJc,MANI,CAMG,CAAC;AAACX,QAAAA,CAAD;AAAIC,QAAAA;AAAJ,OAAD,KAAY;AAClB,YAAID,CAAC,CAACY,MAAF,KAAa,CAAb,IAAkBX,CAAC,CAACW,MAAF,KAAa,CAAnC,EAAsC;AACpC,iBAAO,KAAP;AACD;;AAED,eAAO,IAAP;AACD,OAZI,CAAP;AAaD;;AAED,aAASH,WAAT,GAAuB;AACrB,aAAOhC,SAAS,CACbsB,GADI,CACA,CAAC;AAACL,QAAAA;AAAD,OAAD,KAAYA,IADZ,EAEJiB,MAFI,CAEGxB,CAAC,IAAImB,KAAK,CAACpB,IAAN,CAAW,CAAC;AAACQ,QAAAA;AAAD,OAAD,KAAYA,IAAI,KAAKP,CAAhC,MAAuC,KAF/C,CAAP;AAGD;AACF;AACF,C","sourcesContent":["/* eslint-disable no-console */\n/**\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';\nimport * as features from './features';\n\nexport {features};\n\n// eslint-disable-next-line max-statements\nexport default ({strategy, treshold = 0.9}) => (recordA, recordB) => {\n const minProbabilityQuantifier = 0.5;\n\n const debug = createDebugLogger('@natlibfi/melinda-record-matching:match-detection');\n const debugData = debug.extend('data');\n const featuresA = extractFeatures(recordA);\n const featuresB = extractFeatures(recordB);\n\n debugData(`Features (a): ${JSON.stringify(featuresA)}`);\n debugData(`Features (b): ${JSON.stringify(featuresB)}`);\n\n const featurePairs = generateFeaturePairs();\n const similarityVector = generateSimilarityVector();\n\n if (similarityVector.some(v => v >= minProbabilityQuantifier)) {\n const probability = calculateprobability();\n debug(`probability: ${probability} (Treshold: ${treshold})`);\n return {match: probability >= treshold, probability};\n }\n\n debugData(`No feature yielded minimum probability amount of points (${minProbabilityQuantifier})`);\n return {match: false, probability: 0.0};\n\n function calculateprobability() {\n const probability = similarityVector.reduce((acc, v) => acc + v, 0.0);\n return probability > 1.0 ? 1.0 : probability;\n }\n\n function extractFeatures(record) {\n return strategy.reduce((acc, {name, extract}) => acc.concat({name, value: extract(record)}), []);\n }\n\n function generateSimilarityVector() {\n const compared = featurePairs.map(({name, a, b}) => {\n const {compare} = strategy.find(({name: featureName}) => name === featureName);\n const points = compare(a, b);\n return {name, points};\n });\n\n debugData(`Points: ${JSON.stringify(compared)}`);\n return compared.map(({points}) => points);\n }\n\n function generateFeaturePairs() {\n const pairs = generatePairs();\n const missingFeatures = findMissing();\n\n debug(`Not comparing the following features because one, or both records are missing features: ${JSON.stringify(missingFeatures)}`);\n return pairs;\n\n function generatePairs() {\n return featuresA\n .reduce((acc, {name, value}, index) => acc.concat({\n name,\n a: value,\n b: featuresB[index].value\n }), [])\n .filter(({a, b}) => {\n if (a.length === 0 || b.length === 0) {\n return false;\n }\n\n return true;\n });\n }\n\n function findMissing() {\n return featuresA\n .map(({name}) => name)\n .filter(v => pairs.some(({name}) => name === v) === false);\n }\n }\n};\n"],"file":"index.js"}
@@ -12,9 +12,9 @@ var features = _interopRequireWildcard(require("./features"));
12
12
 
13
13
  var _ = _interopRequireDefault(require("."));
14
14
 
15
- function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
15
+ function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
16
16
 
17
- function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
17
+ function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
18
18
 
19
19
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
20
20
 
@@ -45,30 +45,37 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de
45
45
  * for the JavaScript code in this file.
46
46
  *
47
47
  */
48
- (0, _fixugen.default)({
49
- path: [__dirname, '..', '..', 'test-fixtures', 'match-detection', 'index'],
50
- useMetadataFile: true,
51
- recurse: false,
52
- fixura: {
53
- reader: _fixura.READERS.JSON
54
- },
55
- callback: ({
56
- getFixture,
57
- options,
58
- expectedResults
59
- }) => {
60
- const detect = (0, _.default)(formatOptions());
61
- const recordA = new _marcRecord.MarcRecord(getFixture('recordA.json'));
62
- const recordB = new _marcRecord.MarcRecord(getFixture('recordB.json'));
63
- const results = detect(recordA, recordB);
64
- (0, _chai.expect)(results).to.eql(expectedResults);
48
+ describe('match-detection', () => {
49
+ (0, _fixugen.default)({
50
+ path: [__dirname, '..', '..', 'test-fixtures', 'match-detection', 'index'],
51
+ useMetadataFile: true,
52
+ recurse: false,
53
+ fixura: {
54
+ reader: _fixura.READERS.JSON
55
+ },
56
+ callback: ({
57
+ getFixture,
58
+ options,
59
+ expectedResults,
60
+ enabled = true
61
+ }) => {
62
+ if (!enabled) {
63
+ return;
64
+ }
65
65
 
66
- function formatOptions() {
67
- const contextFeatures = features[options.strategy.type];
68
- return { ...options,
69
- strategy: options.strategy.features.map(v => contextFeatures[v]())
70
- };
66
+ const detect = (0, _.default)(formatOptions());
67
+ const recordA = new _marcRecord.MarcRecord(getFixture('recordA.json'));
68
+ const recordB = new _marcRecord.MarcRecord(getFixture('recordB.json'));
69
+ const results = detect(recordA, recordB);
70
+ (0, _chai.expect)(results).to.eql(expectedResults);
71
+
72
+ function formatOptions() {
73
+ const contextFeatures = features[options.strategy.type];
74
+ return { ...options,
75
+ strategy: options.strategy.features.map(v => contextFeatures[v]())
76
+ };
77
+ }
71
78
  }
72
- }
79
+ });
73
80
  });
74
81
  //# sourceMappingURL=index.spec.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/match-detection/index.spec.js"],"names":["path","__dirname","useMetadataFile","recurse","fixura","reader","READERS","JSON","callback","getFixture","options","expectedResults","detect","formatOptions","recordA","MarcRecord","recordB","results","to","eql","contextFeatures","features","strategy","type","map","v"],"mappings":";;AA4BA;;AACA;;AACA;;AACA;;AACA;;AACA;;;;;;;;AAjCA;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmCA,sBAAc;AACZA,EAAAA,IAAI,EAAE,CAACC,SAAD,EAAY,IAAZ,EAAkB,IAAlB,EAAwB,eAAxB,EAAyC,iBAAzC,EAA4D,OAA5D,CADM;AAEZC,EAAAA,eAAe,EAAE,IAFL;AAGZC,EAAAA,OAAO,EAAE,KAHG;AAIZC,EAAAA,MAAM,EAAE;AACNC,IAAAA,MAAM,EAAEC,gBAAQC;AADV,GAJI;AAOZC,EAAAA,QAAQ,EAAE,CAAC;AAACC,IAAAA,UAAD;AAAaC,IAAAA,OAAb;AAAsBC,IAAAA;AAAtB,GAAD,KAA4C;AACpD,UAAMC,MAAM,GAAG,eAAyBC,aAAa,EAAtC,CAAf;AACA,UAAMC,OAAO,GAAG,IAAIC,sBAAJ,CAAeN,UAAU,CAAC,cAAD,CAAzB,CAAhB;AACA,UAAMO,OAAO,GAAG,IAAID,sBAAJ,CAAeN,UAAU,CAAC,cAAD,CAAzB,CAAhB;AACA,UAAMQ,OAAO,GAAGL,MAAM,CAACE,OAAD,EAAUE,OAAV,CAAtB;AAEA,sBAAOC,OAAP,EAAgBC,EAAhB,CAAmBC,GAAnB,CAAuBR,eAAvB;;AAEA,aAASE,aAAT,GAAyB;AACvB,YAAMO,eAAe,GAAGC,QAAQ,CAACX,OAAO,CAACY,QAAR,CAAiBC,IAAlB,CAAhC;AAEA,aAAO,EACL,GAAGb,OADE;AAELY,QAAAA,QAAQ,EAAEZ,OAAO,CAACY,QAAR,CAAiBD,QAAjB,CAA0BG,GAA1B,CAA8BC,CAAC,IAAIL,eAAe,CAACK,CAAD,CAAf,EAAnC;AAFL,OAAP;AAID;AACF;AAvBW,CAAd","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 generateTests from '@natlibfi/fixugen';\nimport {READERS} from '@natlibfi/fixura';\nimport {expect} from 'chai';\nimport {MarcRecord} from '@natlibfi/marc-record';\nimport * as features from './features';\nimport createDetectionInterface from '.';\n\ngenerateTests({\n path: [__dirname, '..', '..', 'test-fixtures', 'match-detection', 'index'],\n useMetadataFile: true,\n recurse: false,\n fixura: {\n reader: READERS.JSON\n },\n callback: ({getFixture, options, expectedResults}) => {\n const detect = createDetectionInterface(formatOptions());\n const recordA = new MarcRecord(getFixture('recordA.json'));\n const recordB = new MarcRecord(getFixture('recordB.json'));\n const results = detect(recordA, recordB);\n\n expect(results).to.eql(expectedResults);\n\n function formatOptions() {\n const contextFeatures = features[options.strategy.type];\n\n return {\n ...options,\n strategy: options.strategy.features.map(v => contextFeatures[v]())\n };\n }\n }\n});\n"],"file":"index.spec.js"}
1
+ {"version":3,"sources":["../../src/match-detection/index.spec.js"],"names":["describe","path","__dirname","useMetadataFile","recurse","fixura","reader","READERS","JSON","callback","getFixture","options","expectedResults","enabled","detect","formatOptions","recordA","MarcRecord","recordB","results","to","eql","contextFeatures","features","strategy","type","map","v"],"mappings":";;AA4BA;;AACA;;AACA;;AACA;;AACA;;AACA;;;;;;;;AAjCA;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;AASAA,QAAQ,CAAC,iBAAD,EAAoB,MAAM;AAChC,wBAAc;AACZC,IAAAA,IAAI,EAAE,CAACC,SAAD,EAAY,IAAZ,EAAkB,IAAlB,EAAwB,eAAxB,EAAyC,iBAAzC,EAA4D,OAA5D,CADM;AAEZC,IAAAA,eAAe,EAAE,IAFL;AAGZC,IAAAA,OAAO,EAAE,KAHG;AAIZC,IAAAA,MAAM,EAAE;AACNC,MAAAA,MAAM,EAAEC,gBAAQC;AADV,KAJI;AAOZC,IAAAA,QAAQ,EAAE,CAAC;AAACC,MAAAA,UAAD;AAAaC,MAAAA,OAAb;AAAsBC,MAAAA,eAAtB;AAAuCC,MAAAA,OAAO,GAAG;AAAjD,KAAD,KAA4D;AAEpE,UAAI,CAACA,OAAL,EAAc;AACZ;AACD;;AAED,YAAMC,MAAM,GAAG,eAAyBC,aAAa,EAAtC,CAAf;AACA,YAAMC,OAAO,GAAG,IAAIC,sBAAJ,CAAeP,UAAU,CAAC,cAAD,CAAzB,CAAhB;AACA,YAAMQ,OAAO,GAAG,IAAID,sBAAJ,CAAeP,UAAU,CAAC,cAAD,CAAzB,CAAhB;AACA,YAAMS,OAAO,GAAGL,MAAM,CAACE,OAAD,EAAUE,OAAV,CAAtB;AAEA,wBAAOC,OAAP,EAAgBC,EAAhB,CAAmBC,GAAnB,CAAuBT,eAAvB;;AAEA,eAASG,aAAT,GAAyB;AACvB,cAAMO,eAAe,GAAGC,QAAQ,CAACZ,OAAO,CAACa,QAAR,CAAiBC,IAAlB,CAAhC;AAEA,eAAO,EACL,GAAGd,OADE;AAELa,UAAAA,QAAQ,EAAEb,OAAO,CAACa,QAAR,CAAiBD,QAAjB,CAA0BG,GAA1B,CAA8BC,CAAC,IAAIL,eAAe,CAACK,CAAD,CAAf,EAAnC;AAFL,SAAP;AAID;AACF;AA5BW,GAAd;AA8BD,CA/BO,CAAR","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 generateTests from '@natlibfi/fixugen';\nimport {READERS} from '@natlibfi/fixura';\nimport {expect} from 'chai';\nimport {MarcRecord} from '@natlibfi/marc-record';\nimport * as features from './features';\nimport createDetectionInterface from '.';\n\ndescribe('match-detection', () => {\n generateTests({\n path: [__dirname, '..', '..', 'test-fixtures', 'match-detection', 'index'],\n useMetadataFile: true,\n recurse: false,\n fixura: {\n reader: READERS.JSON\n },\n callback: ({getFixture, options, expectedResults, enabled = true}) => {\n\n if (!enabled) {\n return;\n }\n\n const detect = createDetectionInterface(formatOptions());\n const recordA = new MarcRecord(getFixture('recordA.json'));\n const recordB = new MarcRecord(getFixture('recordB.json'));\n const results = detect(recordA, recordB);\n\n expect(results).to.eql(expectedResults);\n\n function formatOptions() {\n const contextFeatures = features[options.strategy.type];\n\n return {\n ...options,\n strategy: options.strategy.features.map(v => contextFeatures[v]())\n };\n }\n }\n });\n});\n"],"file":"index.spec.js"}
@@ -0,0 +1,95 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.getMelindaIdsF035 = getMelindaIdsF035;
7
+ exports.getSubfieldValues = getSubfieldValues;
8
+ exports.validateSidFieldSubfieldCounts = validateSidFieldSubfieldCounts;
9
+
10
+ var _debug = _interopRequireDefault(require("debug"));
11
+
12
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
13
+
14
+ /**
15
+ *
16
+ * @licstart The following is the entire license notice for the JavaScript code in this file.
17
+ *
18
+ * Melinda record matching modules for Javascript
19
+ *
20
+ * Copyright (C) 2020 University Of Helsinki (The National Library Of Finland)
21
+ *
22
+ * This file is part of melinda-record-matching-js
23
+ *
24
+ * melinda-record-matching-js program is free software: you can redistribute it and/or modify
25
+ * it under the terms of the GNU Lesser General Public License as
26
+ * published by the Free Software Foundation, either version 3 of the
27
+ * License, or (at your option) any later version.
28
+ *
29
+ * melinda-record-matching-js is distributed in the hope that it will be useful,
30
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
31
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
32
+ * GNU Lesser General Public License for more details.
33
+ *
34
+ * You should have received a copy of the GNU Affero General Public License
35
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
36
+ *
37
+ * @licend The above is the entire license notice
38
+ * for the JavaScript code in this file.
39
+ *
40
+ */
41
+ const debug = (0, _debug.default)('@natlibfi/melinda-record-matching:utils');
42
+ const debugData = debug.extend('data'); // eslint-disable-next-line max-statements
43
+
44
+ function getMelindaIdsF035(record) {
45
+ const debug = (0, _debug.default)('@natlibfi/melinda-record-matching:melinda-id');
46
+ const debugData = debug.extend('data');
47
+ const f035s = record.getFields('035');
48
+
49
+ if (f035s.length < 1) {
50
+ debug(`No f035s found.`);
51
+ return [];
52
+ }
53
+
54
+ const allF035MelindaIds = [].concat(...f035s.map(toMelindaIds));
55
+ const f035MelindaIds = [...new Set(allF035MelindaIds)];
56
+ debugData(`Fields (${f035s.length}): ${JSON.stringify(f035s)}`);
57
+ debugData(`Ids (${allF035MelindaIds.length}): ${JSON.stringify(allF035MelindaIds)}`);
58
+ debugData(`Unique ids (${f035MelindaIds.length}): ${JSON.stringify(f035MelindaIds)}`);
59
+ return f035MelindaIds;
60
+
61
+ function toMelindaIds({
62
+ subfields
63
+ }) {
64
+ 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(({
66
+ value
67
+ }) => value.replace(melindaIdRegExp, '$<id>'));
68
+ }
69
+ }
70
+
71
+ function validateSidFieldSubfieldCounts(field) {
72
+ // Valid SID-fields have just one $c and one $b
73
+ debugData(`Validating SID field ${JSON.stringify(field)}`);
74
+ const countC = countSubfields(field, 'c');
75
+ const countB = countSubfields(field, 'b');
76
+ debug(`Found ${countC} sf $cs and ${countB} sf $bs. IsValid: ${countC === 1 && countB === 1}`);
77
+ return countC === 1 && countB === 1;
78
+ }
79
+
80
+ function countSubfields(field, subfieldCode) {
81
+ // debug(`Counting subfields ${subfieldCode}`);
82
+ return field.subfields.filter(({
83
+ code
84
+ }) => code === subfieldCode).length;
85
+ }
86
+
87
+ function getSubfieldValues(field, subfieldCode) {
88
+ debugData(`Get subfield(s) $${subfieldCode} from ${JSON.stringify(field)}`);
89
+ return field.subfields.filter(({
90
+ code
91
+ }) => code === subfieldCode).map(({
92
+ value
93
+ }) => value);
94
+ }
95
+ //# sourceMappingURL=matching-utils.js.map
@@ -0,0 +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,oBAAkB,yCAAlB,CAAd;AACA,MAAMC,SAAS,GAAGD,KAAK,CAACE,MAAN,CAAa,MAAb,CAAlB,C,CAEA;;AACO,SAASC,iBAAT,CAA2BC,MAA3B,EAAmC;AAExC,QAAMJ,KAAK,GAAG,oBAAkB,8CAAlB,CAAd;AACA,QAAMC,SAAS,GAAGD,KAAK,CAACE,MAAN,CAAa,MAAb,CAAlB;AAEA,QAAMG,KAAK,GAAGD,MAAM,CAACE,SAAP,CAAiB,KAAjB,CAAd;;AAEA,MAAID,KAAK,CAACE,MAAN,GAAe,CAAnB,EAAsB;AACpBP,IAAAA,KAAK,CAAE,iBAAF,CAAL;AACA,WAAO,EAAP;AACD;;AAED,QAAMQ,iBAAiB,GAAG,GAAGC,MAAH,CAAU,GAAGJ,KAAK,CAACK,GAAN,CAAUC,YAAV,CAAb,CAA1B;AACA,QAAMC,cAAc,GAAG,CAAC,GAAG,IAAIC,GAAJ,CAAQL,iBAAR,CAAJ,CAAvB;AAEAP,EAAAA,SAAS,CAAE,WAAUI,KAAK,CAACE,MAAO,MAAKO,IAAI,CAACC,SAAL,CAAeV,KAAf,CAAsB,EAApD,CAAT;AACAJ,EAAAA,SAAS,CAAE,QAAOO,iBAAiB,CAACD,MAAO,MAAKO,IAAI,CAACC,SAAL,CAAeP,iBAAf,CAAkC,EAAzE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,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"}
package/package.json CHANGED
@@ -14,10 +14,10 @@
14
14
  "url": "git@github.com:natlibfi/melinda-record-matching-js.git"
15
15
  },
16
16
  "license": "LGPL-3.0+",
17
- "version": "1.0.9",
17
+ "version": "2.0.1-alpha.1",
18
18
  "main": "./dist/index.js",
19
19
  "engines": {
20
- "node": ">=12"
20
+ "node": ">=14"
21
21
  },
22
22
  "publishConfig": {
23
23
  "access": "public"
@@ -35,35 +35,34 @@
35
35
  "watch:test": "cross-env DEBUG=1 NODE_ENV=test nodemon -w src -w test-fixtures --exec 'npm run test:dev'"
36
36
  },
37
37
  "dependencies": {
38
- "@natlibfi/marc-record": "^6.1.1",
39
- "@natlibfi/marc-record-serializers": "^7.1.6",
40
- "@natlibfi/sru-client": "^4.0.0",
41
- "debug": "^4.1.1",
42
- "moment": "^2.28.0",
43
- "mongodb": "^3.6.2",
44
- "natural": "^2.1.5",
45
- "uuid": "^8.3.0",
38
+ "@natlibfi/marc-record": "^7.0.0",
39
+ "@natlibfi/marc-record-serializers": "^8.0.4",
40
+ "@natlibfi/sru-client": "^5.0.0-alpha.1",
41
+ "debug": "^4.3.3",
42
+ "moment": "^2.29.1",
43
+ "natural": "^5.1.11",
44
+ "uuid": "^8.3.2",
46
45
  "winston": "^3.3.3"
47
46
  },
48
47
  "devDependencies": {
49
- "@babel/cli": "^7.11.6",
50
- "@babel/core": "^7.11.6",
51
- "@babel/node": "^7.10.5",
52
- "@babel/preset-env": "^7.11.5",
53
- "@babel/register": "^7.11.5",
54
- "@natlibfi/eslint-config-melinda-backend": "^1.0.5",
55
- "@natlibfi/fixugen": "^1.0.0",
56
- "@natlibfi/fixugen-http-client": "^1.1.1",
57
- "@natlibfi/fixura": "^2.1.3",
58
- "babel-eslint": "^10.1.0",
59
- "babel-plugin-istanbul": "^6.0.0",
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",
58
+ "babel-plugin-istanbul": "^6.1.1",
60
59
  "babel-plugin-rewire": "^1.2.0",
61
- "chai": "^4.2.0",
60
+ "chai": "^4.3.4",
62
61
  "chai-as-promised": "^7.1.1",
63
- "cross-env": "^7.0.2",
64
- "eslint": "^7.9.0",
65
- "mocha": "^8.1.3",
66
- "nodemon": "^2.0.4",
62
+ "cross-env": "^7.0.3",
63
+ "eslint": "^7.32.0",
64
+ "mocha": "^9.1.3",
65
+ "nodemon": "^2.0.15",
67
66
  "nyc": "^15.1.0"
68
67
  },
69
68
  "eslintConfig": {
@@ -74,9 +73,7 @@
74
73
  [
75
74
  "@babel/preset-env",
76
75
  {
77
- "targets": {
78
- "node": "12"
79
- }
76
+ "targets": "maintained node versions"
80
77
  }
81
78
  ]
82
79
  ],
@@ -0,0 +1,53 @@
1
+ /**
2
+ *
3
+ * @licstart The following is the entire license notice for the JavaScript code in this file.
4
+ *
5
+ * Melinda record matching modules for Javascript
6
+ *
7
+ * Copyright (C) 2020 University Of Helsinki (The National Library Of Finland)
8
+ *
9
+ * This file is part of melinda-record-matching-js
10
+ *
11
+ * melinda-record-matching-js program is free software: you can redistribute it and/or modify
12
+ * it under the terms of the GNU Lesser General Public License as
13
+ * published by the Free Software Foundation, either version 3 of the
14
+ * License, or (at your option) any later version.
15
+ *
16
+ * melinda-record-matching-js is distributed in the hope that it will be useful,
17
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
18
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19
+ * GNU Lesser General Public License for more details.
20
+ *
21
+ * You should have received a copy of the GNU Affero General Public License
22
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
23
+ *
24
+ * @licend The above is the entire license notice
25
+ * for the JavaScript code in this file.
26
+ *
27
+ */
28
+
29
+ import createDebugLogger from 'debug';
30
+
31
+ export function toQueries(identifiers, queryString) {
32
+
33
+ const debug = createDebugLogger('@natlibfi/melinda-record-matching:toQueries');
34
+ const debugData = debug.extend('data');
35
+
36
+ const quotedIdentifiers = identifiers.map(identifier => identifier.match(/\//u) ? `"${identifier}"` : `${identifier}`);
37
+
38
+ // Aleph supports only two queries with or -operator (This is not actually true)
39
+ const pairs = toPairs(quotedIdentifiers);
40
+ const queries = pairs.map(([a, b]) => b ? `${queryString}=${a} or ${queryString}=${b}` : `${queryString}=${a}`);
41
+
42
+ debugData(`Pairs (${pairs.length}): ${JSON.stringify(pairs)}`);
43
+ debugData(`Queries (${queries.length}): ${JSON.stringify(queries)}`);
44
+
45
+ return queries;
46
+ }
47
+
48
+ function toPairs(array) {
49
+ if (array.length === 0) {
50
+ return [];
51
+ }
52
+ return [array.slice(0, 2)].concat(toPairs(array.slice(2), 2));
53
+ }
@@ -27,7 +27,7 @@
27
27
  */
28
28
 
29
29
  import createDebugLogger from 'debug';
30
- import createClient from '@natlibfi/sru-client';
30
+ 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';
@@ -48,6 +48,7 @@ export default ({record, searchSpec, url, maxRecordsPerRequest = 50}) => {
48
48
  retrieveAll: false
49
49
  });
50
50
 
51
+ debug(`Searching matches for ${inputRecordId}`);
51
52
  debug(`Generated queryList ${JSON.stringify(queryList)}`);
52
53
  if (queryList.length === 0) { // eslint-disable-line functional/no-conditional-statement
53
54
  throw new CandidateSearchError(`Generated query list contains no queries`);
@@ -79,6 +80,12 @@ export default ({record, searchSpec, url, maxRecordsPerRequest = 50}) => {
79
80
 
80
81
  client.searchRetrieve(query, {startRecord: resultSetOffset})
81
82
  .on('error', err => {
83
+ // eslint-disable-next-line functional/no-conditional-statement
84
+ if (err instanceof SruSearchError) {
85
+ debug(`SRU SruSearchError for query: ${query}: ${err}`);
86
+ reject(new CandidateSearchError(`SRU SruSearchError for query: ${query}: ${err}`));
87
+ }
88
+ debug(`SRU error for query: ${query}: ${err}`);
82
89
  reject(new CandidateSearchError(`SRU error for query: ${query}: ${err}`));
83
90
  })
84
91
  .on('end', async nextOffset => {
@@ -101,6 +108,9 @@ export default ({record, searchSpec, url, maxRecordsPerRequest = 50}) => {
101
108
  const foundRecordMarc = await MARCXML.from(foundRecord, {subfieldValues: false});
102
109
  const foundRecordId = getRecordId(foundRecordMarc);
103
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}`);
104
114
  if (inputRecordId === foundRecordId) {
105
115
  debug(`Input and candidate are the same record per 001. Discarding candidate`);
106
116
  return;
@@ -32,78 +32,84 @@ import generateTests from '@natlibfi/fixugen-http-client';
32
32
  import {MarcRecord} from '@natlibfi/marc-record';
33
33
  import createSearchInterface, {CandidateSearchError} from '.';
34
34
 
35
- generateTests({
36
- callback,
37
- path: [__dirname, '..', '..', 'test-fixtures', 'candidate-search', 'index'],
38
- recurse: false,
39
- fixura: {
40
- reader: READERS.JSON
41
- }
42
- });
35
+ describe('candidate-search', () => {
36
+ generateTests({
37
+ callback,
38
+ path: [__dirname, '..', '..', 'test-fixtures', 'candidate-search', 'index'],
39
+ recurse: false,
40
+ fixura: {
41
+ reader: READERS.JSON
42
+ }
43
+ });
43
44
 
44
- // eslint-disable-next-line max-statements
45
- async function callback({getFixture, factoryOptions, searchOptions, expectedFactoryError, expectedSearchError}) {
46
- const url = 'http://foo.bar';
45
+ // eslint-disable-next-line max-statements
46
+ async function callback({getFixture, factoryOptions, searchOptions, expectedFactoryError, expectedSearchError, enabled = true}) {
47
+ const url = 'http://foo.bar';
47
48
 
48
- if (expectedFactoryError) {
49
- if (expectedFactoryError.isCandidateSearchError) {
50
- expect(() => createSearchInterface({...formatFactoryOptions(), url})).to.throw(CandidateSearchError, new RegExp(expectedFactoryError, 'u'));
49
+ if (!enabled) {
51
50
  return;
52
51
  }
53
52
 
54
- expect(() => createSearchInterface({...formatFactoryOptions(), url})).to.throw(new RegExp(expectedFactoryError, 'u'));
55
- return;
56
- }
53
+ if (expectedFactoryError) {
54
+ if (expectedFactoryError.isCandidateSearchError) {
55
+ expect(() => createSearchInterface({...formatFactoryOptions(), url})).to.throw(CandidateSearchError, new RegExp(expectedFactoryError, 'u'));
56
+ return;
57
+ }
57
58
 
58
- const search = createSearchInterface({...formatFactoryOptions(), url});
59
- await iterate({searchOptions});
59
+ expect(() => createSearchInterface({...formatFactoryOptions(), url})).to.throw(new RegExp(expectedFactoryError, 'u'));
60
+ return;
61
+ }
60
62
 
61
- function formatFactoryOptions() {
62
- return {
63
- ...factoryOptions,
64
- maxRecordsPerRequest: 1,
65
- record: new MarcRecord(factoryOptions.record, {subfieldValues: false})
66
- };
67
- }
63
+ const search = createSearchInterface({...formatFactoryOptions(), url});
64
+ await iterate({searchOptions});
68
65
 
69
- // eslint-disable-next-line max-statements
70
- async function iterate({searchOptions, count = 1}) {
71
- const expectedResults = getFixture(`expectedResults${count}.json`);
66
+ function formatFactoryOptions() {
67
+ return {
68
+ ...factoryOptions,
69
+ maxRecordsPerRequest: 1,
70
+ record: new MarcRecord(factoryOptions.record, {subfieldValues: false})
71
+ };
72
+ }
72
73
 
73
- if (expectedSearchError) { // eslint-disable-line functional/no-conditional-statement
74
- try {
75
- await search(searchOptions);
76
- throw new Error('Expected an error');
77
- } catch (err) {
78
- expect(err).to.be.an('error');
79
- expect(err.message).to.match(new RegExp(expectedSearchError, 'u'));
80
- return;
74
+ // eslint-disable-next-line max-statements
75
+ async function iterate({searchOptions, count = 1}) {
76
+ const expectedResults = getFixture(`expectedResults${count}.json`);
77
+
78
+ if (expectedSearchError) { // eslint-disable-line functional/no-conditional-statement
79
+ try {
80
+ await search(searchOptions);
81
+ throw new Error('Expected an error');
82
+ } catch (err) {
83
+ expect(err).to.be.an('error');
84
+ expect(err.message).to.match(new RegExp(expectedSearchError, 'u'));
85
+ return;
86
+ }
81
87
  }
82
- }
83
88
 
84
- const results = await search(searchOptions);
89
+ const results = await search(searchOptions);
85
90
 
86
- expect(formatResults(results)).to.eql(expectedResults);
91
+ expect(formatResults(results)).to.eql(expectedResults);
87
92
 
88
- if (results.records.length > 0) {
89
- return iterate({
90
- searchOptions: resultsToOptions(results),
91
- count: count + 1
92
- });
93
- }
93
+ if (results.records.length > 0) {
94
+ return iterate({
95
+ searchOptions: resultsToOptions(results),
96
+ count: count + 1
97
+ });
98
+ }
94
99
 
95
- function formatResults(results) {
96
- // console.log(results); //eslint-disable-line
97
- return {
98
- ...results,
99
- records: results.records.map(({record, id}) => ({id, record: record.toObject()}))
100
- };
101
- }
100
+ function formatResults(results) {
101
+ // console.log(results); //eslint-disable-line
102
+ return {
103
+ ...results,
104
+ records: results.records.map(({record, id}) => ({id, record: record.toObject()}))
105
+ };
106
+ }
102
107
 
103
- function resultsToOptions(results) {
104
- return Object.entries(results)
105
- .filter(([k]) => k === 'records' === false)
106
- .reduce((acc, [k, v]) => ({...acc, [k]: v}), {});
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
+ }
107
113
  }
108
114
  }
109
- }
115
+ });