|
| 1 | +const fs = require('fs'); |
| 2 | +const papa = require('papaparse'); |
| 3 | +const AWS = require('aws-sdk'); |
| 4 | +const file = fs.createReadStream('.csv'); |
| 5 | + |
| 6 | +// * Usar perfil de configuracion, por defecto se usa "default" |
| 7 | +const credentials = new AWS.SharedIniFileCredentials({ profile: 'default' }); |
| 8 | +AWS.config.update({ region: 'us-east-2', credentials }); |
| 9 | + |
| 10 | +const ddb = new AWS.DynamoDB({ apiVersion: '2012-08-10' }); |
| 11 | + |
| 12 | +const TableName = ""; |
| 13 | + |
| 14 | +// * Parsea csv a json |
| 15 | +papa.parse(file, { |
| 16 | + header: true, |
| 17 | + skipEmptyLines: true, |
| 18 | + complete: onComplete |
| 19 | +}); |
| 20 | + |
| 21 | +async function onComplete(results) { |
| 22 | + const array = results.data; |
| 23 | + const dynamoItems = array.map(item => { |
| 24 | + /* |
| 25 | + * Necesitamos obtener los valores y llaves de cada item, |
| 26 | + * para luego identifar el tipo de dato del valor y crear el objeto |
| 27 | + * con el schema de Dynamo: { PutRequest: { Item: dynamoSchema } } |
| 28 | + */ |
| 29 | + let dynamoSchema = Object.entries(item).reduce((acc, [key, value]) => { |
| 30 | + let type = isNaN(value) ? 'S' : 'N'; |
| 31 | + |
| 32 | + let cleanKey = key.replace(/\s/g, ''); |
| 33 | + |
| 34 | + return ({ |
| 35 | + ...acc, [cleanKey]: { |
| 36 | + [type]: value |
| 37 | + } |
| 38 | + }) |
| 39 | + }, {}); |
| 40 | + return { PutRequest: { Item: dynamoSchema } } |
| 41 | + }); |
| 42 | + |
| 43 | + const chunks = chunkArray(dynamoItems, 25); |
| 44 | + |
| 45 | + console.log('=== chunks size ===', chunks.length); |
| 46 | + |
| 47 | + for (let i = 0; i < chunks.length; i++) { |
| 48 | + try { |
| 49 | + const dynamoData = { [TableName]: chunks[i] } |
| 50 | + const params = { RequestItems: dynamoData } |
| 51 | + await write2dynamo(params) |
| 52 | + console.log('=== chunk written ===', i); |
| 53 | + } catch (error) { |
| 54 | + console.log("Error: ", error) |
| 55 | + // * Ciclamos la información del chunk |
| 56 | + for (let j = 0; j < chunks[j].length; j++) { |
| 57 | + console.log(chunks[i][j]?.PutRequest); |
| 58 | + } |
| 59 | + } |
| 60 | + } |
| 61 | +} |
| 62 | + |
| 63 | +// * Parte el array en chunks de tamaño 'size' |
| 64 | +function chunkArray(arr, size) { |
| 65 | + return Array.from({ length: Math.ceil(arr.length / size) }, (v, i) => arr.slice(i * size, i * size + size)); |
| 66 | +} |
| 67 | + |
| 68 | +// * Promisifica la escritura en DynamoDB |
| 69 | +function write2dynamo(params) { |
| 70 | + return new Promise((resolve, reject) => { |
| 71 | + ddb.batchWriteItem(params, function (err, data) { |
| 72 | + if (err) { |
| 73 | + return reject(err); |
| 74 | + } else { |
| 75 | + console.log("Success", data); |
| 76 | + return resolve(data); |
| 77 | + } |
| 78 | + }); |
| 79 | + }); |
| 80 | +} |
0 commit comments