Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added CSV file support [API, ImportForm] #4

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions admin/src/containers/ImportPage/ImportForm.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {FieldRow, FileField, FormAction} from "./ui-components";
import {readLocalFile} from "../../utils/file";
import JsonDataDisplay from "../../components/JsonDataDisplay";
import {importData} from "../../utils/api";
import { csvParser } from '../../utils/csvParser';

const ImportForm = ({models}) => {
const options = map(models, convertModelToOption);
Expand Down Expand Up @@ -37,7 +38,11 @@ const ImportForm = ({models}) => {
return;
}
setLoading(true);
readLocalFile(sourceFile, JSON.parse).then(setSource)

const filenameSplit = sourceFile.name.split('.');
const ext = filenameSplit[filenameSplit.length - 1];

readLocalFile(sourceFile, ext === 'csv' ? csvParser : JSON.parse).then(setSource)
.catch((error) => {
strapi.notification.error(
"Something wrong when uploading the file, please check the file and try again.");
Expand Down Expand Up @@ -77,7 +82,7 @@ const ImportForm = ({models}) => {
<FileField>
<input id="source"
name="source"
accept={".json"}
accept={".csv,.json"}
type="file"
onChange={onSourceFileChange}
/>
Expand Down
21 changes: 21 additions & 0 deletions admin/src/utils/csvParser.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
export const csvParser = (csv) => {
const csvLines = csv.split(/\r\n|\n/);
const headers = csvLines[0].split(',');
const lines = [];

for (let i = 1; i < csvLines.length; i++) {
const data = csvLines[i].split(',');

if (data.length == headers.length) {
const jsonObj = {};

for (let j = 0; j < headers.length; j++) {
jsonObj[headers[j]] = data[j];
}

lines.push(jsonObj);
}
}

return lines;
};
30 changes: 30 additions & 0 deletions controllers/ContentExportImport.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,40 @@
const PLUGIN_ID = 'content-export-import';

const validator = require('./validations');
const csvHelpers = require("./csvHelpers");

module.exports = {
importContent: async (ctx) => {
const importService = strapi.plugins[PLUGIN_ID].services['contentexportimport'];

let body = ctx.request.body;

try {
// Check if request has files
if (ctx.request.files) {
// Get files['source']
const sourceFile = ctx.request.files["source"].path;
const type = ctx.request.files["source"].type;

// Read and parse file['source']
const source = csvHelpers.readFile(
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The csvHelpers could be a fileHelper or something, otherwise it looks weird to make it parse JSON file as well.

sourceFile,
type === "text/csv" ? csvHelpers.csvParser : JSON.parse
);

body = {
...body,
source,
};

ctx.request.body = body;
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we try not to re-assign an object?
Maybe pass the whole context ctx to the service is not a good idea in the beginning, need to refactor the parameters passing to the service, then you can avoid reassigning the body.


console.log(body);
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can this be removed?

}
} catch (err) {
console.error("err", err, ctx.request.files);
}

const validationResult = validator.validateImportContentRequest(
ctx.request.body);
if (validationResult) {
Expand Down
38 changes: 38 additions & 0 deletions controllers/csvHelpers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
const fs = require('fs');

const readFile = (file, parser) => {
try {
const content = fs.readFileSync(file).toString('utf-8');
console.log('content', content);
return parser && typeof parser === 'function' ? parser(content) : content;
} catch (err) {
throw err;
}
};

const csvParser = (csv) => {
const csvLines = csv.split(/\r\n|\n/);
const headers = csvLines[0].split(',');
const lines = [];

for (let i = 1; i < csvLines.length; i++) {
const data = csvLines[i].split(',');

if (data.length == headers.length) {
const jsonObj = {};

for (let j = 0; j < headers.length; j++) {
jsonObj[headers[j]] = data[j];
}

lines.push(jsonObj);
}
}

return lines;
};

module.exports = {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure whether this file could be moved to utils folder, maybe that's a good place for it. Also please add test cases for it.

readFile,
csvParser
};