Skip to content

Commit 9c6f6f1

Browse files
feature/backend locale mapper sitecore
1 parent 804b701 commit 9c6f6f1

File tree

6 files changed

+135
-19
lines changed

6 files changed

+135
-19
lines changed

api/src/controllers/migration.controller.ts

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,11 +60,17 @@ const saveLocales = async (req:Request, res: Response):Promise<void> =>{
6060
res.status(200).json(resp);
6161
}
6262

63+
const saveMappedLocales = async (req:Request, res:Response):Promise<void> =>{
64+
const resp = await migrationService.updateLocaleMapper(req);
65+
res.status(200).json(resp);
66+
}
67+
6368
export const migrationController = {
6469
createTestStack,
6570
deleteTestStack,
6671
startTestMigration,
6772
startMigration,
6873
getLogs,
69-
saveLocales
74+
saveLocales,
75+
saveMappedLocales
7076
};

api/src/routes/migration.routes.ts

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,10 +65,31 @@ router.get(
6565

6666
)
6767

68+
/**
69+
* Route for updating the source locales from legacy CMS
70+
* @route POST /validator
71+
* @group Migration
72+
* @param {string} projectID - Current project ID
73+
* @body {Object} locales - Fetched Locales
74+
* @returns {Promise<void>} - A promise which resolves when the locales are updated in the DB
75+
*/
6876
router.post(
6977
"/localeMapper/:projectId",
7078
asyncRouter(migrationController.saveLocales)
7179
)
7280

81+
/**
82+
* Route for updating the mapped locales by user
83+
* @route POST /validator
84+
* @group Migration
85+
* @param {string} projectID - Current project ID
86+
* @body {Object} locales - Mapped Locales
87+
* @returns {Promise<void>} - A promise which resolves when the locales are updated in the DB
88+
*/
89+
router.post(
90+
"/updateLocales/:projectId",
91+
asyncRouter(migrationController.saveMappedLocales)
92+
)
93+
7394

7495
export default router;

api/src/services/migration.service.ts

Lines changed: 72 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -410,14 +410,18 @@ const getLogs = async (req: Request): Promise<any> => {
410410

411411
}
412412

413+
/**
414+
* @description - This function takes all the fetched locales from the exported data of the legacy CMS and stores/updates them in the project.json in DB
415+
*
416+
* @param req - A request body object with fetched locales [] as payload along with project ID in params
417+
* @return - void
418+
* @throws Exception if the project ID is invalid or the when the path to project.json is incorrect
419+
*/
413420
export const createSourceLocales = async (req: Request) => {
414421

415-
console.info("ENTERED MIGRATION API LINE 415")
416-
417422
const projectFilePath = path.join(process.cwd(), 'database', 'project.json'); // Adjusted path to project.json
418423
const projectId = req.params.projectId;
419424

420-
console.info("Request Object LINE 420",req.body)
421425
const locales = req.body.locale
422426

423427
try {
@@ -426,36 +430,91 @@ export const createSourceLocales = async (req: Request) => {
426430
console.error(`project.json not found at ${projectFilePath}`);
427431
throw new Error(`project.json not found.`);
428432
}
429-
430-
// const data = await fs.promises.readFile(projectFilePath, 'utf8');
431-
// const projects = JSON.parse(data);
432433

433434
// Find the project with the specified projectId
434435
const project: any = ProjectModelLowdb.chain.get("projects").find({ id: projectId }).value();
435436
if (project) {
436437
const index = ProjectModelLowdb.chain.get("projects").findIndex({ id: projectId }).value();
437438
if (index > -1) {
438-
console.info("INSIDE API IF STATEMENT LINE 437",index );
439439

440440
ProjectModelLowdb.update((data: any) => {
441-
// console.info("DATA LINE 439 ", data?.projects?.[index])
442441
data.projects[index].source_locales = locales;
443-
// console.info(data.projects[index] )
444442
});
445443
} // Write back the updated projects
446444
} else {
447-
console.error(`Project with id ${projectId} not found.`);
445+
logger.error(`Project with ID: ${projectId} not found`,{
446+
status: HTTP_CODES?.NOT_FOUND,
447+
message: HTTP_TEXTS?.INVALID_ID
448+
})
448449
}
449-
} catch (err) {
450-
console.error('Error updating project.json:', err);
450+
} catch (err: any) {
451+
console.error("🚀 ~ createSourceLocales ~ err:", err?.response?.data ?? err, err)
452+
logger.warn('Bad Request', {
453+
status: HTTP_CODES?.BAD_REQUEST,
454+
message: HTTP_TEXTS?.INTERNAL_ERROR,
455+
});
456+
throw new ExceptionFunction(
457+
err?.message || HTTP_TEXTS.INTERNAL_ERROR,
458+
err?.statusCode || err?.status || HTTP_CODES.SERVER_ERROR
459+
);
451460
}
452461
}
453462

