|
| 1 | +openNote.service("tagService", function ($rootScope,storageService) { |
| 2 | + var service = this; |
| 3 | + var tagRegex = /(#[^\ <]*)/ig; |
| 4 | + |
| 5 | + /** |
| 6 | + * Bind handlers to the root scope |
| 7 | + */ |
| 8 | + this.bindHandlers = function(){ |
| 9 | + $rootScope.$on("noteSaved", function(event, note) { |
| 10 | + deleteTagsFromMap(note._id,function(){ |
| 11 | + var results = note.note.match(tagRegex); |
| 12 | + if(!results||!results.length) |
| 13 | + return; |
| 14 | + addTagsToMap(results,note._id); |
| 15 | + }); |
| 16 | + }); |
| 17 | + }; |
| 18 | + |
| 19 | + /** |
| 20 | + * Add tags to the map |
| 21 | + * @param tags - array of tags present |
| 22 | + * @param id - ID of the note |
| 23 | + * @emmit - emiits tagsUpdated on success |
| 24 | + */ |
| 25 | + var addTagsToMap = function(tags,id){ |
| 26 | + var saveCallback = function(response){ |
| 27 | + if(!response.ok) |
| 28 | + throw response; |
| 29 | + $rootScope.$emit("tagsUpdated"); |
| 30 | + }; |
| 31 | + |
| 32 | + var addTags = function(map){ |
| 33 | + tags.forEach(function(tag){ |
| 34 | + if(!map.tags[tag]) |
| 35 | + return (map.tags[tag]=[id]); |
| 36 | + return map.tags[tag].push(id); |
| 37 | + }); |
| 38 | + |
| 39 | + map._id="tagMap"; |
| 40 | + storageService.database().put(map).then(saveCallback); |
| 41 | + }; |
| 42 | + service.getMap().then(addTags,function(err){ |
| 43 | + if(err.status==404) |
| 44 | + return addTags({tags:{}});//Nothing found nothing to delete |
| 45 | + throw err; |
| 46 | + }); |
| 47 | + }; |
| 48 | + |
| 49 | + /** |
| 50 | + * Remove all tags for an id |
| 51 | + * @param id - the id to remove tags for |
| 52 | + * @param callback - calls on sucessful return |
| 53 | + */ |
| 54 | + var deleteTagsFromMap = function(id,callback){ |
| 55 | + service.getMap().then(function(map){ |
| 56 | + //Remove all tags from array |
| 57 | + for(var tag in map.tags){ |
| 58 | + var index = map.tags[tag].indexOf(id); |
| 59 | + if(index == -1) |
| 60 | + continue; |
| 61 | + map.tags[tag].splice(index, 1); |
| 62 | + if(!map.tags[tag].length) |
| 63 | + delete map.tags[tag]; |
| 64 | + } |
| 65 | + |
| 66 | + //Save |
| 67 | + storageService.database().put(map).then(function(response){ |
| 68 | + if(!response.ok) |
| 69 | + throw response; |
| 70 | + $rootScope.$emit("tagsUpdated"); |
| 71 | + return callback(); |
| 72 | + }); |
| 73 | + },function(err){ |
| 74 | + if(err.status==404) |
| 75 | + return callback();//Nothing found nothing to delete |
| 76 | + throw err; |
| 77 | + }); |
| 78 | + }; |
| 79 | + |
| 80 | + /** |
| 81 | + * Get the map |
| 82 | + * @return - a promise that when resolves return the tag map |
| 83 | + */ |
| 84 | + this.getMap = function(){ |
| 85 | + return storageService.database().get("tagMap"); |
| 86 | + }; |
| 87 | +}); |
0 commit comments