|
|
@@ -4,6 +4,7 @@
|
|
|
|
|
|
var MongoClient = require('mongodb').MongoClient,
|
|
|
ObjectId = require('mongodb').ObjectID,
|
|
|
+ async = require('async'),
|
|
|
HttpError = require('connect-lastmile').HttpError,
|
|
|
HttpSuccess = require('connect-lastmile').HttpSuccess;
|
|
|
|
|
|
@@ -12,11 +13,12 @@ exports = module.exports = {
|
|
|
getAll: getAll,
|
|
|
get: get,
|
|
|
add: add,
|
|
|
- del: del
|
|
|
+ del: del,
|
|
|
+ getTags: getTags
|
|
|
};
|
|
|
|
|
|
var databaseUrl = process.env.MONGODB_URL || 'mongodb://127.0.0.1:27017/guacamoly';
|
|
|
-var g_db, g_things;
|
|
|
+var g_db, g_things, g_tags;
|
|
|
|
|
|
function sanitize(data) {
|
|
|
data = data.replace(/##/g, data);
|
|
|
@@ -25,7 +27,7 @@ function sanitize(data) {
|
|
|
|
|
|
function facelift(data, tags) {
|
|
|
tags.forEach(function (tag) {
|
|
|
- data = data.replace(tag, '[' + tag + '](' + tag + ')', 'g');
|
|
|
+ data = data.replace(tag, '[' + tag.slice(1) + '](#' + tag.slice(1) + ')', 'g');
|
|
|
});
|
|
|
|
|
|
return data;
|
|
|
@@ -48,6 +50,7 @@ function init(callback) {
|
|
|
|
|
|
g_db = db;
|
|
|
g_things = db.collection('things');
|
|
|
+ g_tags = db.collection('tags');
|
|
|
|
|
|
callback(null);
|
|
|
});
|
|
|
@@ -93,19 +96,30 @@ function add(req, res, next) {
|
|
|
tags: tags
|
|
|
};
|
|
|
|
|
|
- g_things.insertMany([doc], function (error, result) {
|
|
|
- if (error || !result) return next(new HttpError(500, error));
|
|
|
+ async.eachSeries(tags, function (tag, callback) {
|
|
|
+ g_tags.update({ name: tag.slice(1) }, {
|
|
|
+ $inc: { usage: 1 },
|
|
|
+ $set: {
|
|
|
+ name: tag.slice(1)
|
|
|
+ }
|
|
|
+ }, { upsert:true }, callback);
|
|
|
+ }, function (error) {
|
|
|
+ if (error) return next(new HttpError(500, error));
|
|
|
|
|
|
- console.log('done', result);
|
|
|
+ g_things.insertMany([doc], function (error, result) {
|
|
|
+ if (error || !result) return next(new HttpError(500, error));
|
|
|
+
|
|
|
+ console.log('done', result);
|
|
|
|
|
|
- next(new HttpSuccess(201, { id: result._id }));
|
|
|
+ next(new HttpSuccess(201, { id: result._id }));
|
|
|
+ });
|
|
|
});
|
|
|
}
|
|
|
|
|
|
function del(req, res, next) {
|
|
|
console.log('del', req.params.id);
|
|
|
|
|
|
- g_things.deleteOne({ _id: ObjectId(req.params.id) }, function (error, result) {
|
|
|
+ g_things.deleteOne({ _id: new ObjectId(req.params.id) }, function (error, result) {
|
|
|
if (error || !result) return next(new HttpError(500, error));
|
|
|
|
|
|
console.log('done', result.result);
|
|
|
@@ -113,3 +127,13 @@ function del(req, res, next) {
|
|
|
next(new HttpSuccess(200, {}));
|
|
|
});
|
|
|
}
|
|
|
+
|
|
|
+function getTags(req, res, next) {
|
|
|
+ g_tags.find({}).sort({ createdAt: -1 }).toArray(function (error, result) {
|
|
|
+ if (error || !result) return next(new HttpError(500, error));
|
|
|
+
|
|
|
+ console.log('done', result);
|
|
|
+
|
|
|
+ next(new HttpSuccess(200, { tags: result }));
|
|
|
+ });
|
|
|
+}
|