-
Notifications
You must be signed in to change notification settings - Fork 0
/
insert_data.js
86 lines (81 loc) · 2.38 KB
/
insert_data.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
require('babel-polyfill');
const dataFolder = './data';
const fs = require('fs');
const path = require('path');
const Ix = require('ix');
const promisify = require('util.promisify');
const request = require('request');
const readFileProm = promisify(fs.readFile);
const sessionName = "Reactivate quiz"
fs.readdir(dataFolder, (err, files) => {
const arrProm = files.map(file => readFileProm(path.join(dataFolder, file)));
Promise.all(arrProm).then(arr => {
const res = arr.map((data) => {
const question = JSON.parse(data.toString('utf-8'));
const optIds = question.options.map(opt => {
return new Promise((resolve, reject) => {
request({
uri: 'http://localhost:8080/option',
body: JSON.stringify({ title: opt.title }),
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
},
(err, res, body) => {
if (!err) {
resolve(body);
} else {
reject(err);
}
}
)
});
});
return Promise
.all(optIds)
.then((res) => {
const serializedRes = res.map(opt => JSON.parse(opt));
return new Promise((resolve, reject) => {
request({
uri: 'http://localhost:8080/question',
body: JSON.stringify({
title: question.title,
description: question.description,
optionIds: serializedRes.map(opt => opt.data._id),
rightOption: serializedRes.find((_, index) => index === question.rightOption).data._id
}),
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
},
(err, res, body) => {
if (!err) {
resolve(body);
} else {
reject(err);
}
})
})
});
});
return Promise.all(res);
})
.then(questions => {
request({
uri: 'http://localhost:8080/session',
body: JSON.stringify({
name: sessionName,
questionIds: questions.map(q => JSON.parse(q).data._id)
}),
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
},
(err, res, body) => {
console.log(body);
})
});
});