-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdatabaseUtils.js
More file actions
92 lines (79 loc) · 2.17 KB
/
databaseUtils.js
File metadata and controls
92 lines (79 loc) · 2.17 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
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
88
89
90
91
92
"use strict";
const AWS = require("aws-sdk");
class DatabaseUtils {
constructor(config) {
this.config = config;
console.log("Using configuration:", config);
this.dbOptions = { region: config.MIGRATIONS_DB_REGION };
if (!config.REMOTE) {
this.dbOptions.endpoint = config.MIGRATIONS_DB_ENDPOINT;
}
console.log("Seeting up DB:", this.dbOptions);
this.db = new AWS.DynamoDB(this.dbOptions);
}
async verifyMigrationsTableExistence() {
try {
console.log("verifyMigrationsTableExistence");
const data = await this.describeTable();
} catch (err) {
console.error(err);
// Table doesn't exist, create it
if (err.code === "ResourceNotFoundException") {
await this.createMigrationsTable();
// Wait for table to be active
for (let i = 0; i < 10; i++) {
const data = await this.describeTable();
if (data.Table.TableStatus !== "ACTIVE") {
await new Promise((r) => setTimeout(r, 2000));
} else {
break;
}
}
} else {
console.log("Failed to verify table status", err);
throw err;
}
}
}
async describeTable() {
console.log("Getting ", this.config.MIGRATIONS_TABLE_NAME)
return this.db
.describeTable({ TableName: this.config.MIGRATIONS_TABLE_NAME })
.promise();
}
async createMigrationsTable() {
try {
const params = {
AttributeDefinitions: [
{
AttributeName: "pk",
AttributeType: "S",
},
{
AttributeName: "sk",
AttributeType: "S",
},
],
KeySchema: [
{
AttributeName: "pk",
KeyType: "HASH",
},
{
AttributeName: "sk",
KeyType: "RANGE",
},
],
ProvisionedThroughput: {
ReadCapacityUnits: 1,
WriteCapacityUnits: 1,
},
TableName: this.config.MIGRATIONS_TABLE_NAME,
};
await this.db.createTable(params).promise();
} catch (err) {
console.log("Failed to create table", err);
}
}
}
module.exports = DatabaseUtils;