createGrowiPagesFromImports.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. module.exports = (crowi) => {
  2. const Page = crowi.model('Page');
  3. /**
  4. * Create posts from imported data
  5. * @param pages = [{
  6. * path: String,
  7. * body: String,
  8. * user: Object
  9. * }]
  10. */
  11. const createGrowiPages = async(pages) => {
  12. const promises = [];
  13. const errors = [];
  14. /* eslint-disable no-await-in-loop */
  15. for (const page of pages) {
  16. const path = page.path;
  17. const user = page.user;
  18. const body = page.body;
  19. const isCreatableName = await Page.isCreatableName(path);
  20. const isPageNameTaken = await Page.findByPathAndViewer(path, user);
  21. if (isCreatableName && !isPageNameTaken) {
  22. try {
  23. const promise = Page.create(path, body, user, { grant: Page.GRANT_PUBLIC, grantUserGroupId: null });
  24. promises.push(promise);
  25. }
  26. catch (err) {
  27. errors.push(err);
  28. }
  29. }
  30. else {
  31. if (!isCreatableName) {
  32. errors.push(new Error(`${path} is not a creatable name in Growi`));
  33. }
  34. if (isPageNameTaken) {
  35. errors.push(new Error(`${path} already exists in Growi`));
  36. }
  37. }
  38. }
  39. /* eslint-enable no-await-in-loop */
  40. await Promise.all(promises);
  41. return errors;
  42. };
  43. return createGrowiPages;
  44. };