-
Notifications
You must be signed in to change notification settings - Fork 5
/
db-test.js
71 lines (60 loc) · 1.35 KB
/
db-test.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
const mysqlx = require('@mysql/xdevapi');
const randomstring = require("randomstring");
async function generateLink(url) {
try {
const session = await getDbConn()
const table = session.getSchema('n3_links').getTable('link')
const id = await generateUniqueId(table)
console.log("unique id?", id)
await insertLink(id, url, table)
} catch(error) {
console.log(error.info.msg)
}
}
function getDbConn() {
return mysqlx.getSession({
user: 'root',
password: '12345',
host: 'localhost',
port: '33060'
})
}
async function generateUniqueId(table) {
const id = ranString()
console.log("id?", id)
const exists = await checkId(id, table)
console.log("exists?", exists)
if (exists)
return generateUniqueId(table)
else
return id;
}
function checkId(id, table) {
return new Promise((resFn, rejFn) =>
table
.select([ 'url' ])
.where("id = :id")
.bind('id', id)
.execute()
.then((results) => resFn(results.fetchOne() !== undefined))
.catch((error) => rejFn(error))
)
}
function insertLink(id, url, table) {
return new Promise((resFn, rejFn) =>
table
.insert('id', 'url')
.values(id, url)
.execute()
.then(resFn)
.catch(rejFn)
)
}
var cnt = 0
function ranString() {
if (cnt++ == 0)
return "123"
else
return randomstring.generate(8)
}
generateLink("http://ppr.cs.dal.ca:3002/n3/editor?formula=somelongformula")