├── .gitignore ├── .npmignore ├── LICENSE ├── README.md ├── index.js ├── package-lock.json ├── package.json └── source ├── Config └── Config.js ├── Extractor ├── CSVExtractor.js ├── Extractor.js ├── GoogleSpreadSheetExtractor.js ├── JSONExtractor.js ├── MySQLExtractor.js └── XLSXExtractor.js ├── Loader ├── CSVLoader.js ├── GoogleSpreadSheetLoader.js ├── JSONLoader.js ├── Loader.js ├── MySQLLoader.js └── XLSXLoader.js ├── Utils ├── ArrayUtils.js ├── ClassLoader.js ├── RateLimiter.js └── TypeChecker.js ├── Wizard └── wizard.js ├── index.js └── midas.js /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | distribution 3 | test 4 | test/configs 5 | test/enrichees/datev_paypal/credentials.json 6 | .DS_Store 7 | package-lock.json 8 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | test 2 | test/* 3 | test/configs 4 | test/enrichees/datev_paypal/credentials.json 5 | source 6 | .DS_Store 7 | package-lock.json -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![npm](https://img.shields.io/npm/v/npm.svg?style=for-the-badge) 2 | ![version](https://img.shields.io/badge/version-0.1-blue.svg?Cache=true&style=for-the-badge) 3 | [](https://discord.gg/zBYnHuN) 4 | ![Image](https://i.imgur.com/QhEPsca.png) 5 | 6 | With **midas** you can easily build a pipeline that automates the enrichment process of your CSV, JSON and Excel datasets. Use any web API (e.g. OpenWeatherMap, GoogleMaps, CoinMarketCap and more) to add additional information to your existing dataset without you having to worry about stuff like 7 | 8 | - **extracting data** from your dataset, 9 | - **converting file types** and 10 | - **rate limiting** of external APIs. 11 | 12 | 13 | 14 | ## **Documentation** 15 | 16 | [🚀 Getting started](https://github.com/midas-science/midas/wiki/Getting-Started) 17 | 18 | [🔧 Pipeline Configuration](https://github.com/midas-science/midas/wiki/Pipeline-Configuration) 19 | 20 | [➕ Develop your own Enricher](https://github.com/midas-science/midas/wiki/Develop-your-own-Enricher) 21 | 22 | 23 | 24 | ## **Enrichers** 25 | 26 | - [OpenWeatherMap](https://github.com/midas-science/enricher-openweathermap) 27 | - [CoinMarketCap](https://github.com/midas-science/enricher-coinmarketcap) 28 | - [Google Geocoding](https://github.com/midas-science/enricher-googlegeocoding) 29 | - [Instagram](https://github.com/midas-science/enricher-instagramlocation) 30 | - [Clearbit](https://github.com/midas-science/enricher-clearbit) 31 | - [ipapi](https://github.com/midas-science/enricher-ipapi) 32 | - [Develop your own](https://github.com/midas-science/midas/wiki/Develop-your-own-Enricher) 33 | 34 | 35 | ## **Get in touch** 36 | Join our [Discord channel](https://discord.gg/zBYnHuN) or send an email to hello@midas.science if you need help or want to give feedback. 37 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | console.log('Hello, world!'); -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "midas-core", 3 | "version": "0.0.4", 4 | "description": "Enrich data with APIs", 5 | "main": "./distribution/index.js", 6 | "bin": { 7 | "midas": "./distribution/index.js" 8 | }, 9 | "scripts": { 10 | "test": "echo \"Error: no test specified\" && exit 1", 11 | "build": "babel source --presets babel-preset-es2015 --plugins syntax-dynamic-import --out-dir distribution" 12 | }, 13 | "keywords": [ 14 | "enrich", 15 | "api", 16 | "enrichment", 17 | "json", 18 | "tranformation" 19 | ], 20 | "author": "Patrick Holl", 21 | "license": "Apache-2.0", 22 | "devDependencies": { 23 | "babel-cli": "^6.26.0", 24 | "babel-plugin-syntax-dynamic-import": "^6.18.0", 25 | "babel-preset-es2015": "^6.24.1", 26 | "colors": "^1.1.2", 27 | "command-line-args": "^5.0.2", 28 | "object-path": "^0.11.4", 29 | "prettyjson": "^1.2.1" 30 | }, 31 | "dependencies": { 32 | "camelcase": "^4.1.0", 33 | "colors": "^1.1.2", 34 | "command-line-args": "^5.0.2", 35 | "csvjson": "^5.0.0", 36 | "flat": "^4.0.0", 37 | "fs-extra": "^5.0.0", 38 | "google-spreadsheet": "^2.0.4", 39 | "google-spreadsheet-as-promised": "^0.2.12", 40 | "inquirer": "^5.1.0", 41 | "json2csv": "^4.1.2", 42 | "json2xls": "^0.1.2", 43 | "jsonfile": "^4.0.0", 44 | "jsonpath": "^1.0.0", 45 | "load-json-file": "^4.0.0", 46 | "mysql2": "^1.5.3", 47 | "npm": "^5.7.1", 48 | "object-path": "^0.11.4", 49 | "prettyjson": "^1.2.1", 50 | "read-json-sync": "^2.0.0", 51 | "recursive-iterator": "^3.3.0", 52 | "request": "^2.83.0", 53 | "request-promise": "^4.2.2", 54 | "sqlstring": "^2.3.1", 55 | "xlsx": "^0.12.2", 56 | "xlsx-writestream": "^0.5.1" 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /source/Config/Config.js: -------------------------------------------------------------------------------- 1 | import json_loader from 'load-json-file'; 2 | import read_json_sync from 'read-json-sync'; 3 | 4 | 5 | class Config { 6 | constructor(json) { 7 | this.json = json; 8 | } 9 | 10 | get_config_object_promise() { 11 | return json_loader(this.json); 12 | } 13 | 14 | get_config_object_sync() { 15 | let config = read_json_sync(this.json); 16 | 17 | // Sanity check 18 | // Make source = target if no target is defined 19 | if(typeof config.target === 'undefined') { 20 | config.target = config.source; 21 | } 22 | 23 | return config; 24 | } 25 | 26 | } 27 | 28 | export { Config as default} -------------------------------------------------------------------------------- /source/Extractor/CSVExtractor.js: -------------------------------------------------------------------------------- 1 | import Extractor from './Extractor'; 2 | 3 | import fs from 'fs-extra'; 4 | 5 | // CSV Extractors 6 | import csvjson from 'csvjson'; 7 | 8 | 9 | class CSVExtractor extends Extractor { 10 | 11 | constructor(config) { 12 | super(config); 13 | } 14 | 15 | get_data_sync() { 16 | // NOT YET IMPLEMENTED 17 | } 18 | 19 | get_data_promise() { 20 | let options = { 21 | delimiter : ',', 22 | quote : '"' 23 | }; 24 | let data = fs.readFile(this.config._source.path, { encoding : 'utf8'}); 25 | return data.then((data) => { 26 | return Promise.resolve(csvjson.toObject(data, options)); 27 | }); 28 | } 29 | 30 | } 31 | 32 | export { CSVExtractor as default} -------------------------------------------------------------------------------- /source/Extractor/Extractor.js: -------------------------------------------------------------------------------- 1 | class Extractor { 2 | 3 | constructor(config) { 4 | if(config == null || typeof config === 'undefined') { 5 | throw "No config is set"; 6 | } 7 | 8 | this.config = config; 9 | this.config._source = this.config.source[Object.keys(this.config.source)[0]]; 10 | this.config._source.type = Object.keys(this.config.source)[0]; 11 | } 12 | 13 | get_type() { 14 | return this.config._source.type; 15 | } 16 | 17 | } 18 | 19 | export { Extractor as default} -------------------------------------------------------------------------------- /source/Extractor/GoogleSpreadSheetExtractor.js: -------------------------------------------------------------------------------- 1 | import Extractor from './Extractor'; 2 | 3 | // Utils 4 | import ArrayUtils from './../Utils/ArrayUtils'; 5 | import {promisify} from 'util'; 6 | 7 | // GoogleSpreadSpreadsheet handler 8 | import GoogleSpreadSheet from 'google-spreadsheet'; 9 | 10 | 11 | class GoogleSpreadSheetExtractor extends Extractor { 12 | 13 | constructor(config) { 14 | super(config); 15 | } 16 | 17 | get_data_promise() { 18 | let doc = new GoogleSpreadSheet(this.config._source.spreadsheet_id); 19 | let creds = require(this.config._source.credentials_file_path); 20 | 21 | let doc_promise = {}; 22 | doc_promise.useServiceAccountAuth = promisify(doc.useServiceAccountAuth); 23 | doc_promise.getRows = promisify(doc.getRows); 24 | 25 | return doc_promise.useServiceAccountAuth(creds).then(() => { 26 | return doc_promise.getRows(1).then((rows, err) => { 27 | return Promise.resolve(rows); 28 | }); 29 | }); 30 | } 31 | 32 | } 33 | 34 | export { GoogleSpreadSheetExtractor as default} -------------------------------------------------------------------------------- /source/Extractor/JSONExtractor.js: -------------------------------------------------------------------------------- 1 | import Extractor from './Extractor'; 2 | 3 | // JSON handlers 4 | import json_loader from 'load-json-file'; 5 | import read_json_sync from 'read-json-sync'; 6 | 7 | class JSONExtractor extends Extractor { 8 | 9 | constructor(config) { 10 | super(config); 11 | } 12 | 13 | get_data_sync() { 14 | return read_json_sync(this.config._source.path); 15 | } 16 | 17 | get_data_promise() { 18 | return json_loader(this.config._source.path); 19 | } 20 | 21 | } 22 | 23 | export { JSONExtractor as default} -------------------------------------------------------------------------------- /source/Extractor/MySQLExtractor.js: -------------------------------------------------------------------------------- 1 | import Extractor from './Extractor'; 2 | 3 | const SqlString = require('sqlstring'); 4 | const mysql = require('mysql2/promise'); 5 | 6 | // MySQL handler 7 | 8 | class MySQLExtractor extends Extractor { 9 | 10 | constructor(config) { 11 | super(config); 12 | } 13 | 14 | get_data_sync() { 15 | return read_json_sync(this.config._source.path); 16 | } 17 | 18 | async get_data_promise() { 19 | 20 | const db_config = { 21 | host:this.config._source.host, 22 | port:this.config._source.port, 23 | user:this.config._source.user, 24 | password:this.config._source.password, 25 | database:this.config._source.database 26 | }; 27 | 28 | // create the connection 29 | const connection = await mysql.createConnection(db_config); 30 | 31 | // query database 32 | const [rows, fields] = await connection.execute(`SELECT * FROM ${SqlString.escapeId(this.config._source.table)}`); 33 | 34 | // close connection after query 35 | connection.close(); 36 | 37 | return rows; 38 | } 39 | 40 | } 41 | 42 | export { MySQLExtractor as default} -------------------------------------------------------------------------------- /source/Extractor/XLSXExtractor.js: -------------------------------------------------------------------------------- 1 | import Extractor from './Extractor'; 2 | 3 | // Utils 4 | import ArrayUtils from './../Utils/ArrayUtils'; 5 | 6 | // XLSX handler 7 | import XLSX from 'xlsx'; 8 | 9 | class XLSXExtractor extends Extractor { 10 | 11 | constructor(config) { 12 | super(config); 13 | } 14 | 15 | get_data_promise() { 16 | let wb = XLSX.readFile(this.config._source.path, {type: "file"}); 17 | let sheet = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]], {raw:false, header:1}); 18 | let objects = ArrayUtils.arrayObjectify(sheet); 19 | return Promise.resolve(objects); 20 | } 21 | 22 | } 23 | 24 | export { XLSXExtractor as default} -------------------------------------------------------------------------------- /source/Loader/CSVLoader.js: -------------------------------------------------------------------------------- 1 | import Loader from './Loader'; 2 | import fs from 'fs-extra'; 3 | 4 | import flatten from 'flat'; 5 | import csvjson from 'csvjson'; 6 | 7 | 8 | class CSVLoader extends Loader { 9 | 10 | constructor(config) { 11 | super(config); 12 | } 13 | 14 | load(data) { 15 | let options = { 16 | delimiter : this.config._target.delimiter, 17 | wrap : false, 18 | headers : 'key' 19 | }; 20 | 21 | let _data = []; 22 | 23 | data.forEach((row, index) => { 24 | _data.push(flatten(row)); 25 | }); 26 | 27 | var data_string = csvjson.toCSV(_data, options); 28 | return fs.outputFile(this.config._target.path, data_string); 29 | } 30 | 31 | } 32 | 33 | export { CSVLoader as default} -------------------------------------------------------------------------------- /source/Loader/GoogleSpreadSheetLoader.js: -------------------------------------------------------------------------------- 1 | import Loader from './Loader'; 2 | 3 | // JSON 4 | import fs from 'fs-extra'; 5 | 6 | // Utils 7 | import {promisify} from 'util'; 8 | 9 | // GoogleSpreadSpreadsheet handler 10 | import GoogleSpreadSheet from 'google-spreadsheet'; 11 | 12 | class GoogleSpreadSheetLoader extends Loader { 13 | 14 | constructor(config) { 15 | super(config); 16 | } 17 | 18 | _get_header_keys(data) { 19 | if(!Array.isArray(data)) { 20 | return Object.keys(data); 21 | } else { 22 | return Object.keys(data[0]); 23 | } 24 | } 25 | 26 | load(data) { 27 | 28 | let doc = new GoogleSpreadSheet(this.config._target.spreadsheet_id); 29 | let creds = require(this.config._target.credentials_file_path); 30 | 31 | let doc_promise = {}; 32 | doc_promise.useServiceAccountAuth = promisify(doc.useServiceAccountAuth); 33 | doc_promise.getRows = promisify(doc.getRows); 34 | doc_promise.getCells = promisify(doc.getCells); 35 | doc_promise.addWorksheet = promisify(doc.addWorksheet); 36 | 37 | data.forEach((row) => { 38 | row.street = row.company_address.street; 39 | row.lng = row.company_address.lng; 40 | row.lat = row.company_address.lat; 41 | row.save(); 42 | }); 43 | 44 | return Promise.resolve('Done'); 45 | } 46 | 47 | } 48 | 49 | export { GoogleSpreadSheetLoader as default} -------------------------------------------------------------------------------- /source/Loader/JSONLoader.js: -------------------------------------------------------------------------------- 1 | import Loader from './Loader'; 2 | 3 | // JSON 4 | import fs from 'fs-extra'; 5 | 6 | class JSONLoader extends Loader { 7 | 8 | constructor(config) { 9 | super(config); 10 | } 11 | 12 | load(data) { 13 | return fs.outputJson(this.config._target.path, data, {spaces:'\t'}); 14 | } 15 | 16 | } 17 | 18 | export { JSONLoader as default} -------------------------------------------------------------------------------- /source/Loader/Loader.js: -------------------------------------------------------------------------------- 1 | class Loader { 2 | 3 | constructor(config) { 4 | this.config = config; 5 | this.config._target = this.config.target[Object.keys(this.config.target)[0]]; 6 | this.config._target.type = Object.keys(this.config.target)[0]; 7 | } 8 | 9 | get_type() { 10 | return this.config._target.type; 11 | } 12 | 13 | } 14 | 15 | export { Loader as default} -------------------------------------------------------------------------------- /source/Loader/MySQLLoader.js: -------------------------------------------------------------------------------- 1 | import Loader from './Loader'; 2 | import flat from 'flat'; 3 | import SqlString from 'sqlstring'; 4 | import mysql from 'mysql2/promise'; 5 | import crypto from 'crypto'; 6 | 7 | import fs from 'fs-extra'; 8 | import path from 'path'; 9 | 10 | class MySQLLoader extends Loader { 11 | 12 | constructor(config) { 13 | super(config); 14 | this.db_config = { 15 | connectionLimit: 10, 16 | host:this.config._target.host, 17 | port:this.config._target.port, 18 | user:this.config._target.user, 19 | password:this.config._target.password, 20 | database:this.config._target.database 21 | }; 22 | this.pool = mysql.createPool(this.db_config); 23 | } 24 | 25 | async _get_connection() { 26 | return this.pool.getConnection(); 27 | } 28 | 29 | _escape_column_name(name) { 30 | return SqlString.escape(name.trim().toLowerCase().replace(/ /g, '_').replace(/'/g, '')).replace(/'/g, ''); 31 | } 32 | 33 | async _create_columns(table_name, columns) { 34 | table_name = SqlString.escapeId(table_name); 35 | let connection = await this._get_connection(); 36 | 37 | // build statement 38 | let statement = `ALTER TABLE ${table_name}`; 39 | columns.forEach((column, index) => { 40 | column = this._escape_column_name(column); 41 | statement += `ADD COLUMN \`${column}\` varchar(255),`; 42 | }) 43 | statement = statement.slice(0, -1); 44 | 45 | let result = await connection.query(statement); 46 | connection.close(); 47 | return result; 48 | } 49 | 50 | async _get_column_names_from_table(database, table_name) { 51 | database = SqlString.escape(database); 52 | table_name = SqlString.escape(table_name); 53 | let result = []; 54 | 55 | let connection = await this._get_connection(); 56 | 57 | let column_statement = `SELECT \`COLUMN_NAME\` 58 | FROM \`INFORMATION_SCHEMA\`.\`COLUMNS\` 59 | WHERE \`TABLE_SCHEMA\`= ${database} 60 | AND \`TABLE_NAME\`= ${table_name}`; 61 | 62 | let existence_statement = `SELECT EXISTS (${column_statement})`; 63 | let table_exists = await connection.query(existence_statement); 64 | 65 | // looks weird but works 66 | table_exists = !! + table_exists[0][0][Object.keys(table_exists[0][0])[0]]; 67 | 68 | // Return empty result if table does not exist 69 | if(!table_exists) { 70 | connection.close(); 71 | return result; 72 | } 73 | 74 | let column_names = await connection.query(column_statement); 75 | if(column_names.length < 1 || !Array.isArray(column_names[0])) { 76 | connection.close(); 77 | return result; 78 | } 79 | 80 | column_names[0].forEach((item, key) => { 81 | result.push(item.COLUMN_NAME); 82 | }) 83 | 84 | // close connection from pool 85 | connection.close(); 86 | 87 | return new Set(result); 88 | } 89 | 90 | async _create_table_from_object(obj, name = null) { 91 | 92 | let keys = []; 93 | if (!Array.isArray(obj) && typeof obj === 'object') { 94 | keys = Object.keys(obj); 95 | } else { 96 | keys = obj; 97 | } 98 | 99 | let column_string = ''; 100 | let hash = crypto.createHmac('sha256', crypto.randomBytes(32) 101 | .toString('hex') + '') 102 | .update(keys.length + '') 103 | .digest('hex'); 104 | 105 | if (name === null) { 106 | name = ('p' + hash); 107 | } 108 | 109 | // SQL tables can have a maximum of 32 chars 110 | name = name.replace(/\W/g, '') 111 | .slice(0, 32); 112 | 113 | // Add primary key 114 | column_string = '_id_midas INT NOT NULL AUTO_INCREMENT PRIMARY KEY,'; 115 | //column_string = ''; 116 | keys.forEach((key) => { 117 | // normalize column names (dot . is a reserves named) 118 | key = this._escape_column_name(key); 119 | // replace reserved word 120 | if(key === '_id_midas') { 121 | return; 122 | key = '_id_midas_'+hash.slice(0,4); 123 | } 124 | column_string += `\`${key}\`` + ' varchar(255),'; 125 | }); 126 | 127 | // chop off last , 128 | column_string = column_string.slice(0, -1); 129 | // create the connection 130 | let connection = await this._get_connection(); 131 | // query database 132 | await connection.execute(`CREATE TABLE IF NOT EXISTS ${name} (${column_string});`); 133 | // close connection 134 | connection.close(); 135 | 136 | return name; 137 | } 138 | 139 | // check https://stackoverflow.com/questions/15271202/mysql-load-data-infile-with-on-duplicate-key-update 140 | async _load_data_in_file_on_duplicate_key_update(data, table_name) { 141 | let connection = await this._get_connection(); 142 | 143 | // creat temporary table 144 | let temporary_table_name = crypto.createHmac('sha256', crypto.randomBytes(32) 145 | .toString('hex') + '') 146 | .digest('hex').slice(0, 32); 147 | let temporary_table_statement = `CREATE TEMPORARY TABLE ${SqlString.escapeId(temporary_table_name)} LIKE ${SqlString.escapeId(table_name)}`; 148 | 149 | await connection.execute(temporary_table_statement); 150 | 151 | // TODO drop indexes 152 | // ... 153 | 154 | // Load file into temporary CSV 155 | let file_path = await this._write_data_to_csv(data); 156 | let column_names = await this._get_column_names_from_table(this.config._target.database, table_name); 157 | 158 | // Load data infile 159 | let temp_c = [...column_names].map(column => '`' + this._escape_column_name(column) + '`'); 160 | let no_id = ''; 161 | 162 | // Check if data contains the _id_midas property 163 | if(data.length > 0 && typeof data[0]['_id_midas'] === 'undefined') { 164 | temp_c = temp_c.filter(e => e !== '`_id_midas`'); 165 | no_id = 'SET _id_midas = NULL;' 166 | } 167 | 168 | //temp_c.splice(1,1); 169 | let infile_statement = `LOAD DATA LOCAL INFILE '${file_path}' INTO TABLE ${SqlString.escapeId(temporary_table_name)} 170 | FIELDS TERMINATED BY ',' 171 | OPTIONALLY ENCLOSED BY '"' 172 | LINES TERMINATED BY '\r\n' 173 | IGNORE 1 LINES 174 | (${temp_c.join(',')}) 175 | ${no_id}`; 176 | await connection.query(infile_statement); 177 | 178 | // Insert data 179 | let insert_statement = `INSERT INTO ${SqlString.escapeId(table_name)} 180 | SELECT * FROM ${SqlString.escapeId(temporary_table_name)} 181 | ON DUPLICATE KEY UPDATE ${temp_c.map(column => `${column} = VALUES(${column})` ).join(',')};` 182 | await connection.execute(insert_statement); 183 | 184 | // Drop temporary table 185 | let drop_temp_table_statement = `DROP TEMPORARY TABLE ${SqlString.escapeId(temporary_table_name)}`; 186 | await connection.execute(drop_temp_table_statement); 187 | 188 | // Remove temporary file 189 | await fs.remove(file_path); 190 | 191 | // Close connection 192 | connection.close(); 193 | } 194 | 195 | async _write_data_to_csv(data) { 196 | 197 | const json2csv = require('json2csv').parse; 198 | try { 199 | const data_string = json2csv(data, {flatten:true, eol:'\r\n'}); 200 | let random_hash = crypto.createHmac('sha256', crypto.randomBytes(32) 201 | .toString('hex') + '') 202 | .digest('hex'); 203 | let file_path = __dirname + path.sep + 'TEMP_MIDAS_TABLE_FILE__' + random_hash; 204 | let result = await fs.outputFile(file_path, data_string); 205 | return file_path; 206 | } catch (err) { 207 | return Promise.resolve(err); 208 | } 209 | } 210 | 211 | async load(data) { 212 | 213 | let result = false; 214 | let flattened = flat(data[0]); 215 | let table_name = ''; 216 | let keys = new Set(Object.keys(flattened)); 217 | let columns_to_create = []; 218 | let alter_columns_result = null; 219 | let column_names = await this._get_column_names_from_table(this.config._target.database, this.config._target.table); 220 | 221 | // check if it is required to create a new table 222 | if(column_names.length === 0) { 223 | table_name = await this._create_table_from_object(flattened, this.config._target.table); 224 | result = true; 225 | } 226 | // Add alter base table 227 | else { 228 | keys = new Set([...keys].map(x => this._escape_column_name(x))); 229 | columns_to_create = new Set([...keys].filter(x => !column_names.has(x))); 230 | alter_columns_result = await this._create_columns(this.config._target.table, columns_to_create); 231 | table_name = this.config._target.table; 232 | result = true; 233 | } 234 | 235 | // Load actual data 236 | await this._load_data_in_file_on_duplicate_key_update(data, table_name); 237 | 238 | return result; 239 | } 240 | 241 | } 242 | 243 | export { MySQLLoader as default} -------------------------------------------------------------------------------- /source/Loader/XLSXLoader.js: -------------------------------------------------------------------------------- 1 | import Loader from './Loader'; 2 | 3 | // Utils 4 | import fs from 'fs-extra'; 5 | import flatten from 'flat'; 6 | import {promisify} from 'util'; 7 | 8 | // XLSX handler 9 | import XLSXWriter from 'xlsx-writestream'; 10 | 11 | 12 | class XLSXLoader extends Loader { 13 | 14 | constructor(config) { 15 | super(config); 16 | } 17 | 18 | load(data) { 19 | let _data = []; 20 | 21 | data.forEach((row, index) => { 22 | _data.push(flatten(row)); 23 | }); 24 | 25 | let writer = new XLSXWriter(this.config._target.path, {} /* options */); 26 | let writerPromise = promisify(XLSXWriter.write); 27 | writerPromise(this.config._target.path, _data); 28 | 29 | return Promise.resolve(true); 30 | } 31 | 32 | } 33 | 34 | export { XLSXLoader as default} -------------------------------------------------------------------------------- /source/Utils/ArrayUtils.js: -------------------------------------------------------------------------------- 1 | class ArrayUtils { 2 | 3 | static arrayify(array) { 4 | if(!Array.isArray(array)) { 5 | return [array]; 6 | } 7 | return array; 8 | } 9 | 10 | 11 | static arrayObjectify(array) { 12 | var keys = array.shift(); 13 | var objects = array.map(function(values) { 14 | return keys.reduce(function(o, k, i) { 15 | o[k] = values[i]; 16 | return o; 17 | }, {}); 18 | }); 19 | return objects; 20 | } 21 | 22 | } 23 | 24 | export { ArrayUtils as default} -------------------------------------------------------------------------------- /source/Utils/ClassLoader.js: -------------------------------------------------------------------------------- 1 | class ClassLoader { 2 | 3 | static load_class(path) { 4 | return require(path); 5 | } 6 | 7 | static load_classes(names) { 8 | let result = []; 9 | names.forEach((_class, index) => { 10 | result.push(this.load_class(_class.path+'/'+_class.name)); 11 | }); 12 | return result; 13 | } 14 | 15 | } 16 | 17 | export { ClassLoader as default} -------------------------------------------------------------------------------- /source/Utils/RateLimiter.js: -------------------------------------------------------------------------------- 1 | class RateLimiter { 2 | 3 | static async async_stall(rate = -1, time_unit = 's', stall_time = 0) { 4 | 5 | let t_factor = 1000; 6 | 7 | if(time_unit == 's') { 8 | t_factor = 1000; 9 | } else if (time_unit == 'm') { 10 | t_factor = 1000 * 60; 11 | } else if (t_factor == 'h') { 12 | t_factor = 1000 * 60 * 60; 13 | } 14 | 15 | if(rate == -1) { 16 | stall_time = 0 17 | return Promise.resolve(true); 18 | } else { 19 | stall_time = t_factor / rate; 20 | } 21 | 22 | await new Promise(resolve => setTimeout(resolve, stall_time)); 23 | } 24 | } 25 | 26 | export { RateLimiter as default} -------------------------------------------------------------------------------- /source/Utils/TypeChecker.js: -------------------------------------------------------------------------------- 1 | class TypeChecker { 2 | static isNumber(val) { 3 | return /^\d+$/.test(val); 4 | } 5 | } 6 | 7 | export {TypeChecker as default} -------------------------------------------------------------------------------- /source/Wizard/wizard.js: -------------------------------------------------------------------------------- 1 | // Utils 2 | import fs from 'fs-extra'; 3 | import RecursiveIterator from 'recursive-iterator'; 4 | import camelCase from 'camelcase'; 5 | import TypeChecker from './../Utils/TypeChecker'; 6 | 7 | // Utils 8 | import ArrayUtils from './../Utils/ArrayUtils'; 9 | import csvjson from 'csvjson'; 10 | import XLSX from 'xlsx'; 11 | import read_json_sync from 'read-json-sync'; 12 | import jp from 'jsonpath'; 13 | 14 | import inquirer from 'inquirer'; 15 | import colors from 'colors'; 16 | import prettyjson from 'prettyjson'; 17 | 18 | 19 | class Wizard { 20 | 21 | _transform_to_config_object(object) { 22 | let config = {source: {}, target:{}, enrichers:[]}; 23 | let rate_limit = {number_of_requests: -1, time_window: 's'}; 24 | 25 | // Source 26 | config.name = object.name; 27 | config.source[object.source_type] = {}; 28 | config.source[object.source_type].path = object.source_path; 29 | 30 | // Enricher 31 | let enricher_name = this._has_custom_enricher(object) ? camelCase(object.custom_enricher) : camelCase(object.enricher); 32 | 33 | // check if rate limit is set 34 | if(typeof object.rate_limit !== 'undefined') { 35 | let limits = object.rate_limit.split('/'); 36 | 37 | if(['s', 'm', 'h'].indexOf(limits[1]) > -1) { 38 | rate_limit.number_of_requests = limits[0]; 39 | rate_limit.time_window = limits[1]; 40 | } 41 | } 42 | 43 | if(object.enricher !== 'no') { 44 | config.enrichers = [{ 45 | name: enricher_name, 46 | path: this._resolve_enricher_parent_path(enricher_name), 47 | config: { 48 | input_parameter: object.source_object_path, 49 | target_property: object.target_property_name, 50 | rate_limit: rate_limit 51 | } 52 | }]; 53 | } else { 54 | config.enrichers = [{ 55 | name: "NAME_OF_YOUR_ENRICHER", 56 | path: "ABSOLUTE_PATH_TO_YOUR_ENRICHER", 57 | config: { 58 | input_parameter: object.source_object_path, 59 | target_property: object.target_property_name, 60 | rate_limit: rate_limit 61 | } 62 | }]; 63 | } 64 | 65 | 66 | // Add configs for pre-defined enricher 67 | if(!this._has_custom_enricher(object) && enricher_name === 'openWeather') { 68 | config.enrichers[0].config['api_key'] = object.enricher_config_api_key; 69 | } 70 | 71 | // Target 72 | if(object.target_type === 'alter source') { 73 | config.target[object.source_type] = {}; 74 | config.target[object.source_type].path = object.source_path; 75 | } else { 76 | // ONLY TARGET FOR ALPHA 77 | config.target[object.source_type] = {}; 78 | config.target[object.source_type].path = object.source_path; 79 | 80 | //config.target[object.target_type] = {}; 81 | //config.target[object.target_type].path = object.target_path; 82 | } 83 | 84 | return config; 85 | } 86 | 87 | _has_custom_enricher(answers) { 88 | return typeof answers.custom_enricher !== 'undefined'; 89 | } 90 | 91 | _resolve_enricher_parent_path(name) { 92 | let base_path = __dirname + '/../Enrichers/'; 93 | if(name === 'openWeather') { 94 | return base_path; 95 | } 96 | return process.cwd(); 97 | } 98 | 99 | _create_enricher(name) { 100 | name = camelCase(name); 101 | const enricher_template = ` 102 | "use strict"; 103 | var Enricher = class Enricher { 104 | 105 | constructor(rp, inputData, config) { 106 | //npm request-promise is used for handling requests 107 | //see: https://github.com/request/request-promise 108 | this.rp = rp; 109 | //loads inputData of the target file specified in the source object path in your config 110 | this.inputData = inputData; 111 | //loads config for this enrichment 112 | this.config = config; 113 | } 114 | 115 | getConfig() { 116 | return this.config; 117 | } 118 | 119 | getName() { 120 | return 'Enricher'; 121 | } 122 | 123 | setData(inputData) { 124 | this.inputData = inputData; 125 | } 126 | 127 | process(inputData) { 128 | 129 | if (typeof inputData != 'undefined' && inputData != null) { 130 | this.inputData = inputData; 131 | } 132 | 133 | // Do stuff here 134 | 135 | 136 | return Promise.resolve(this.inputData); 137 | } 138 | 139 | // eof class 140 | }; 141 | 142 | module.exports.Enricher = Enricher; 143 | `; 144 | 145 | let new_enricher_source = enricher_template.replace(/Enricher/g, name); 146 | let enricher_path = process.cwd() + '/' + name + '.js'; 147 | fs.writeFileSync(enricher_path, new_enricher_source); 148 | return enricher_path; 149 | } 150 | 151 | _process_answers(answers) { 152 | let config_object = this._transform_to_config_object(answers); 153 | let config_string = JSON.stringify(config_object, null, '\t'); 154 | let config_save_path = process.cwd()+'/'+config_object.name.toLowerCase().replace(/\s/g, "_")+'_midas.json'; 155 | 156 | if(this._has_custom_enricher(answers)) { 157 | this._create_enricher(answers.custom_enricher); 158 | } 159 | 160 | let config_save_state = fs.outputJson(config_save_path, config_object, {spaces:'\t'}); 161 | config_save_state.then(() => { 162 | console.log(''); 163 | console.log('--------------------------------------------------------------'); 164 | console.log('✅ New enrichment job successfully created '.green.bold); 165 | console.log(''); 166 | console.log(' ⚠️ You can freely customize your enrichment job using your own enrichers and config'.cyan); 167 | console.log('Check out https://midas.science/guide'.cyan); 168 | console.log(''); 169 | 170 | // Notify user that s/he has to add an enricher themself 171 | if(!this._has_custom_enricher(answers)) { 172 | console.log(''); 173 | console.log(' ⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️'); 174 | console.log('Currently you didn\'t specify any enricher for your process'.bold); 175 | console.log('Create or add one before start your enrichement process'.bold); 176 | console.log(' ⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️'); 177 | console.log(''); 178 | console.log(''); 179 | } 180 | 181 | console.log('Start enrichment process via '.green.bold); 182 | console.log('midas enrich -c "'+config_save_path+'"'); 183 | console.log('--------------------------------------------------------------'); 184 | console.log(''); 185 | }).catch((err) => console.log('Something went wrong')); 186 | } 187 | 188 | start() { 189 | 190 | let questions = inquirer 191 | .prompt([ 192 | { 193 | type: 'input', 194 | name: 'name', 195 | message: "Chose a name for your enrichment process:", 196 | }, 197 | { 198 | type: 'list', 199 | name: 'source_type', 200 | message: 'What\'s your data source?', 201 | choices: ['CSV', 'JSON', 'XLSX'], 202 | filter: function(val) { 203 | return val.toLowerCase(); 204 | } 205 | }, 206 | { 207 | when: function(response) { 208 | return response.source_type === 'csv'; 209 | }, 210 | type: 'input', 211 | name: 'csv_delimiter', 212 | message: "What\'s the delimiter of your CSV file?", 213 | }, 214 | { 215 | when: function(response) { 216 | return true; 217 | }, 218 | type: 'input', 219 | name: 'source_path', 220 | message: "Where is your file located? (Enter the absolute path)", 221 | validate: function(value) { 222 | if (fs.existsSync(value)) { 223 | return true; 224 | } 225 | return 'File not found :/'; 226 | } 227 | }, 228 | { 229 | when: function(response) { 230 | return true; 231 | }, 232 | type: 'input', 233 | name: 'source_object_path', 234 | message: function(response) { 235 | if(response.json_path_validate === 'n') { 236 | return 'Just try again'; 237 | } 238 | else { 239 | return 'Define the JSON path of your input parameter'; 240 | } 241 | }, 242 | validate: function(value, response) { 243 | 244 | 245 | // Extract data schema 246 | let data_set = null; 247 | if(response.source_type === 'xlsx') { 248 | let wb = XLSX.readFile(response.source_path, {type: "file"}); 249 | data_set = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]], {raw:false, header:1}); 250 | data_set = ArrayUtils.arrayObjectify(data_set); 251 | } else if(response.source_type === 'csv') { 252 | 253 | let options = { 254 | delimiter : response.csv_delimiter, 255 | quote : '"' 256 | }; 257 | 258 | let _data = fs.readFileSync(response.source_path, { encoding : 'utf8'}); 259 | data_set = csvjson.toObject(_data, options); 260 | } else if(response.source_type === 'json') { 261 | data_set = read_json_sync(response.source_path); 262 | } 263 | 264 | let jp_source_data = null; 265 | 266 | try { 267 | jp_source_data = jp.nodes(data_set, value); 268 | } catch(e) { 269 | return 'Please enter a valid json path'; 270 | } 271 | 272 | let example_data_point = 'Not found'; 273 | if(jp_source_data.length > 0 && typeof jp_source_data[0].value !== 'undefined') { 274 | example_data_point = jp_source_data[0].value; 275 | } else { 276 | return 'Please enter a valid json path'; 277 | } 278 | 279 | let example_data_point_type = (typeof example_data_point).bold; 280 | if(Array.isArray(example_data_point)) { 281 | example_data_point_type = 'array'.bold; 282 | } 283 | 284 | console.log(''); 285 | console.log(''); 286 | console.log('This will be the input for your enricher:'); 287 | console.log('Example (first row / data point):'); 288 | console.log(''); 289 | console.log('Type ' + example_data_point_type); 290 | if(typeof example_data_point === 'object') { 291 | console.log(prettyjson.render(example_data_point)); 292 | } else { 293 | console.log(example_data_point.blue); 294 | } 295 | console.log(''); 296 | console.log(''); 297 | 298 | 299 | return true; 300 | } 301 | }, 302 | 303 | { 304 | type: 'list', 305 | name: 'enricher', 306 | message: 'Do you want to create a new enricher?', 307 | choices: ['Yes', 'No'], 308 | filter: function(val) { 309 | let return_value = val; 310 | if(val === 'Yes') { 311 | return_value = 'custom'; 312 | } 313 | return camelCase(return_value); 314 | } 315 | }, 316 | 317 | { 318 | when: function(response) { 319 | return response.enricher === 'custom'; 320 | }, 321 | type: 'input', 322 | name: 'custom_enricher', 323 | message: 'Specify a name for your new enricher', 324 | filter: function(val) { 325 | return val; 326 | } 327 | }, 328 | 329 | { 330 | when: function(response) { 331 | return true; 332 | }, 333 | type: 'input', 334 | name: 'target_property_name', 335 | message: "Name of the enriched property?" 336 | }, 337 | 338 | { 339 | when: function(response) { 340 | return true; 341 | }, 342 | type: 'list', 343 | name: 'rate_limit_yesno', 344 | message: "Do you need rate limiting?", 345 | choices: ['Yes', 'No'], 346 | filter: function(val) { 347 | return val.toLowerCase(); 348 | } 349 | }, 350 | 351 | { 352 | when: function(response) { 353 | return response.rate_limit_yesno === 'yes'; 354 | }, 355 | type: 'input', 356 | name: 'rate_limit', 357 | message: "Define your rate limit via NUMBER_OF_REQUESTS/TIME_UNIT (e.g. 100/s would mean midas will make a maximum of 100 requests per second)", 358 | filter: function(val) { 359 | return val.toLowerCase(); 360 | }, 361 | validate: function(value, response) { 362 | let split = value.split('/'); 363 | 364 | if(split.length != 2) { 365 | return false; 366 | } 367 | 368 | if(['s', 'm', 'h'].indexOf(split[1]) <= -1) { 369 | return false; 370 | } 371 | 372 | if(/^\d+$/.test(split[0]) == false) { 373 | return false; 374 | } 375 | 376 | return true; 377 | } 378 | } 379 | 380 | ]); 381 | 382 | 383 | questions.then(answers => { 384 | this._process_answers(answers); 385 | } 386 | ); 387 | // eof 388 | } 389 | 390 | } 391 | 392 | export { Wizard as default } -------------------------------------------------------------------------------- /source/index.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | import Config from './Config/Config'; 4 | import Midas from './midas'; 5 | import Wizard from './Wizard/Wizard'; 6 | 7 | import fs from 'fs'; 8 | import RecursiveIterator from 'recursive-iterator'; 9 | import read_json_sync from 'read-json-sync'; 10 | 11 | // Loader 12 | import JSONLoader from './Loader/JSONLoader'; 13 | 14 | // CMD Args 15 | import inquirer from 'inquirer'; 16 | import command_line_args from 'command-line-args'; 17 | const main_definitions = [ 18 | { name: 'command', defaultOption: true } 19 | ]; 20 | 21 | const main_options = command_line_args(main_definitions, { stopAtFirstUnknown: true }); 22 | const argv = main_options._unknown || []; 23 | 24 | // Enricher 25 | if (main_options.command === 'enrich') { 26 | 27 | const merge_definitions = [ 28 | { name: 'config', type: String, alias: 'c' } 29 | ] 30 | const merge_options = command_line_args(merge_definitions, { argv }); 31 | 32 | let midas = new Midas(new Config(merge_options.config).get_config_object_sync()); 33 | midas.touch(); 34 | } 35 | 36 | // Scaffolding 37 | if (main_options.command === 'init') { 38 | 39 | let wizard = new Wizard(); 40 | wizard.start(); 41 | 42 | } -------------------------------------------------------------------------------- /source/midas.js: -------------------------------------------------------------------------------- 1 | // Utils 2 | import ClassLoader from './Utils/ClassLoader'; 3 | import ArrayUtils from './Utils/ArrayUtils'; 4 | import object_path from 'object-path'; 5 | import colors from 'colors'; 6 | import RecursiveIterator from 'recursive-iterator'; 7 | import jp from 'jsonpath'; 8 | import RateLimiter from './Utils/RateLimiter'; 9 | 10 | // Extractors 11 | import JSONExtractor from './Extractor/JSONExtractor'; 12 | import CSVExtractor from './Extractor/CSVExtractor'; 13 | import XLSXExtractor from './Extractor/XLSXExtractor'; 14 | import GoogleSpreadSheetExtractor from './Extractor/GoogleSpreadSheetExtractor'; 15 | import MySQLExtractor from './Extractor/MySQLExtractor'; 16 | 17 | // Loaders 18 | import JSONLoader from './Loader/JSONLoader'; 19 | import CSVLoader from './Loader/CSVLoader'; 20 | import XLSXLoader from './Loader/XLSXLoader'; 21 | import MySQLLoader from './Loader/MySQLLoader'; 22 | // import GoogleSpreadSheetLoader from './Loader/GoogleSpreadSheetLoader'; 23 | 24 | import flat from 'flat'; 25 | 26 | 27 | class Midas { 28 | 29 | constructor(config) { 30 | this.config = config; 31 | this.config._source = this.config.source[Object.keys(this.config.source)[0]]; 32 | this.config._source.type = Object.keys(this.config.source)[0]; 33 | this.config._target = this.config.target[Object.keys(this.config.target)[0]]; 34 | this.config._target.type = Object.keys(this.config.target)[0]; 35 | this.rp = null; 36 | } 37 | 38 | _report_status(status) { 39 | console.log(status.message); 40 | } 41 | 42 | _chain_enrichers(enrichers, data) { 43 | var self = this; 44 | async function chain_enricher_promises(promises, self) { 45 | var result = []; 46 | let enrichment_target = null; 47 | let intermediate_result = null; 48 | let path_expression = ''; 49 | let parent_object_path = ''; 50 | let parent = {}; 51 | 52 | for (let promise of promises) { 53 | 54 | let jp_source_data = jp.nodes(data, promise.getConfig().input_parameter); 55 | let jp_source_data_2 = jp.nodes(data, '$..price'); 56 | 57 | let enriched_property_name = promise.getConfig().target_property; 58 | for(let node of jp_source_data) { 59 | 60 | let node_path = node.path.join('.').substring(2); // Remove leading $. from path string for object path 61 | enrichment_target = node.value; 62 | 63 | promise.setData(enrichment_target); 64 | intermediate_result = enrichment_target; 65 | intermediate_result = await promise.process(intermediate_result); 66 | let deep_copied_intermediate_result = JSON.parse(JSON.stringify(intermediate_result)); 67 | 68 | // Check node type 69 | if(typeof node.value !== 'object' && !Array.isArray(node.value)) { 70 | path_expression = jp.stringify(node.path); 71 | let node_path_deep_copy = JSON.parse(JSON.stringify(node.path)); 72 | //node_path_deep_copy.pop(); 73 | node_path_deep_copy.shift(); 74 | parent_object_path = node_path_deep_copy.join('.'); 75 | 76 | // get parent and check if it's an array 77 | parent = jp.parent(data, path_expression); 78 | if(Array.isArray(parent)) { 79 | let enriched_intermediate_object = {value: node.value}; 80 | enriched_intermediate_object[enriched_property_name] = deep_copied_intermediate_result; 81 | object_path.set(data, parent_object_path, enriched_intermediate_object); 82 | } else { 83 | parent[enriched_property_name] = deep_copied_intermediate_result; 84 | } 85 | } 86 | 87 | if(typeof node.value === 'object' && !Array.isArray(node.value)) { 88 | object_path.set(data, node_path + '.' + enriched_property_name, deep_copied_intermediate_result); 89 | } 90 | 91 | if(Array.isArray(node.value)) { 92 | path_expression = jp.stringify(node.path); 93 | parent = jp.parent(data, path_expression); 94 | parent[enriched_property_name] = deep_copied_intermediate_result; 95 | } 96 | 97 | // check if there is some kind of rate limit defined within the configuration 98 | if(typeof promise.getConfig().rate_limit !== 'undefined' && typeof promise.getConfig().rate_limit !== 'undefined') { 99 | await RateLimiter.async_stall(promise.getConfig().rate_limit.number_of_requests, promise.getConfig().rate_limit.time_window); 100 | } 101 | } 102 | 103 | } 104 | 105 | return {data: result}; 106 | } 107 | return chain_enricher_promises(enrichers, self); 108 | } 109 | 110 | _instantiate_enricher_classes(enrichers, enricher_classes, data) { 111 | let instances = []; 112 | enrichers.forEach((enricher, index) => { 113 | instances.push(new enricher_classes[index][enricher.name](this._enricher_add_utils(), data, enrichers[index].config)); 114 | }); 115 | return instances; 116 | } 117 | 118 | _enricher_add_utils() { 119 | let rp = require('request-promise'); 120 | return rp; 121 | } 122 | 123 | _extractor() { 124 | let extractor_type = this.config._source.type.toLowerCase(); 125 | 126 | if(extractor_type === 'json') { 127 | return new JSONExtractor(this.config); 128 | } 129 | 130 | if(extractor_type === 'csv') { 131 | return new CSVExtractor(this.config); 132 | } 133 | 134 | if(extractor_type === 'xlsx') { 135 | return new XLSXExtractor(this.config); 136 | } 137 | 138 | if(extractor_type === 'googlespreadsheet') { 139 | return new GoogleSpreadSheetExtractor(this.config); 140 | } 141 | 142 | if(extractor_type === 'mysql') { 143 | return new MySQLExtractor(this.config); 144 | } 145 | 146 | } 147 | 148 | _loader() { 149 | let loader_type = this.config._target.type.toLowerCase(); 150 | 151 | if(loader_type === 'json') { 152 | return new JSONLoader(this.config); 153 | } 154 | 155 | if(loader_type === 'csv') { 156 | return new CSVLoader(this.config); 157 | } 158 | 159 | if(loader_type == 'xlsx') { 160 | return new XLSXLoader(this.config); 161 | } 162 | 163 | if(loader_type == 'mysql') { 164 | return new MySQLLoader(this.config); 165 | } 166 | 167 | } 168 | 169 | _extract_data() { 170 | return this._extractor().get_data_promise(); 171 | }; 172 | 173 | _match_path(path_generic, path_instance) { 174 | let path_generic_split = path_generic.split('.'); 175 | let path_instance_split = path_instance.split('.'); 176 | 177 | var isNumber = function(val) { 178 | return /^\d+$/.test(val); 179 | } 180 | 181 | // Remove starting $. 182 | path_generic_split.shift(); 183 | 184 | 185 | // Compare paths 186 | let result = true; 187 | path_generic_split.forEach((path_element, index) => { 188 | if(path_element === '[:]') { 189 | if(!isNumber(path_instance_split[index])) { 190 | result = false; 191 | } 192 | } else { 193 | result = result && (path_instance_split[index] === path_element) && (path_generic_split.length == path_instance_split.length); 194 | } 195 | }); 196 | 197 | return result; 198 | } 199 | 200 | 201 | touch() { 202 | 203 | // LOG 204 | this._report_status({message: '👑👑 midas data enrichment process started'.yellow.bold}); 205 | this._report_status({message: this.config.name + ' || ' + this._extractor().get_type() + '->' + this._loader().get_type() + '\n'}); 206 | 207 | let data_promise = this._extract_data(); 208 | 209 | // TODO: Fix hardcoded path 210 | let enricher_classes = ClassLoader.load_classes(this.config.enrichers); 211 | let enrichers = this._instantiate_enricher_classes(this.config.enrichers, enricher_classes, {}); 212 | 213 | // LOG 214 | this._report_status({message: '🔗🔗 Enrichment chain'.bold + ''}); 215 | let status_message = ''; 216 | this.config.enrichers.forEach((enricher, index) => { 217 | if(index < (this.config.enrichers.length - 1)) { 218 | status_message += enricher.name + ' -> '; 219 | } else { 220 | status_message += enricher.name; 221 | } 222 | }); 223 | status_message = status_message.split(' -> ').join(' -> '); 224 | this._report_status({message: status_message}); 225 | 226 | 227 | return data_promise.then((data_set) => { 228 | 229 | data_set = ArrayUtils.arrayify(data_set); 230 | let enrichers_chain = []; 231 | let enrichment = enrichers_chain.push(this._chain_enrichers(enrichers, data_set)); 232 | 233 | return Promise.all(enrichers_chain) 234 | .then(enriched_items => { 235 | 236 | let result = this._loader().load(data_set); 237 | return result.then((res) => { 238 | // LOG 239 | this._report_status({message: '\n✅ midas data enrichment process done'.green.bold}); 240 | return Promise.resolve(true); 241 | }); 242 | }).catch((err) => { 243 | console.log(err); 244 | console.log('Something went wrong'.red); 245 | return Promise.resolve(false); 246 | }); 247 | }); 248 | // end of function 249 | } 250 | 251 | } 252 | 253 | export { Midas as default} --------------------------------------------------------------------------------