UNPKG

3.18 kBJavaScriptView Raw
1"use strict";
2
3// Dependencies
4const sift = require("sift")
5 , isThere = require("is-there")
6 , abs = require("abs")
7 , rJson = require("r-json")
8 , wJson = require("w-json")
9 ;
10
11// Constants
12const DEFAULT_PATH = abs("~/.ideas.json");
13
14/**
15 * Idea
16 *
17 * @name Idea
18 * @function
19 * @param {String} path The path to the JSON file where your ideas will be stored (default: `~/.ideas.json`).
20 * @param {Function} callback The callback function.
21 * @return {Idea} The `Idea` instance.
22 */
23class Idea {
24 constructor (path, callback) {
25 if (typeof path === "function") {
26 callback = path;
27 path = null;
28 }
29
30 // Defaults
31 this.path = path = path || DEFAULT_PATH;
32 callback = callback || (err => { if (err) throw err });
33
34 // Init
35 if (!isThere(this.path)) {
36 this.ideas = [];
37 this.save(callback);
38 } else {
39 this.list((err, ideas) => {
40 if (err) { return callback(err); }
41 this.ideas = ideas;
42 callback(null, ideas, this);
43 });
44 }
45 }
46 /**
47 * list
48 * Lists all ideas.
49 *
50 * @name list
51 * @function
52 * @param {Function} callback The callback function.
53 * @return {Idea} The `Idea` instance.
54 */
55 list (callback) {
56 rJson(this.path, (err, content) => {
57 if (err) { return callback(err); }
58 callback(err, content);
59 });
60 return this;
61 }
62 /**
63 * filter
64 * Filters ideas.
65 *
66 * @name filter
67 * @function
68 * @param {Object} filters An MongoDB like query object.
69 * @param {Function} callback The callback function.
70 * @return {Idea} The `Idea` instance.
71 */
72 filter (filters, callback) {
73 callback(null, sift(filters, this.ideas));
74 return this;
75 }
76 /**
77 * create
78 *
79 * @name create
80 * @function
81 * @param {String} idea The idea you have.
82 * @param {Function} callback The callback function.
83 * @return {Idea} The `Idea` instance.
84 */
85 create (idea, callback) {
86 if (!idea) {
87 return callback(new Error("Idea cannot be empty."));
88 }
89 this.ideas.push({
90 id: this.ideas.length
91 , idea: idea
92 , date: new Date()
93 , state: "OPEN"
94 });
95 return this;
96 }
97 /**
98 * solve
99 * Solves an idea.
100 *
101 * @name solve
102 * @function
103 * @param {String} id The idea id.
104 * @param {Function} callback The callback function.
105 * @return {Idea} The `Idea` instance.
106 */
107 solve (id, callback) {
108 if (!this.ideas[id - 1]) {
109 return callback(new Error("Cannot find any idea with this id."));
110 }
111 this.ideas[id - 1].state = "SOLVED";
112 return this;
113 }
114 /**
115 * save
116 * Saves the ideas in the file.
117 *
118 * @name save
119 * @function
120 * @param {Function} callback The callback function.
121 * @return {Idea} The `Idea` instance.
122 */
123 save (callback) {
124 wJson(this.path, this.ideas, callback);
125 return this;
126 }
127}
128
129module.exports = Idea;