Support uploading structured JSON to create courses, classes, and students without wiping existing data, and merge user name fields while adding gender and registration details from source sheets.
29 lines
984 B
JavaScript
29 lines
984 B
JavaScript
// /components/dataImport/dataImportController.js
|
|
'use strict';
|
|
|
|
const catchAsync = require('../../utils/catchAsync');
|
|
const dataImportService = require('./dataImportService');
|
|
const AppError = require('../../utils/AppError');
|
|
const { successResponse } = require('../../utils/apiResponse');
|
|
|
|
exports.importJson = catchAsync(async (req, res) => {
|
|
let payload = req.body;
|
|
|
|
if (req.file?.buffer) {
|
|
try {
|
|
payload = JSON.parse(req.file.buffer.toString('utf8'));
|
|
} catch {
|
|
throw new AppError('VALIDATION_FAILED', null, 'Uploaded file is not valid JSON');
|
|
}
|
|
}
|
|
|
|
// Allow { data: { courses: [...] } } wrappers
|
|
if (payload?.data?.courses) payload = payload.data;
|
|
if (!payload?.courses && payload?.version && payload?.courses == null) {
|
|
throw new AppError('VALIDATION_FAILED', null, 'Invalid import payload');
|
|
}
|
|
|
|
const result = await dataImportService.importData(payload);
|
|
return successResponse(res, 200, 'Data imported successfully', result);
|
|
});
|