Total Complexity | 4 |
Complexity/F | 0 |
Lines of Code | 38 |
Function Count | 0 |
Duplicated Lines | 0 |
Ratio | 0 % |
Changes | 0 |
1 | import {Handler} from "@netlify/functions"; |
||
2 | import {MongoClient} from "mongodb"; |
||
3 | |||
4 | const uri = `mongodb+srv://${process.env.MONGODB_USER}:${process.env.MONGODB_PASSWORD}@cluster0.k6gbu.mongodb.net/test_database?retryWrites=true&w=majority`; |
||
5 | const dbName = "replayerDB"; |
||
6 | const collectionName = "media"; |
||
7 | |||
8 | const handler: Handler = async (event, context) => { |
||
9 | if (event.httpMethod !== "POST") { |
||
10 | return {statusCode: 405, body: "Method Not Allowed"}; |
||
11 | } |
||
12 | |||
13 | if (!event.body) { |
||
14 | return {statusCode: 400, body: "Bad Request"}; |
||
15 | } |
||
16 | |||
17 | // @ts-ignore |
||
18 | const client = new MongoClient(uri, {useNewUrlParser: true, useUnifiedTopology: true}); |
||
19 | await client.connect(); |
||
20 | const collection = client.db(dbName).collection(collectionName); |
||
21 | const body = JSON.parse(event.body); |
||
22 | const query = collection.find({name: new RegExp(`${body.query}`)}) |
||
23 | .sort({_id: -1}).skip(body.startIndex); |
||
24 | |||
25 | let hasMore = true; |
||
26 | if (await query.count() <= body.endIndex) hasMore = false; |
||
27 | |||
28 | const documents = await query.limit(body.startIndex - body.endIndex).toArray(); |
||
29 | await client.close(); |
||
30 | |||
31 | return { |
||
32 | statusCode: 200, |
||
33 | body: JSON.stringify({documents: documents.length > 0 ? documents : null, hasMore}) |
||
34 | }; |
||
35 | }; |
||
36 | |||
37 | export {handler}; |
||
38 |