server/services/database/share.js
Artem Anufrij 50c682e31f
All checks were successful
continuous-integration/drone/push Build is passing
wip sharing api
2023-02-16 18:19:42 +01:00

92 lines
2.1 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":
console.log(result.type);
database.albums.byId(result.object_id, undefined, (album) => {
result.object = album;
cb(callback, result);
});
break;
case "box":
console.log(result.type);
database.boxes.byId(result.object_id, undefined, (box) => {
result.object = box;
cb(callback, result);
});
break;
default:
console.log(result.type);
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);
}
}