crunch-node/category.js

96 lines
2.5 KiB
JavaScript

var moment = require("moment");
var _ = require("lodash");
var schemas = require('./schemas.js');
var Category = function(data) {
this.data = data;
}
Category.prototype.data = {}
Category.prototype.get = function (name) {
return this.data[name];
}
Category.prototype.set = function (name, value) {
this.data[name] = value;
}
Category.prototype.sanitize = function (data) {
data = data || {};
schema = schemas.category;
return _.pick(_.defaults(data, schema), _.keys(schema));
}
Category.prototype.save = function (callback) {
var self = this;
this.data = this.sanitize(this.data);
db.collection("categories").save(this.data, callback(err));
}
// Function to get a YYYY-MM-DD format of the current CategoryDate
// Requires no arguments.
Category.prototype.getShortDate = function () {
return moment(this.get("createdDate")).format("YYYY-MM-DD");
}
// Get a specific category by its name
// Returns a Category object
Category.getByName = function (name, callback) {
db.collection("categories").findOne({name: name}, function(err, doc) {
callback(err, new Category(doc));
});
}
// Get a specific category by its UUID
// Returns a Category object
Category.getByUUID = function (uuid, callback) {
db.collection("categories").findOne({uuid: uuid}, function(err, doc) {
callback(err, new Category(doc));
});
}
// Function to get a count of current Categories
// Returns count of Categories
Category.countCategories = function(callback) {
db.collection("categories").find({}).count(function (err, count) {
if (err) console.log(err);
callback(err, count);
});
}
// Function to get a list of all existing categories
// Start and count are optional, but if start is used, count must be used as well.
// Returns an array of Category objects
Category.getCategories = function(count, start, callback) {
if (typeof callback === undefined) {
if (typeof start === undefined) {
callback = count;
count = undefined;
start = undefined;
}
else {
callback = start;
start = undefined;
}
}
var options = {}
if (start) options.skip=start;
if (count) options.limit=count;
options.sort = {name: 1};
db.collection("categories").find({}, options).toArray(function(err, docs) {
if (err) console.log(err);
var rows = [];
for (i=0; i<docs.length; i++) {
rows.push(new Category(docs[i]));
}
callback(null, rows);
});
}
module.exports = Category;