-
Notifications
You must be signed in to change notification settings - Fork 0
/
insertTestData.js
72 lines (56 loc) · 1.75 KB
/
insertTestData.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
67
68
69
70
71
72
/**
* Colly | insert test data into database
*/
import mongoose from "mongoose"
import { promises as fs } from "fs"
import { connectDbAsync } from "./app/init.js"
const User = mongoose.model("User")
const Tag = mongoose.model("Tag")
const Item = mongoose.model("Item")
const deleteData = async () => {
await User.collection.drop()
await Tag.collection.drop()
await Item.collection.drop()
}
const replaceIdsInObject = (obj) => {
for (const key in obj) {
const val = obj[key]
if (Array.isArray(val)) {
obj[key] = replaceIdsInObject(val)
}
if (val.length === 24 && val[23] !== "=") {
obj[key] = new mongoose.Types.ObjectId(val)
}
if (val.length === 24 && val[23] === "=") {
obj[key] = new mongoose.Types.UUID(
Buffer.from(val, "base64").toString("hex")
)
}
}
return obj
}
const convertIdsToObjectIds = (data) => {
return data.map(replaceIdsInObject)
}
const importData = async () => {
const userContent = await fs.readFile(
"./test-data/content/user.json",
"utf8"
)
const tagContent = await fs.readFile("./test-data/content/tag.json", "utf8")
const itemContent = await fs.readFile(
"./test-data/content/item.json",
"utf8"
)
const users = JSON.parse(userContent)
const tags = JSON.parse(tagContent)
const items = JSON.parse(itemContent)
await User.collection.insertMany(convertIdsToObjectIds(users))
await Tag.collection.insertMany(convertIdsToObjectIds(tags))
await Item.collection.insertMany(convertIdsToObjectIds(items))
}
await connectDbAsync()
await deleteData()
console.log("Deleted existing data")
await importData()
console.log("Imported test data")