src/functions/put.ts   A
last analyzed

Complexity

Total Complexity 3
Complexity/F 0

Size

Lines of Code 43
Function Count 0

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 3
eloc 32
mnd 3
bc 3
fnc 0
dl 0
loc 43
rs 10
bpm 0
cpm 0
noi 0
c 0
b 0
f 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
  const date = (new Date()).toISOString().replace(/\.|:|-|T|Z/g, "");
18
  let dateRadix36 = parseInt(date).toString(36);
19
  // @ts-ignore
20
  const client = new MongoClient(uri, {useNewUrlParser: true, useUnifiedTopology: true});
21
  await client.connect();
22
  const collection = client.db(dbName).collection(collectionName);
23
  const body = JSON.parse(event.body);
24
  while (await collection.find({"resourceId": dateRadix36}).limit(1).hasNext()) {
25
    dateRadix36 = (parseInt(dateRadix36, 36) + 1).toString(36);
26
  }
27
  // const newDocument = {"resourceId": dateRadix36};
28
  // const keys = Object.keys(body);
29
  // for (const key of keys) {
30
  //   // @ts-ignore
31
  //   newDocument[key] = body[key];
32
  // }
33
  await collection.insertOne({"resourceId": dateRadix36, ...body});
34
  await client.close();
35
36
  return {
37
    statusCode: 200,
38
    body: JSON.stringify({resourceId: dateRadix36})
39
  };
40
};
41
42
export {handler};
43