server/services/database/share.js

99 lines
2.2 KiB
JavaScript
Raw Normal View History

2023-02-15 23:36:19 +01:00
const redis = require("../redis")
const { ObjectId } = require('mongodb');
const connector = require("./CONNECTOR");
2023-02-16 18:19:42 +01:00
const database = require("./index");
2023-02-15 23:36:19 +01:00
var dbo;
connector.connect().then((ret) => {
dbo = ret;
});
exports.byId = function (id, callback) {
2023-02-16 18:19:42 +01:00
let _id;
try {
_id = ObjectId(id);
} catch {
cb(callback);
return;
}
2023-02-15 23:36:19 +01:00
dbo.collection("shares")
2023-02-16 18:19:42 +01:00
.findOne({ _id: _id })
2023-02-15 23:36:19 +01:00
.then((result) => {
2023-02-16 18:19:42 +01:00
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);
}
2023-02-15 23:36:19 +01:00
});
}
2023-02-17 10:21:58 +01:00
exports.collection = function (callback) {
dbo.collection("shares")
.find({})
2023-02-17 22:06:11 +01:00
.sort({ type: 1 })
2023-02-17 10:21:58 +01:00
.toArray((err, result) => {
if (err) throw err;
cb(callback, result);
});
}
2023-02-15 23:36:19 +01:00
exports.exists = function (object_id, callback) {
dbo.collection("shares")
.findOne({ object_id: ObjectId(object_id) })
.then(result => {
2023-02-17 22:36:34 +01:00
cb(callback, result);
2023-02-15 23:36:19 +01:00
});
}
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;
2023-02-17 22:36:34 +01:00
cb(callback, result[0]);
2023-02-15 23:36:19 +01:00
})
}
});
}
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;
2023-02-16 18:19:42 +01:00
cb(callback);
2023-02-15 23:36:19 +01:00
});
2023-02-16 18:19:42 +01:00
}
2023-02-15 23:36:19 +01:00
2023-02-16 18:19:42 +01:00
function cb(callback, value) {
if (callback) {
callback(value);
}
2023-02-15 23:36:19 +01:00
}