-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfindId.js
66 lines (58 loc) · 2.28 KB
/
findId.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
const { MongoClient, ServerApiVersion } = require("mongodb");
const { config } = require("./config");
const uri = `mongodb+srv://${config.mongoDbCredentials}${config.mongoDbCredentialsLastPart}`;
const client = new MongoClient(uri, {
serverApi: ServerApiVersion.v1,
});
const database = client.db(config.dbName);
const collectionData = database.collection(config.collectionName);
/**
* Receives a JSON object as input and returns a list of items from the database that match the input.
* The keys of the input JSON are matched with a predetermined key mapping.
* If a key is found in the input JSON, it is used to form a query which is then executed against the MongoDB collection.
*
* @param {Object} json - The JSON object that contains the data to search for. Valid keys include 'title', 'allocineid',
* 'betaseriesid', 'imdbid', 'letterboxdid', 'metacriticid', 'rottentomatoesid', 'senscritiqueid', 'thetvdbid', 'tmdbid', 'traktid', 'tvtimeid'.
* @returns {Object} An object containing two properties: 'results' which is an array of matching documents from the database,
* and 'total_results', which is the total count of matching documents.
*/
const findId = async (json) => {
const keysMapping = {
allocineid: "allocine.id",
betaseriesid: "betaseries.id",
imdbid: "imdb.id",
letterboxdid: "letterboxd.id",
metacriticid: "metacritic.id",
rottentomatoesid: "rotten_tomatoes.id",
senscritiqueid: "senscritique.id",
title: null,
tmdbid: "id",
traktid: "trakt.id",
tvtimeid: "tv_time.id",
thetvdbid: "thetvdb.id",
};
let query = {};
for (let key in keysMapping) {
if (json.hasOwnProperty(key)) {
const mappedKey = keysMapping[key];
query[mappedKey != null ? mappedKey : key] = ["title"].includes(key)
? { $regex: json[key], $options: "i" }
: [
"allocineid",
"senscritiqueid",
"thetvdbid",
"tmdbid",
"tvtimeid",
].includes(key)
? parseInt(json[key])
: json[key];
break;
}
}
const [results, total_results] = await Promise.all([
collectionData.find(query).toArray(),
collectionData.countDocuments(query),
]);
return { results: results, total_results: total_results };
};
module.exports = findId;