createGrowiPagesFromImports.js 1.4 KB

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