-
Notifications
You must be signed in to change notification settings - Fork 0
/
checkouts-import.ts
110 lines (97 loc) · 2.9 KB
/
checkouts-import.ts
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
import fs from "fs";
import { parse } from "csv-parse";
import { User } from "./models/User";
import { Score } from "./models/Score";
import { Checkout, checkoutSchema } from "./models/Checkout";
import { v4 as uuidv4 } from "uuid";
import mongoose from "mongoose";
require("dotenv").config();
// Ausfühhrung mit: ts-node checkouts-import.ts
// database connection
const dbURI = process.env.MONGODB_URL as string;
mongoose.set("strictQuery", false);
// mongoose.connect(dbURI, { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex:true }) // useCreateIndex not supported
mongoose
.connect(dbURI!)
.then((result: any) => importCsv())
.catch((err: any) => console.log(err));
async function importCsv() {
type CheckoutRecord = {
firstName: string;
lastName: string;
voice: string;
email: string;
scoreId: string;
comment: string;
};
type User = {
firstName: string;
lastName: string;
voice: string;
email: string;
};
const headers = [
"lastName",
"firstName",
"voice",
"email",
"scoreId",
"comment",
];
const parser = parse(
{ delimiter: ";", columns: headers },
async function (err, records: CheckoutRecord[]) {
// console.log(records);
const userMap = new Map<string, User>();
for (const record of records) {
console.log(record);
let user = userMap.get(record.lastName);
userMap.set(record.lastName, {
firstName: record.firstName,
lastName: record.lastName,
voice: record.voice,
email: record.email,
});
const email = record.email ? record.email : undefined;
try {
let user = record.email
? await User.findOne({ email: record.email })
: await User.findOne({ lastName: record.lastName });
if (user) {
console.log("Duplet: ", user.lastName);
} else {
user = await User.create({
email,
firstName: record.firstName,
lastName: record.lastName,
password: uuidv4(),
isManuallyRegistered: true,
});
}
const signature = "ORFF-COM";
const scoreId = signature + "-" + uuidv4();
const checkout = new Checkout({
userId: user.id,
scoreId,
checkoutTimestamp: new Date("2020-01-01"),
checkoutComment: record.comment,
});
const checkouts = [];
checkouts.push(checkout);
const score = await Score.create({
signature,
id: scoreId,
extId: record.scoreId,
checkedOutByUserId: user.id,
checkouts,
});
console.log(score._id);
} catch (e) {
console.error(e);
}
}
process.exit(0);
}
);
fs.createReadStream(process.env.CHECKOUTS_IMPORT_FILE!).pipe(parser);
}