-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathuniqueNumberGenerator.js
More file actions
60 lines (55 loc) · 2.3 KB
/
uniqueNumberGenerator.js
File metadata and controls
60 lines (55 loc) · 2.3 KB
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
'strict';
const cds = require('@sap/cds');
module.exports = class uniqueNumberGenerator {
static async getNextNumber(sequenceName, dbKind, poetrySlamID) {
let nextNumber;
let result;
switch (dbKind) {
case 'hana':
// With HANA Cloud, the embedded functionality of numbering by sequence is used.
// The sequence is a database object that is used to automatically generate the incremented list of numeric values.
// Sequence specification file used in the generating process: ./db/src/poetrySlamNumber.hdbsequence
// NEXTVAL function is used to retrieve the next value in the sequence
nextNumber = await cds.run(
`SELECT "${sequenceName}".NEXTVAL AS NEXTNO FROM DUMMY`
);
// Return the result as string
return nextNumber[0]['NEXTNO'].toString();
case 'sqlite':
// With sqlite db, Auto-increment is used.
// Auto increment generates a unique number automatically when a new record is inserted into a table.
// First, check if sequencename pattern is correct
if (!sequenceName.match(/^[A-Za-z0-9_-]*$/)) {
console.error(`Invalid Sequencename: ${sequenceName}`);
throw new Error(`Invalid Sequencename: ${sequenceName}`);
}
try {
await cds.run(
INSERT.into(sequenceName).columns('ID').values(poetrySlamID)
);
} catch (error) {
// If the table does not exist, it has to be created under the name: sequencename.
console.log(
`[PoetrySlam uniqueNumberGenerator.js]: sqlite SEQUENCE not found - creating sequence (error: ${error})`
);
await cds.run(
`CREATE TABLE "${sequenceName}" (number INTEGER PRIMARY KEY AUTOINCREMENT, ID TEXT NOT NULL)`
);
await cds.run(
INSERT.into(sequenceName).columns('ID').values(poetrySlamID)
);
}
// Read the number of the newly inserted record
result = await cds.run(
SELECT.one
.from(sequenceName)
.columns('number')
.where({ ID: poetrySlamID })
);
return result.number.toString();
default:
console.error(`Invalid Database type: ${dbKind}`);
throw new Error(`Invalid Database type: ${dbKind}`);
}
}
};