const redis = require("../redis") const { ObjectId } = require('mongodb'); const connector = require("./CONNECTOR"); const database = require("./index"); var dbo; connector.connect().then((ret) => { dbo = ret; }); exports.byId = function (id, callback) { let _id; try { _id = ObjectId(id); } catch { cb(callback); return; } dbo.collection("shares") .findOne({ _id: _id }) .then((result) => { if (result) { switch (result.type) { case "album": database.albums.byId(result.object_id, undefined, (album) => { result.object = album; cb(callback, result); }); break; case "box": database.boxes.byId(result.object_id, undefined, (box) => { result.object = box; cb(callback, result); }); break; default: cb(callback, result); } } else { cb(callback); } }); } exports.collection = function (callback) { dbo.collection("shares") .find({}) .sort({ type: 1 }) .toArray((err, result) => { if (err) throw err; cb(callback, result); }); } exports.exists = function (object_id, callback) { dbo.collection("shares") .findOne({ object_id: ObjectId(object_id) }) .then(result => { cp(callback, result); }); } exports.add = function (item, callback) { let redis_key = item.type + "Id__" + item.object_id; redis.del(redis_key); dbo.collection("shares") .insertOne(item, err => { if (err) throw err; if (callback) { dbo.collection("shares") .aggregate([ { $sort: { _id: -1 } }, { $limit: 1 } ]) .toArray((err, result) => { if (err) throw err; cp(callback, result[0]); }) } }); } exports.delete = function (item, callback) { let redis_key = item.type + "Id__" + item.object_id; redis.del(redis_key); dbo.collection("shares") .deleteMany({ object_id: ObjectId(item.object_id) }, (err) => { if (err) throw err; cb(callback); }); } function cb(callback, value) { if (callback) { callback(value); } }