ProjectEntityMongoUpdateHandler.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683
  1. const { callbackify } = require('util')
  2. const { callbackifyMultiResult } = require('../../util/promises')
  3. const _ = require('underscore')
  4. const logger = require('@overleaf/logger')
  5. const path = require('path')
  6. const { ObjectId } = require('mongodb')
  7. const Settings = require('@overleaf/settings')
  8. const OError = require('@overleaf/o-error')
  9. const CooldownManager = require('../Cooldown/CooldownManager')
  10. const Errors = require('../Errors/Errors')
  11. const { Folder } = require('../../models/Folder')
  12. const LockManager = require('../../infrastructure/LockManager')
  13. const { Project } = require('../../models/Project')
  14. const ProjectEntityHandler = require('./ProjectEntityHandler')
  15. const ProjectGetter = require('./ProjectGetter')
  16. const ProjectLocator = require('./ProjectLocator')
  17. const FolderStructureBuilder = require('./FolderStructureBuilder')
  18. const SafePath = require('./SafePath')
  19. const { DeletedFile } = require('../../models/DeletedFile')
  20. const LOCK_NAMESPACE = 'mongoTransaction'
  21. const ENTITY_TYPE_TO_MONGO_PATH_SEGMENT = {
  22. doc: 'docs',
  23. docs: 'docs',
  24. file: 'fileRefs',
  25. files: 'fileRefs',
  26. fileRefs: 'fileRefs',
  27. folder: 'folders',
  28. folders: 'folders',
  29. }
  30. module.exports = {
  31. LOCK_NAMESPACE,
  32. addDoc: callbackifyMultiResult(wrapWithLock(addDoc), ['result', 'project']),
  33. addFile: callbackifyMultiResult(wrapWithLock(addFile), ['result', 'project']),
  34. addFolder: callbackifyMultiResult(wrapWithLock(addFolder), [
  35. 'folder',
  36. 'parentFolderId',
  37. ]),
  38. replaceFileWithNew: callbackifyMultiResult(wrapWithLock(replaceFileWithNew), [
  39. 'oldFileRef',
  40. 'project',
  41. 'path',
  42. 'newProject',
  43. ]),
  44. replaceDocWithFile: callbackify(replaceDocWithFile),
  45. replaceFileWithDoc: callbackify(replaceFileWithDoc),
  46. mkdirp: callbackifyMultiResult(wrapWithLock(mkdirp), [
  47. 'newFolders',
  48. 'folder',
  49. ]),
  50. moveEntity: callbackifyMultiResult(wrapWithLock(moveEntity), [
  51. 'project',
  52. 'startPath',
  53. 'endPath',
  54. 'rev',
  55. 'changes',
  56. ]),
  57. deleteEntity: callbackifyMultiResult(wrapWithLock(deleteEntity), [
  58. 'entity',
  59. 'path',
  60. 'projectBeforeDeletion',
  61. 'newProject',
  62. ]),
  63. renameEntity: callbackifyMultiResult(wrapWithLock(renameEntity), [
  64. 'project',
  65. 'startPath',
  66. 'endPath',
  67. 'rev',
  68. 'changes',
  69. ]),
  70. createNewFolderStructure: callbackify(wrapWithLock(createNewFolderStructure)),
  71. _insertDeletedFileReference: callbackify(_insertDeletedFileReference),
  72. _putElement: callbackifyMultiResult(_putElement, ['result', 'project']),
  73. _confirmFolder,
  74. promises: {
  75. addDoc: wrapWithLock(addDoc),
  76. addFile: wrapWithLock(addFile),
  77. addFolder: wrapWithLock(addFolder),
  78. replaceFileWithNew: wrapWithLock(replaceFileWithNew),
  79. replaceDocWithFile: wrapWithLock(replaceDocWithFile),
  80. replaceFileWithDoc: wrapWithLock(replaceFileWithDoc),
  81. mkdirp: wrapWithLock(mkdirp),
  82. moveEntity: wrapWithLock(moveEntity),
  83. deleteEntity: wrapWithLock(deleteEntity),
  84. renameEntity: wrapWithLock(renameEntity),
  85. createNewFolderStructure: wrapWithLock(createNewFolderStructure),
  86. _insertDeletedFileReference,
  87. _putElement,
  88. },
  89. }
  90. function wrapWithLock(methodWithoutLock) {
  91. // This lock is used whenever we read or write to an existing project's
  92. // structure. Some operations to project structure cannot be done atomically
  93. // in mongo, this lock is used to prevent reading the structure between two
  94. // parts of a staged update.
  95. async function methodWithLock(projectId, ...rest) {
  96. return LockManager.promises.runWithLock(LOCK_NAMESPACE, projectId, () =>
  97. methodWithoutLock(projectId, ...rest)
  98. )
  99. }
  100. return methodWithLock
  101. }
  102. async function addDoc(projectId, folderId, doc) {
  103. const project = await ProjectGetter.promises.getProjectWithoutLock(
  104. projectId,
  105. {
  106. rootFolder: true,
  107. name: true,
  108. overleaf: true,
  109. }
  110. )
  111. folderId = _confirmFolder(project, folderId)
  112. const { result, project: newProject } = await _putElement(
  113. project,
  114. folderId,
  115. doc,
  116. 'doc'
  117. )
  118. return { result, project: newProject }
  119. }
  120. async function addFile(projectId, folderId, fileRef) {
  121. const project = await ProjectGetter.promises.getProjectWithoutLock(
  122. projectId,
  123. { rootFolder: true, name: true, overleaf: true }
  124. )
  125. folderId = _confirmFolder(project, folderId)
  126. const { result, project: newProject } = await _putElement(
  127. project,
  128. folderId,
  129. fileRef,
  130. 'file'
  131. )
  132. return { result, project: newProject }
  133. }
  134. async function addFolder(projectId, parentFolderId, folderName) {
  135. const project = await ProjectGetter.promises.getProjectWithoutLock(
  136. projectId,
  137. { rootFolder: true, name: true, overleaf: true }
  138. )
  139. parentFolderId = _confirmFolder(project, parentFolderId)
  140. const folder = new Folder({ name: folderName })
  141. await _putElement(project, parentFolderId, folder, 'folder')
  142. return { folder, parentFolderId }
  143. }
  144. async function replaceFileWithNew(projectId, fileId, newFileRef) {
  145. const project = await ProjectGetter.promises.getProjectWithoutLock(
  146. projectId,
  147. { rootFolder: true, name: true, overleaf: true }
  148. )
  149. const { element: fileRef, path } = await ProjectLocator.promises.findElement({
  150. project,
  151. element_id: fileId,
  152. type: 'file',
  153. })
  154. await _insertDeletedFileReference(projectId, fileRef)
  155. const newProject = await Project.findOneAndUpdate(
  156. { _id: project._id },
  157. {
  158. $set: {
  159. [`${path.mongo}._id`]: newFileRef._id,
  160. [`${path.mongo}.created`]: new Date(),
  161. [`${path.mongo}.linkedFileData`]: newFileRef.linkedFileData,
  162. [`${path.mongo}.hash`]: newFileRef.hash,
  163. },
  164. $inc: {
  165. version: 1,
  166. [`${path.mongo}.rev`]: 1,
  167. },
  168. },
  169. { new: true }
  170. ).exec()
  171. // Note: Mongoose uses new:true to return the modified document
  172. // https://mongoosejs.com/docs/api.html#model_Model.findOneAndUpdate
  173. // but Mongo uses returnNewDocument:true instead
  174. // https://docs.mongodb.com/manual/reference/method/db.collection.findOneAndUpdate/
  175. // We are using Mongoose here, but if we ever switch to a direct mongo call
  176. // the next line will need to be updated.
  177. return { oldFileRef: fileRef, project, path, newProject }
  178. }
  179. async function replaceDocWithFile(projectId, docId, fileRef) {
  180. const project = await ProjectGetter.promises.getProjectWithoutLock(
  181. projectId,
  182. { rootFolder: true, name: true, overleaf: true }
  183. )
  184. const { path } = await ProjectLocator.promises.findElement({
  185. project,
  186. element_id: docId,
  187. type: 'doc',
  188. })
  189. const folderMongoPath = _getParentMongoPath(path.mongo)
  190. const newProject = await Project.findOneAndUpdate(
  191. { _id: project._id },
  192. {
  193. $pull: {
  194. [`${folderMongoPath}.docs`]: { _id: docId },
  195. },
  196. $push: {
  197. [`${folderMongoPath}.fileRefs`]: fileRef,
  198. },
  199. $inc: { version: 1 },
  200. },
  201. { new: true }
  202. ).exec()
  203. return newProject
  204. }
  205. async function replaceFileWithDoc(projectId, fileId, newDoc) {
  206. const project = await ProjectGetter.promises.getProjectWithoutLock(
  207. projectId,
  208. { rootFolder: true, name: true, overleaf: true }
  209. )
  210. const { path } = await ProjectLocator.promises.findElement({
  211. project,
  212. element_id: fileId,
  213. type: 'file',
  214. })
  215. const folderMongoPath = _getParentMongoPath(path.mongo)
  216. const newProject = await Project.findOneAndUpdate(
  217. { _id: project._id },
  218. {
  219. $pull: {
  220. [`${folderMongoPath}.fileRefs`]: { _id: fileId },
  221. },
  222. $push: {
  223. [`${folderMongoPath}.docs`]: newDoc,
  224. },
  225. $inc: { version: 1 },
  226. },
  227. { new: true }
  228. ).exec()
  229. return newProject
  230. }
  231. async function mkdirp(projectId, path, options = {}) {
  232. // defaults to case insensitive paths, use options {exactCaseMatch:true}
  233. // to make matching case-sensitive
  234. let folders = path.split('/')
  235. folders = _.select(folders, folder => folder.length !== 0)
  236. const project = await ProjectGetter.promises.getProjectWithOnlyFolders(
  237. projectId
  238. )
  239. if (path === '/') {
  240. return { newFolders: [], folder: project.rootFolder[0] }
  241. }
  242. const newFolders = []
  243. let builtUpPath = ''
  244. let lastFolder = null
  245. for (const folderName of folders) {
  246. builtUpPath += `/${folderName}`
  247. try {
  248. const { element: foundFolder } =
  249. await ProjectLocator.promises.findElementByPath({
  250. project,
  251. path: builtUpPath,
  252. exactCaseMatch: options.exactCaseMatch,
  253. })
  254. lastFolder = foundFolder
  255. } catch (err) {
  256. // Folder couldn't be found. Create it.
  257. const parentFolderId = lastFolder && lastFolder._id
  258. const { folder: newFolder, parentFolderId: newParentFolderId } =
  259. await addFolder(projectId, parentFolderId, folderName)
  260. newFolder.parentFolder_id = newParentFolderId
  261. lastFolder = newFolder
  262. newFolders.push(newFolder)
  263. }
  264. }
  265. return { folder: lastFolder, newFolders }
  266. }
  267. async function moveEntity(projectId, entityId, destFolderId, entityType) {
  268. const project = await ProjectGetter.promises.getProjectWithoutLock(
  269. projectId,
  270. { rootFolder: true, name: true, overleaf: true }
  271. )
  272. const { element: entity, path: entityPath } =
  273. await ProjectLocator.promises.findElement({
  274. project,
  275. element_id: entityId,
  276. type: entityType,
  277. })
  278. // Prevent top-level docs/files with reserved names (to match v1 behaviour)
  279. if (_blockedFilename(entityPath, entityType)) {
  280. throw new Errors.InvalidNameError('blocked element name')
  281. }
  282. await _checkValidMove(project, entityType, entity, entityPath, destFolderId)
  283. const { docs: oldDocs, files: oldFiles } =
  284. ProjectEntityHandler.getAllEntitiesFromProject(project)
  285. // For safety, insert the entity in the destination
  286. // location first, and then remove the original. If
  287. // there is an error the entity may appear twice. This
  288. // will cause some breakage but is better than being
  289. // lost, which is what happens if this is done in the
  290. // opposite order.
  291. const { result } = await _putElement(
  292. project,
  293. destFolderId,
  294. entity,
  295. entityType
  296. )
  297. // Note: putElement always pushes onto the end of an
  298. // array so it will never change an existing mongo
  299. // path. Therefore it is safe to remove an element
  300. // from the project with an existing path after
  301. // calling putElement. But we must be sure that we
  302. // have not moved a folder subfolder of itself (which
  303. // is done by _checkValidMove above) because that
  304. // would lead to it being deleted.
  305. const newProject = await _removeElementFromMongoArray(
  306. Project,
  307. projectId,
  308. entityPath.mongo,
  309. entityId
  310. )
  311. const { docs: newDocs, files: newFiles } =
  312. ProjectEntityHandler.getAllEntitiesFromProject(newProject)
  313. const startPath = entityPath.fileSystem
  314. const endPath = result.path.fileSystem
  315. const changes = {
  316. oldDocs,
  317. newDocs,
  318. oldFiles,
  319. newFiles,
  320. newProject,
  321. }
  322. // check that no files have been lost (or duplicated)
  323. if (
  324. oldFiles.length !== newFiles.length ||
  325. oldDocs.length !== newDocs.length
  326. ) {
  327. logger.warn(
  328. {
  329. projectId,
  330. oldDocs: oldDocs.length,
  331. newDocs: newDocs.length,
  332. oldFiles: oldFiles.length,
  333. newFiles: newFiles.length,
  334. origProject: project,
  335. newProject,
  336. },
  337. "project corrupted moving files - shouldn't happen"
  338. )
  339. throw new Error('unexpected change in project structure')
  340. }
  341. return { project, startPath, endPath, rev: entity.rev, changes }
  342. }
  343. async function deleteEntity(projectId, entityId, entityType, callback) {
  344. const project = await ProjectGetter.promises.getProjectWithoutLock(
  345. projectId,
  346. { name: true, rootFolder: true, overleaf: true, rootDoc_id: true }
  347. )
  348. const deleteRootDoc =
  349. project.rootDoc_id &&
  350. entityId &&
  351. project.rootDoc_id.toString() === entityId.toString()
  352. const { element: entity, path } = await ProjectLocator.promises.findElement({
  353. project,
  354. element_id: entityId,
  355. type: entityType,
  356. })
  357. const newProject = await _removeElementFromMongoArray(
  358. Project,
  359. projectId,
  360. path.mongo,
  361. entityId,
  362. deleteRootDoc
  363. )
  364. return { entity, path, projectBeforeDeletion: project, newProject }
  365. }
  366. async function renameEntity(
  367. projectId,
  368. entityId,
  369. entityType,
  370. newName,
  371. callback
  372. ) {
  373. const project = await ProjectGetter.promises.getProjectWithoutLock(
  374. projectId,
  375. { rootFolder: true, name: true, overleaf: true }
  376. )
  377. const {
  378. element: entity,
  379. path: entPath,
  380. folder: parentFolder,
  381. } = await ProjectLocator.promises.findElement({
  382. project,
  383. element_id: entityId,
  384. type: entityType,
  385. })
  386. const startPath = entPath.fileSystem
  387. const endPath = path.join(path.dirname(entPath.fileSystem), newName)
  388. // Prevent top-level docs/files with reserved names (to match v1 behaviour)
  389. if (_blockedFilename({ fileSystem: endPath }, entityType)) {
  390. throw new Errors.InvalidNameError('blocked element name')
  391. }
  392. // check if the new name already exists in the current folder
  393. _checkValidElementName(parentFolder, newName)
  394. const { docs: oldDocs, files: oldFiles } =
  395. ProjectEntityHandler.getAllEntitiesFromProject(project)
  396. // we need to increment the project version number for any structure change
  397. const newProject = await Project.findOneAndUpdate(
  398. { _id: projectId },
  399. { $set: { [`${entPath.mongo}.name`]: newName }, $inc: { version: 1 } },
  400. { new: true }
  401. ).exec()
  402. const { docs: newDocs, files: newFiles } =
  403. ProjectEntityHandler.getAllEntitiesFromProject(newProject)
  404. return {
  405. project,
  406. startPath,
  407. endPath,
  408. rev: entity.rev,
  409. changes: { oldDocs, newDocs, oldFiles, newFiles, newProject },
  410. }
  411. }
  412. async function _insertDeletedFileReference(projectId, fileRef) {
  413. await DeletedFile.create({
  414. projectId,
  415. _id: fileRef._id,
  416. name: fileRef.name,
  417. linkedFileData: fileRef.linkedFileData,
  418. hash: fileRef.hash,
  419. deletedAt: new Date(),
  420. })
  421. }
  422. async function _removeElementFromMongoArray(
  423. model,
  424. modelId,
  425. path,
  426. elementId,
  427. deleteRootDoc = false
  428. ) {
  429. const nonArrayPath = path.slice(0, path.lastIndexOf('.'))
  430. const options = { new: true }
  431. const query = { _id: modelId }
  432. const update = {
  433. $pull: { [nonArrayPath]: { _id: elementId } },
  434. $inc: { version: 1 },
  435. }
  436. if (deleteRootDoc) {
  437. update.$unset = { rootDoc_id: 1 }
  438. }
  439. return model.findOneAndUpdate(query, update, options).exec()
  440. }
  441. function _countElements(project) {
  442. function countFolder(folder) {
  443. if (folder == null) {
  444. return 0
  445. }
  446. let total = 0
  447. if (folder.folders) {
  448. total += folder.folders.length
  449. for (const subfolder of folder.folders) {
  450. total += countFolder(subfolder)
  451. }
  452. }
  453. if (folder.docs) {
  454. total += folder.docs.length
  455. }
  456. if (folder.fileRefs) {
  457. total += folder.fileRefs.length
  458. }
  459. return total
  460. }
  461. return countFolder(project.rootFolder[0])
  462. }
  463. async function _putElement(project, folderId, element, type) {
  464. if (element == null || element._id == null) {
  465. logger.warn(
  466. { projectId: project._id, folderId, element, type },
  467. 'failed trying to insert element as it was null'
  468. )
  469. throw new Error('no element passed to be inserted')
  470. }
  471. const pathSegment = _getMongoPathSegmentFromType(type)
  472. // original check path.resolve("/", element.name) isnt "/#{element.name}" or element.name.match("/")
  473. // check if name is allowed
  474. if (!SafePath.isCleanFilename(element.name)) {
  475. logger.warn(
  476. { projectId: project._id, folderId, element, type },
  477. 'failed trying to insert element as name was invalid'
  478. )
  479. throw new Errors.InvalidNameError('invalid element name')
  480. }
  481. if (folderId == null) {
  482. folderId = project.rootFolder[0]._id
  483. }
  484. if (_countElements(project) > Settings.maxEntitiesPerProject) {
  485. logger.warn(
  486. { projectId: project._id },
  487. 'project too big, stopping insertions'
  488. )
  489. CooldownManager.putProjectOnCooldown(project._id)
  490. throw new Error('project_has_too_many_files')
  491. }
  492. const { element: folder, path } = await ProjectLocator.promises.findElement({
  493. project,
  494. element_id: folderId,
  495. type: 'folder',
  496. })
  497. const newPath = {
  498. fileSystem: `${path.fileSystem}/${element.name}`,
  499. mongo: path.mongo,
  500. }
  501. // check if the path would be too long
  502. if (!SafePath.isAllowedLength(newPath.fileSystem)) {
  503. throw new Errors.InvalidNameError('path too long')
  504. }
  505. // Prevent top-level docs/files with reserved names (to match v1 behaviour)
  506. if (_blockedFilename(newPath, type)) {
  507. throw new Errors.InvalidNameError('blocked element name')
  508. }
  509. _checkValidElementName(folder, element.name)
  510. element._id = ObjectId(element._id.toString())
  511. const mongoPath = `${path.mongo}.${pathSegment}`
  512. const newProject = await Project.findOneAndUpdate(
  513. { _id: project._id },
  514. { $push: { [mongoPath]: element }, $inc: { version: 1 } },
  515. { new: true }
  516. ).exec()
  517. return { result: { path: newPath }, project: newProject }
  518. }
  519. function _blockedFilename(entityPath, entityType) {
  520. // check if name would be blocked in v1
  521. // javascript reserved names are forbidden for docs and files
  522. // at the top-level (but folders with reserved names are allowed).
  523. const isFolder = entityType === 'folder'
  524. const dir = path.dirname(entityPath.fileSystem)
  525. const file = path.basename(entityPath.fileSystem)
  526. const isTopLevel = dir === '/'
  527. if (isTopLevel && !isFolder && SafePath.isBlockedFilename(file)) {
  528. return true
  529. } else {
  530. return false
  531. }
  532. }
  533. function _getMongoPathSegmentFromType(type) {
  534. const pathSegment = ENTITY_TYPE_TO_MONGO_PATH_SEGMENT[type]
  535. if (pathSegment == null) {
  536. throw new Error(`Unknown entity type: ${type}`)
  537. }
  538. return pathSegment
  539. }
  540. /**
  541. * Check if the name is already taken by a doc, file or folder. If so, return an
  542. * error "file already exists".
  543. */
  544. function _checkValidElementName(folder, name) {
  545. if (folder == null) {
  546. return
  547. }
  548. const elements = []
  549. .concat(folder.docs || [])
  550. .concat(folder.fileRefs || [])
  551. .concat(folder.folders || [])
  552. for (const element of elements) {
  553. if (element.name === name) {
  554. throw new Errors.InvalidNameError('file already exists')
  555. }
  556. }
  557. }
  558. function _confirmFolder(project, folderId) {
  559. if (folderId == null) {
  560. return project.rootFolder[0]._id
  561. } else {
  562. return folderId
  563. }
  564. }
  565. async function _checkValidMove(
  566. project,
  567. entityType,
  568. entity,
  569. entityPath,
  570. destFolderId
  571. ) {
  572. const { element: destEntity, path: destFolderPath } =
  573. await ProjectLocator.promises.findElement({
  574. project,
  575. element_id: destFolderId,
  576. type: 'folder',
  577. })
  578. // check if there is already a doc/file/folder with the same name
  579. // in the destination folder
  580. _checkValidElementName(destEntity, entity.name)
  581. if (/folder/.test(entityType)) {
  582. const isNestedFolder =
  583. destFolderPath.fileSystem.slice(0, entityPath.fileSystem.length) ===
  584. entityPath.fileSystem
  585. if (isNestedFolder) {
  586. throw new Errors.InvalidNameError(
  587. 'destination folder is a child folder of me'
  588. )
  589. }
  590. }
  591. }
  592. /**
  593. * Create an initial file tree out of a list of doc and file entries
  594. *
  595. * Each entry specifies a path to the doc or file. Folders are automatically
  596. * created.
  597. *
  598. * @param {ObjectId} projectId - id of the project
  599. * @param {DocEntry[]} docEntries - list of docs to add
  600. * @param {FileEntry[]} fileEntries - list of files to add
  601. * @return {Promise<string>} the project version after the operation
  602. */
  603. async function createNewFolderStructure(projectId, docEntries, fileEntries) {
  604. try {
  605. const rootFolder = FolderStructureBuilder.buildFolderStructure(
  606. docEntries,
  607. fileEntries
  608. )
  609. const project = await Project.findOneAndUpdate(
  610. {
  611. _id: projectId,
  612. 'rootFolder.0.folders.0': { $exists: false },
  613. 'rootFolder.0.docs.0': { $exists: false },
  614. 'rootFolder.0.files.0': { $exists: false },
  615. },
  616. {
  617. $set: { rootFolder: [rootFolder] },
  618. $inc: { version: 1 },
  619. },
  620. {
  621. new: true,
  622. lean: true,
  623. fields: { version: 1 },
  624. }
  625. ).exec()
  626. if (project == null) {
  627. throw new OError('project not found or folder structure already exists', {
  628. projectId,
  629. })
  630. }
  631. return project.version
  632. } catch (err) {
  633. throw OError.tag(err, 'failed to create folder structure', { projectId })
  634. }
  635. }
  636. /**
  637. * Given a Mongo path to an entity, return the Mongo path to the parent folder
  638. */
  639. function _getParentMongoPath(mongoPath) {
  640. const segments = mongoPath.split('.')
  641. if (segments.length <= 2) {
  642. throw new Error('Root folder has no parents')
  643. }
  644. return segments.slice(0, -2).join('.')
  645. }