Skip to content

Commit 9af26fd

Browse files
committed
feat: integrate PapaParse for CSV parsing and enhance error handling
1 parent a47820f commit 9af26fd

File tree

3 files changed

+95
-20
lines changed

3 files changed

+95
-20
lines changed

custom/ImportCsv.vue

+32-20
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
import { ref, Ref } from 'vue';
1313
import { callAdminForthApi } from '@/utils';
1414
import adminforth from '@/adminforth';
15+
import Papa from 'papaparse';
1516
1617
const inProgress: Ref<boolean> = ref(false);
1718
@@ -63,32 +64,43 @@ async function importCsv() {
6364
return;
6465
}
6566
66-
// post data in format, plain json
67-
// data is in format {[columnName]: [value1, value2, value3...], [columnName2]: [value1, value2, value3...]}
68-
const data = {};
6967
const reader = new FileReader();
7068
reader.onload = async (e) => {
71-
const text = e.target.result as string;
72-
73-
const lines = text.split('\n');
74-
const columns = lines[0].split(',');
75-
for (let i = 1; i < lines.length; i++) {
76-
const values = lines[i].split(',');
77-
for (let j = 0; j < columns.length; j++) {
78-
if (!data[columns[j]]) {
79-
data[columns[j]] = [];
69+
try {
70+
const text = e.target.result as string;
71+
72+
Papa.parse(text, {
73+
header: true,
74+
skipEmptyLines: true,
75+
complete: async (results) => {
76+
if (results.errors.length > 0) {
77+
throw new Error(`CSV parsing errors: ${results.errors.map(e => e.message).join(', ')}`);
78+
}
79+
const data: Record<string, string[]> = {};
80+
const rows = results.data as Record<string, string>[];
81+
82+
if (rows.length === 0) {
83+
throw new Error('No data rows found in CSV');
84+
}
85+
Object.keys(rows[0]).forEach(column => {
86+
data[column] = rows.map(row => row[column]);
87+
});
88+
89+
await postData(data);
90+
},
91+
error: (error) => {
92+
throw new Error(`Failed to parse CSV: ${error.message}`);
8093
}
81-
data[columns[j]].push(values[j]);
82-
}
94+
});
95+
} catch (error) {
96+
inProgress.value = false;
97+
adminforth.alert({
98+
message: `Error processing CSV: ${error.message}`,
99+
variant: 'danger'
100+
});
83101
}
84-
await postData(data);
85102
};
86103
reader.readAsText(file);
87-
88-
89-
90104
};
91-
92105
}
93-
94106
</script>

custom/package-lock.json

+47
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

custom/package.json

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
{
2+
"name": "custom",
3+
"version": "1.0.0",
4+
"main": "index.js",
5+
"scripts": {
6+
"test": "echo \"Error: no test specified\" && exit 1"
7+
},
8+
"keywords": [],
9+
"author": "",
10+
"license": "ISC",
11+
"description": "",
12+
"dependencies": {
13+
"@types/papaparse": "^5.3.15",
14+
"papaparse": "^5.5.2"
15+
}
16+
}

0 commit comments

Comments
 (0)