-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
228 lines (180 loc) · 7.37 KB
/
main.js
File metadata and controls
228 lines (180 loc) · 7.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
const fs = require('fs');
const util = require('util');
const readline = require('node:readline');
const papa = require('papaparse');
const AWS = require('aws-sdk');
const file = fs.createReadStream('csv/{file-name}.csv');
// * Usar perfil de configuración, por defecto se usa "default"
const credentials = new AWS.SharedIniFileCredentials({ profile: 'default' });
AWS.config.update({ region: 'us-east-2', credentials });
// * Inicializamos el servicio de DynamoDB
const ddb = new AWS.DynamoDB({ apiVersion: '2012-08-10' });
// * Nombre de la tabla en DynamoDB
const tableName = "{table-name}";
// * Verifica si hay duplicados en la data
const checkDuplicates = (data) => {
let setCheck = new Set();
let set = new Set();
for (let i = 0; i < data.length; i++) {
if (setCheck.has(data[i].InternalID)) {
console.log('============================================================');
console.log(`=== Duplicado en la posición ${i} del arreglo ===`, data[i]);
console.log('============================================================\n');
} else {
setCheck.add(data[i].InternalID);
set.add(data[i]);
}
}
console.log('=== Tamaño original del arreglo ===', data.length);
console.log('=== Tamaño del arreglo ya limpiado ===', setCheck.size);
console.log('=== Numero de duplicados ===', data.length - setCheck.size);
return [...set];
}
// * Parte el array en chunks de tamaño especificado
const chunkArray = (arr, size) => {
return Array.from({ length: Math.ceil(arr.length / size) }, (v, i) => arr.slice(i * size, i * size + size));
}
// * Convierte en promesa la escritura en DynamoDB
const write2Dynamo = (params) => {
return new Promise((resolve, reject) => {
ddb.batchWriteItem(params, function (err, data) {
if (err) {
console.log("=== Error al guardar en DynamoDB ===", err);
return reject(err);
} else {
console.log("=== Guardado en DynamoDB ===", data);
return resolve(data);
}
});
});
}
// * Procesa la data del csv
const processData = async (results, save) => {
// * Verificamos si hay duplicados en el arreglo
const array = checkDuplicates(results.data);
const dynamoItems = array.map(item => {
/*
* Necesitamos obtener los valores y llaves de cada item,
* para luego identificar el tipo de dato del valor y crear el objeto
* con el schema de Dynamo: { PutRequest: { Item: dynamoSchema } }
*/
let dynamoSchema = Object.entries(item).reduce((acc, [key, value]) => {
let type = '';//isNaN(value) ? 'S' : 'N';
let cleanKey = key.replace(/\s/g, '');
return ({
...acc, [cleanKey]: {
[type]: value
}
})
}, {});
return { PutRequest: { Item: dynamoSchema } }
});
const chunks = chunkArray(dynamoItems, 25);
let registers = 0;
let error = 0;
for (let i = 0; i < chunks.length; i++) {
try {
console.clear();
console.log('\n============================================================\n');
console.log('=== Numero de items ===', dynamoItems.length);
console.log('=== Registros guardados ===', registers += chunks[i].length);
console.log('=== Tamaño del chunk ===', chunks[i].length);
console.log('=== Chunks guardados ===', `${i + 1} / ${chunks.length}`);
console.log('=== Errores de chunk ===', error);
for (let j = 0; j < chunks[i].length; j++) {
console.log(`\n=== Información del chunk ${i + 1} ===`);
console.log(`=== Numero de item en el chunk: ${j + 1} ===`);
console.log(`=== Total de keys del item: ${Object.keys(chunks[i][j]?.PutRequest.Item).length} ===`);
console.log(`=== ${Object.keys(chunks[i][j]?.PutRequest.Item)} ===`);
console.log('\n=== Información del item ===', chunks[i][j]?.PutRequest.Item);
}
console.log('\n============================================================\n');
if (save) {
await write2Dynamo({
RequestItems: {
[tableName]: chunks[i]
}
});
}
} catch (error) {
console.log('\n============================================================\n');
console.log(`Error en el chunk ${i + 1}:`, error);
error++;
// * Ciclamos la información del chunk
for (let j = 0; j < chunks[j].length; j++) {
console.log(chunks[i][j]?.PutRequest);
}
console.log('\n============================================================\n');
return;
}
}
console.log('=== Finalizando proceso y guardado de logs ===');
}
// * Pregunta si se desea guardar en DynamoDB
const question = (results) => {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
rl.question(`¿Desea 1)guardar los registros en DynamoDB o solo 2)generar el log? (1/2): `, async (answer) => {
const save = answer.toLowerCase();
if (save !== '1' && save !== '2') {
console.log('=== Opción no válida, finalizando proceso ===');
return rl.close();
}
await processData(results, save === '1');
return rl.close();
});
}
// * Inicializa el log
const initLog = () => {
return new Promise((resolve, reject) => {
try {
// * Verifica si existe la carpeta logs
if (!fs.existsSync(__dirname + '/logs')) {
fs.mkdirSync(__dirname + '/logs');
}
// * Crea el archivo de log
const log_file = fs.createWriteStream(__dirname + `/logs/${new Date().getTime()}.log`, { flags: 'w' });
const log_stdout = process.stdout;
// * Sobre escribimos la función console.log
console.log = (d, ...args) => {
log_file.write(util.format(d, ...args) + '\n');
log_stdout.write(util.format(d, ...args) + '\n');
};
console.log('=== Iniciando proceso y guardado de logs ===\n');
return resolve();
} catch (error) {
return reject(error);
}
});
}
// * Obtener los registros que contengan un valor semejante a un string en el campo Description
/*const scanData = async (value) => {
const params = {
TableName: tableName,
FilterExpression: 'contains(Description, :value)',
ExpressionAttributeValues: {
':value': { S: value }
}
};
const data = await ddb.scan(params).promise();
return data;
}
scanData('{value-to-scan}').then((data) => {
console.log('=== Data escaneada ===', data.Items.length);
}).catch((error) => {
console.log('=== Error al escanear la data ===', error);
});*/
// * Inicializamos la lectura del archivo csv y su procesamiento
initLog().then(() => {
// * Formateamos el archivo csv
papa.parse(file, {
header: true,
skipEmptyLines: true,
encoding: 'utf-8',
complete: question
});
}).catch((error) => {
console.log('=== Error al inicializar el log ===', error);
});