server/services/database/share.js
Artem Anufrij f984acea9b
All checks were successful
continuous-integration/drone/push Build is passing
small clean ups
2023-02-16 23:55:40 +01:00

89 lines
2.0 KiB
JavaScript

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.exists = function (object_id, callback) {
dbo.collection("shares")
.findOne({ object_id: ObjectId(object_id) })
.then(result => {
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;
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);
}
}