format-chapter-data-json.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /**
  2. * A script that helps with reformatting the JSON data pulled from QDC's chapters API e.g. https://api.quran.com/api/v4/chapters?language=ar
  3. * to QDC's FE JSON structure. This will help us:
  4. *
  5. * 1. Camelize the keys.
  6. * 2. Remove un-necessary data to make the payload size as small as possible.
  7. *
  8. * It can be used by running `yarn run chapter-data:format {locale}` e.g. `yarn run chapter-data:format en`
  9. * after having created a file called `data/chapters/en.json` and pasted the API's JSON response into it.
  10. */
  11. /* eslint-disable no-console */
  12. const fs = require('fs');
  13. const locale = process.argv[2];
  14. if (!locale) {
  15. console.log('Please enter the locale!');
  16. } else {
  17. const path = `./data/chapters/${locale}.json`;
  18. if (fs.existsSync(path)) {
  19. let fileContent;
  20. try {
  21. fileContent = fs.readFileSync(path, 'utf-8');
  22. } catch (error) {
  23. console.log('Something went wrong while trying to open');
  24. }
  25. if (fileContent) {
  26. const fileContentJson = JSON.parse(fileContent);
  27. const chaptersData = fileContentJson.chapters;
  28. const newFileContent = {};
  29. chaptersData.forEach((chapterData) => {
  30. const newChapterData = {};
  31. newChapterData.revelationPlace = chapterData.revelation_place;
  32. newChapterData.transliteratedName =
  33. locale === 'ar' ? chapterData.name_arabic : chapterData.name_simple;
  34. newChapterData.versesCount = chapterData.verses_count;
  35. newChapterData.translatedName =
  36. locale === 'ar' ? chapterData.name_arabic : chapterData.translated_name.name;
  37. newChapterData.slug = chapterData.slug.slug;
  38. newFileContent[chapterData.id] = newChapterData;
  39. });
  40. fs.writeFile(path, JSON.stringify(newFileContent), (err) => {
  41. if (err) {
  42. console.log(`Something went wrong while trying to write to ${path}`);
  43. return;
  44. }
  45. console.log('Executed successfully');
  46. });
  47. }
  48. } else {
  49. // Below code to create the folder, if its not there
  50. console.log(`File ${path} does not exist!`);
  51. }
  52. }