463+
464+
/**
465+
* @description - Function retrieves the mapped locales and updates them in the project.json in DB
466+
* @param req - A request body object with mapped locales as payload and project ID in the params
467+
* @return - void
468+
* @throws Exception if the project ID is invalid or the when the path to project.json is incorrect
469+
*/
470+
export const updateLocaleMapper = async (req:Request) =>{
471+
const mapperObject = req.body.mapper;
472+
const projectFilePath = path.join(process.cwd(), 'database', 'project.json'); // Adjusted path to project.json
473+
const projectId = req.params.projectId;
474+
475+
try {
476+
// Check if the project.json file exists
477+
if (!fs.existsSync(projectFilePath)) {
478+
console.error(`project.json not found at ${projectFilePath}`);
479+
throw new Error(`project.json not found.`);
480+
}
481+
482+
// Find the project with the specified projectId
483+
const project: any = ProjectModelLowdb.chain.get("projects").find({ id: projectId }).value();
484+
if (project) {
485+
const index = ProjectModelLowdb.chain.get("projects").findIndex({ id: projectId }).value();
486+
if (index > -1) {
487+
ProjectModelLowdb.update((data: any) => {
488+
data.projects[index].master_locale = mapperObject?.master_locale;
489+
data.projects[index].locales = mapperObject?.locales;
490+
});
491+
} // Write back the updated projects
492+
} else {
493+
logger.error(`Project with ID: ${projectId} not found`,{
494+
status: HTTP_CODES?.NOT_FOUND,
495+
message: HTTP_TEXTS?.INVALID_ID
496+
})
497+
}
498+
} catch (err: any) {
499+
console.error("🚀 ~ createSourceLocales ~ err:", err?.response?.data ?? err, err)
500+
logger.warn('Bad Request', {
501+
status: HTTP_CODES?.BAD_REQUEST,
502+
message: HTTP_TEXTS?.INTERNAL_ERROR,
503+
});
504+
throw new ExceptionFunction(
505+
err?.message || HTTP_TEXTS.INTERNAL_ERROR,
506+
err?.statusCode || err?.status || HTTP_CODES.SERVER_ERROR
507+
);
508+
}
509+
510+
}
511+
454512
export const migrationService = {
455513
createTestStack,
456514
deleteTestStack,
457515
startTestMigration,
458516
startMigration,
459517
getLogs,
460-
createSourceLocales
518+
createSourceLocales,
519+
updateLocaleMapper
461520
};

upload-api/migration-sitecore/index.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import reference from "./libs/reference.js";
77
// eslint-disable-next-line @typescript-eslint/no-var-requires
88
import ExtractFiles from "./libs/convert.js"
99

10-
import findAndExtractLanguages from './libs/extractLocales.js'
10+
import {findAndExtractLanguages} from './libs/extractLocales.js'
1111

1212
export {
1313
contentTypes,
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import fs from 'fs'
2+
import path from 'path'
3+
4+
const uniqueLanguages = new Set(); // Define uniqueLanguages globally or pass it as a parameter
5+
6+
export const findAndExtractLanguages = (dir) => {
7+
const items = fs.readdirSync(dir, { withFileTypes: true });
8+
9+
for (const item of items) {
10+
const fullPath = path.join(dir, item.name);
11+
12+
if (item.isDirectory()) {
13+
findAndExtractLanguages(fullPath); // Proper recursion
14+
} else if (item.isFile() && item.name === "data.json.json") {
15+
try {
16+
const rawData = fs.readFileSync(fullPath, "utf8");
17+
const jsonData = JSON.parse(rawData);
18+
const language = jsonData?.item?.$?.language;
19+
20+
if (language) {
21+
uniqueLanguages.add(language);
22+
}
23+
} catch (error) {
24+
console.error(`Error reading ${fullPath}:`, error.message);
25+
}
26+
}
27+
}
28+
return uniqueLanguages;
29+
};

upload-api/src/controllers/sitecore/index.ts

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,8 @@ const createSitecoreMapper = async (filePath: string = "", projectId: string | s
1919
const newPath = path.join(filePath, 'items');
2020

2121
const localeData = await findAndExtractLanguages(path.join(filePath, 'items','master','sitecore','content'));
22-
logger.info('Fetched Locales: ', localeData)
22+
console.log("Fetched Locales: ", localeData);
23+
2324

2425
await ExtractFiles(newPath);
2526
await ExtractConfiguration(newPath);
@@ -76,15 +77,15 @@ const createSitecoreMapper = async (filePath: string = "", projectId: string | s
7677

7778
const mapRes = await axios.request(mapperConfig)
7879
if(mapRes?.status==200){
79-
logger.info('Validation success', {
80+
logger.info('Locales Saved', {
8081
status: HTTP_CODES?.OK,
8182
message: HTTP_TEXTS?.LOCALE_SAVED,
82-
});
83+
});
8384
}
8485

8586
}
8687
} catch (err: any) {
87-
console.error("🚀 ~ createSitecoreMapper ~ err:", err?.response?.data ?? err, err)
88+
console.error("🚀 ~ createSitecoreMapper ~ err:", err?.response?.data ?? err)
8889
logger.warn('Validation error:', {
8990
status: HTTP_CODES?.UNAUTHORIZED,
9091
message: HTTP_TEXTS?.VALIDATION_ERROR,

0 commit comments

Comments
 (0)