-
Notifications
You must be signed in to change notification settings - Fork 39
/
setup.js
72 lines (59 loc) · 2.02 KB
/
setup.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
const {resolve} = require('path');
const cwd = require('cwd');
const {DynamoDB} = require('@aws-sdk/client-dynamodb');
const DynamoDbLocal = require('dynamodb-local');
const debug = require('debug')('jest-dynamodb');
const waitForLocalhost = require('./wait-for-localhost');
// aws-sdk requires access and secret key to be able to call DDB
process.env.AWS_ACCESS_KEY_ID = 'access-key';
process.env.AWS_SECRET_ACCESS_KEY = 'secret-key';
const DEFAULT_PORT = 8000;
const DEFAULT_OPTIONS = ['-sharedDb'];
module.exports = async function () {
const config = require(resolve(cwd(), 'jest-dynamodb-config.js'));
const {
tables: newTables,
clientConfig,
installerConfig,
port: port = DEFAULT_PORT,
options: options = DEFAULT_OPTIONS
} = typeof config === 'function' ? await config() : config;
const dynamoDB = new DynamoDB({
endpoint: `http://localhost:${port}`,
tls: false,
region: 'local-env',
credentials: {
accessKeyId: 'fakeMyKeyId',
secretAccessKey: 'fakeSecretAccessKey'
},
...clientConfig
});
global.__DYNAMODB_CLIENT__ = dynamoDB;
try {
const {TableNames: tableNames} = await Promise.race([
dynamoDB.listTables({}),
waitForLocalhost(DEFAULT_PORT)
]);
await deleteTables(dynamoDB, tableNames); // cleanup leftovers
} catch (err) {
// eslint-disable-next-line no-console
debug(`fallback to launch DB due to ${err}`);
if (installerConfig) {
DynamoDbLocal.configureInstaller(installerConfig);
}
if (!global.__DYNAMODB__) {
debug('spinning up a local ddb instance');
global.__DYNAMODB__ = await DynamoDbLocal.launch(port, null, options);
await waitForLocalhost(DEFAULT_PORT);
}
}
await createTables(dynamoDB, newTables);
};
async function createTables(dynamoDB, tables) {
return Promise.all(tables.map(table => dynamoDB.createTable(table)));
}
async function deleteTables(dynamoDB, tableNames) {
return Promise.all(
tableNames.map(tableName => dynamoDB.deleteTable({TableName: tableName}).promise())
);
}