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.models;
  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. for (const page of pages) {
  18. const path = page.path;
  19. const user = page.user;
  20. const body = page.body;
  21. const isCreatableName = isCreatablePage(path);
  22. // biome-ignore lint/performance/noAwaitInLoops: Allow for memory consumption control
  23. const isPageNameTaken = await Page.findByPathAndViewer(path, user);
  24. if (isCreatableName && !isPageNameTaken) {
  25. try {
  26. const promise = crowi.pageService.create(path, body, user, {
  27. grant: Page.GRANT_PUBLIC,
  28. grantUserGroupId: null,
  29. });
  30. promises.push(promise);
  31. } catch (err) {
  32. errors.push(err);
  33. }
  34. } else {
  35. if (!isCreatableName) {
  36. errors.push(new Error(`${path} is not a creatable name in GROWI`));
  37. }
  38. if (isPageNameTaken) {
  39. errors.push(new Error(`${path} already exists in GROWI`));
  40. }
  41. }
  42. }
  43. await Promise.all(promises);
  44. return errors;
  45. };
  46. return createGrowiPages;
  47. };