Advertisement
UrQuan

Untitled

May 22nd, 2017
309
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.01 KB | None | 0 0
  1. validate: {
  2. validDirectoryString () {
  3. // Required here - because it's not defined on init (Framework limitations)
  4. const Directory = require('../models').Directory
  5. const bookmark = this
  6.  
  7. if (!this.directory_id && (!this.directory || (this.directory === '/'))) {
  8. // It belongs to root directory, and is not a problem
  9. return true
  10. }
  11.  
  12. if (this.directory_id) {
  13. return Directory.findOne({where: {id: this.directory_id}}).then(dir => {
  14. if (!dir) throw new Error('Invalid directory ID - directory could not be found.')
  15. bookmark.directory = dir.directory
  16. })
  17. }
  18.  
  19. let dirList = directoryMixin.parseDirList(this.directory)
  20.  
  21. // Recursive promise magic - each element of the directory structure gets
  22. // thrown onto the promise chain, until the whole structure is built
  23. function recursiveDirectoryCreation (dirList, index, parentId) {
  24. function _recursePromise (newDir) {
  25. let parent = newDir ? newDir.id : null
  26. let directoryName = '/' + dirList.slice(0, index + 1).join('/') + '/'
  27. if (dirList.length === (index + 1)) {
  28. return Directory.create({directory: directoryName, parent: parent, user_id: bookmark.user_id})
  29. }
  30. index += 1
  31.  
  32. return Directory.create({
  33. directory: directoryName,
  34. parent: parent,
  35. user_id: bookmark.user_id
  36. }).then(_recursePromise)
  37. }
  38.  
  39. return _recursePromise(null)
  40. }
  41.  
  42. return Directory.find({where: {
  43. user_id: bookmark.user_id,
  44. directory: bookmark.directory
  45. }}).then((matchedDir) => {
  46. if (!matchedDir) {
  47. return recursiveDirectoryCreation(dirList, 0, null).then((dir) => {
  48. bookmark.directory_id = dir.id
  49. })
  50. }
  51. bookmark.directory_id = matchedDir.id
  52. })
  53. }
  54. },
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement