forked from remarcmij/database_examples
-
Notifications
You must be signed in to change notification settings - Fork 5
/
3-db-promise.js
79 lines (71 loc) · 1.92 KB
/
3-db-promise.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
const fs = require('fs');
const mysql = require('mysql');
function execQuery(con, sql, args = []) {
return new Promise((resolve, reject) => {
con.query(sql, args, (err, rows) => {
if (err) {
reject(err);
} else {
resolve(rows);
}
});
});
}
function readFile(path, encoding = 'utf8') {
return new Promise((resolve, reject) => {
fs.readFile(path, encoding, (err, data) => {
if (err) {
reject(err);
} else {
resolve(data);
}
});
});
}
const CONNECTION_CONFIG = {
host: 'localhost',
user: 'hyfuser',
password: 'hyfpassword',
database: 'userdb',
};
const CREATE_STUDENTS_TABLE = `
CREATE TABLE IF NOT EXISTS students (
student_number INT,
student_name VARCHAR(50),
date_of_birth DATE,
grade FLOAT,
gender ENUM('m', 'f')
);`;
const CREATE_TEACHERS_TABLE = `
CREATE TABLE IF NOT EXISTS teachers (
teacher_number INT,
teacher_name VARCHAR(50),
date_of_birth DATE,
subject TEXT,
gender ENUM('m', 'f')
);`;
async function seedDatabase() {
const connection = mysql.createConnection(CONNECTION_CONFIG);
// Promise chaining
// execQuery() and readFile() functions must return promise
// In other words, they do something that is async (DB connection, read file etc.)
// To get the results of the query, then() method of the returned promise must be called
execQuery(connection, CREATE_STUDENTS_TABLE)
.then(() => execQuery(connection, CREATE_TEACHERS_TABLE))
.then(() => readFile(__dirname + '/students.json', 'utf8'))
.then(data => JSON.parse(data))
.then(students => {
const promises = students.map(student =>
execQuery(connection, 'INSERT INTO students SET ?', student),
);
return Promise.all(promises);
})
.then(() => {
connection.end();
})
.catch(err => {
console.error(err.message);
connection.end();
});
}
seedDatabase();