Bis jetzt habe ich eine Sammlung erstellt:
Code: Select all
{
"kind": "collectionType",
"collectionName": "locations",
"info": {
"singularName": "location",
"pluralName": "locations",
"displayName": "location",
"description": ""
},
"options": {
"draftAndPublish": true
},
"pluginOptions": {},
"attributes": {
"address": {
"type": "text",
"required": true
},
"country": {
"type": "string",
"required": true
},
"city": {
"type": "string",
"required": true
},
"zip": {
"type": "string",
"required": true
}
}
}
Code: Select all
{
"kind": "singleType",
"collectionName": "loactions-uploads",
"info": {
"singularName": "loactions-upload",
"pluralName": "loactions-uploads",
"displayName": "Loactions-upload"
},
"options": {
"draftAndPublish": true
},
"pluginOptions": {},
"attributes": {
"upload": {
"allowedTypes": [
"files"
],
"type": "media",
"multiple": false
}
}
}
Code: Select all
const fs = require("fs");
const path = require("path");
const { parse } = require("csv-parse");
module.exports = {
async afterCreate(event) {
const { result } = event;
const file = result.file;
if (!file || file.ext !== ".csv") {
strapi.log.warn("No valid .csv file found.");
return;
}
const filePath = path.join(strapi.dirs.static.public, file.url);
try {
const data = fs.readFileSync(filePath, "utf-8");
// Parse CSV
const records = [];
const parser = parse({ delimiter: ";", columns: true });
parser.write(data);
parser.end();
parser.on("readable", () => {
let record;
while ((record = parser.read())) {
records.push(record);
}
});
await new Promise((resolve, reject) => {
parser.on("end", resolve);
parser.on("error", reject);
});
// Process records and create entries
for (const record of records) {
await strapi.entityService.create("api::location.location", {
data: {
zip: record.ZIP,
address: record.Address,
country: record.Country,
city: record.city,
},
});
}
strapi.log.info(
`Successfully imported ${records.length} entries from CSV.`
);
} catch (err) {
strapi.log.error("Failed to process the CSV file:", err);
}
},
};
Die CSV-Datei sieht wie folgt aus:
Code: Select all
ZIP;Address;City;Country;
1010;Seilerstätte 12/1;Vienna;Austria;
1030;Rochusgasse 9/21,Vienna;Austria;