-
Notifications
You must be signed in to change notification settings - Fork 0
/
HttpTriggerSQLServerTedious.js
87 lines (72 loc) · 2.6 KB
/
HttpTriggerSQLServerTedious.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
87
module.exports = function (context, req) {
context.log('JavaScript HTTP trigger function processed a request.');
const Connection = require('tedious').Connection;
const Request = require('tedious').Request;
const data = req.body;
// change config file
const config = {
userName: 'username',
password: 'password',
server: 'example.database.windows.net',
options: {
database: 'SecureTravel',
encrypt: true // enable it in Azure Functions
}
}
const connection = new Connection(config);
connection.on('connect', function (err) {
if (err) {
context.log(err);
} else {
context.log('Connected');
insertHistorical();
}
});
function insertHistorical() {
results = [];
request = new Request(
`insert into historicals(full_name, email, department) values ('${data.name}', '${data.email}', '${data.department}'); select @@identity`,
function (err, rowCount) {
if (err) {
context.log(err);
}
if (rowCount > 0) {
context.log('Historical inserted');
}
});
request.on('row', function (columns) {
results.push(columns[0].value);
});
request.on('requestCompleted', function () {
context.log(results[0]);
insertPeriod(results[0]);
});
connection.execSql(request);
}
function insertPeriod(id) {
let query = `insert into periods(historical_id, destination, start_date, end_date) values `;
for (let i = 0; i < data.destinations.length; i++) {
if (i == data.destinations.length - 1) {
query += `('${id}', '${data.destinations[i].destiny}', '${data.destinations[i].firstDate}', '${data.destinations[i].lastDate}') `;
} else {
query += `('${id}', '${data.destinations[i].destiny}', '${data.destinations[i].firstDate}', '${data.destinations[i].lastDate}'), `;
}
}
request = new Request(query,
function (err, rowCount) {
if (err) {
context.log(err);
} else {
context.log('Periods inserted');
}
});
request.on('requestCompleted', function () {
connection.close();
context.res = {
body: "Rows Inserted"
};
context.done();
});
connection.execSql(request);
}
};