Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Aws sdk v3 #25

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -108,3 +108,5 @@ dist
build

.DS_Store

.vscode/
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was so free to add this to .gitignore as we also ignore '.idea'

17,167 changes: 10,028 additions & 7,139 deletions package-lock.json

Large diffs are not rendered by default.

5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,8 @@
"build/**/*"
],
"dependencies": {
"aws-sdk": "^2.1113.0",
"@aws-sdk/client-dynamodb": "^3.556.0",
"@aws-sdk/credential-providers": "^3.556.0",
"cli-table3": "^0.6.3",
"commander": "^9.1.0",
"del": "^6.0.0",
Expand All @@ -61,7 +62,7 @@
"@types/sinon": "^10.0.13",
"@typescript-eslint/eslint-plugin": "^5.21.0",
"@typescript-eslint/parser": "^5.23.0",
"aws-sdk-mock": "^5.8.0",
"aws-sdk-client-mock": "^4.0.0",
"babel-jest": "^29.4.3",
"dynalite": "^3.2.2",
"eslint": "^7.32.0",
Expand Down
1 change: 1 addition & 0 deletions src/lib/actions/down.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import * as AWS from '@aws-sdk/client-dynamodb';
import pEachSeries from 'p-each-series';
import { status } from './status';
import * as migrationsDir from '../env/migrationsDir';
Expand Down
2 changes: 2 additions & 0 deletions src/lib/env/fileLoader/fileLoader.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import * as AWS from '@aws-sdk/client-dynamodb';

export interface Migration {
up(ddb: AWS.DynamoDB): Promise<void>;
down(ddb: AWS.DynamoDB): Promise<void>;
Expand Down
126 changes: 65 additions & 61 deletions src/lib/env/migrationsDb.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,25 @@
import AWS from 'aws-sdk';
import { Key } from 'aws-sdk/clients/dynamodb';
import * as AWS from '@aws-sdk/client-dynamodb';
import { AttributeValue, CreateTableCommandInput, waitUntilTableExists } from '@aws-sdk/client-dynamodb';
import { fromIni } from '@aws-sdk/credential-providers';
import * as config from './config';

export async function getDdb(profile = 'default') {
await loadAwsConfig(profile);
return new AWS.DynamoDB({ apiVersion: '2012-08-10' });
const awsConfig = await loadAwsConfig(profile);
return new AWS.DynamoDB({
apiVersion: '2012-08-10',
region: awsConfig.region,
credentials: { accessKeyId: awsConfig.accessKeyId, secretAccessKey: awsConfig.secretAccessKey },
});
}

export async function configureMigrationsLogDbSchema(ddb: AWS.DynamoDB) {
const params = {
export type AWSConfig = {
region: string;
accessKeyId: string;
secretAccessKey: string;
};

export async function configureMigrationsLogDbSchema(ddb: AWS.DynamoDB, maxWaitTimeForTableCreation = 120) {
const params: CreateTableCommandInput = {
AttributeDefinitions: [
{
AttributeName: 'FILE_NAME',
Expand Down Expand Up @@ -38,24 +49,20 @@ export async function configureMigrationsLogDbSchema(ddb: AWS.DynamoDB) {
StreamEnabled: false,
},
};
ddb.createTable(params, function callback(err) {
if (err) {
throw err;
await ddb.createTable(params);

try {
const tableExists = await waitUntilTableExists(
{ client: ddb, maxWaitTime: maxWaitTimeForTableCreation },
{ TableName: 'MIGRATIONS_LOG_DB' },
);
if (tableExists.state === 'SUCCESS') {
return await Promise.resolve();
}
});

const migrationParam = {
TableName: 'MIGRATIONS_LOG_DB',
};
return new Promise((resolve, reject) => {
ddb.waitFor('tableExists', migrationParam, async function callback(err, data) {
if (err) {
reject(err);
} else {
resolve(data);
}
});
});
return await Promise.reject(new Error('Migration table does not exist!'));
} catch {
return Promise.reject(new Error('Migration table does not exist!'));
}
}

export async function addMigrationToMigrationsLogDb(item: { fileName: string; appliedAt: string }, ddb: AWS.DynamoDB) {
Expand All @@ -68,16 +75,12 @@ export async function addMigrationToMigrationsLogDb(item: { fileName: string; ap
};

// Call DynamoDB to add the item to the table

return new Promise((resolve, reject) => {
ddb.putItem(params, async function callback(err, data) {
if (err) {
reject(err);
} else {
resolve(data);
}
});
});
try {
const data = await ddb.putItem(params);
return await Promise.resolve(data);
} catch (error) {
return Promise.reject(error);
}
}

export async function deleteMigrationFromMigrationsLogDb(
Expand All @@ -92,41 +95,35 @@ export async function deleteMigrationFromMigrationsLogDb(
},
};

return new Promise((resolve, reject) => {
ddb.deleteItem(params, function callback(err, data) {
if (err) {
reject(err);
} else {
resolve(data);
}
});
});
try {
const data = await ddb.deleteItem(params);
return await Promise.resolve(data);
} catch (error) {
return Promise.reject(error);
}
}

export async function doesMigrationsLogDbExists(ddb: AWS.DynamoDB) {
const params = {
TableName: 'MIGRATIONS_LOG_DB',
};
return new Promise((resolve) => {
ddb.describeTable(params, function callback(err) {
if (err) {
resolve(false);
} else {
resolve(true);
}
});
});
try {
const data = await ddb.describeTable(params);
return await Promise.resolve(true);
} catch {
return Promise.resolve(false);
}
}

export async function getAllMigrations(ddb: AWS.DynamoDB) {
const migrations: { FILE_NAME?: string; APPLIED_AT?: string }[] = [];
const recursiveProcess = async (lastEvaluatedKey?: Key) => {
const recursiveProcess = async (lastEvaluatedKey?: Record<string, AttributeValue>) => {
const params = {
TableName: 'MIGRATIONS_LOG_DB',
ExclusiveStartKey: lastEvaluatedKey,
};

const { Items, LastEvaluatedKey } = await ddb.scan(params).promise();
const { Items, LastEvaluatedKey } = await ddb.scan(params);
if (Items)
migrations.push(
...Items.map((item) => {
Expand All @@ -144,7 +141,13 @@ export async function getAllMigrations(ddb: AWS.DynamoDB) {
return migrations;
}

async function loadAwsConfig(inputProfile: string) {
async function loadAwsConfig(inputProfile: string): Promise<AWSConfig> {
const resultConfig: AWSConfig = {
accessKeyId: '',
secretAccessKey: '',
region: '',
};

const configFromFile = await config.loadAWSConfig();

// Check for data for input profile
Expand All @@ -156,18 +159,19 @@ async function loadAwsConfig(inputProfile: string) {

// Populate region
if (profileConfig && profileConfig.region) {
AWS.config.region = profileConfig.region;
resultConfig.region = profileConfig.region;
} else {
throw new Error(`Please provide region for profile:${inputProfile}`);
}

if (profileConfig && profileConfig.accessKeyId && profileConfig.secretAccessKey) {
AWS.config.update({
accessKeyId: profileConfig.accessKeyId,
secretAccessKey: profileConfig.secretAccessKey,
});
resultConfig.accessKeyId = profileConfig.accessKeyId;
resultConfig.secretAccessKey = profileConfig.secretAccessKey;
} else {
// Load config from shared credentials file if present
AWS.config.credentials = new AWS.SharedIniFileCredentials({ profile: inputProfile });
// Load config from shared credentials ini file if present
const credentials = await fromIni({ profile: inputProfile })();
resultConfig.accessKeyId = credentials.accessKeyId;
resultConfig.secretAccessKey = credentials.secretAccessKey;
}
return resultConfig;
}
4 changes: 2 additions & 2 deletions tests/lib/actions/down.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import AWS from 'aws-sdk';
import * as AWS from '@aws-sdk/client-dynamodb'
import { down } from "../../../src/lib/actions/down";

import * as statusModule from '../../../src/lib/actions/status';
Expand Down Expand Up @@ -36,7 +36,7 @@ describe("down", () => {
jest.spyOn(migrationsDb, "getDdb").mockResolvedValue( new AWS.DynamoDB({ apiVersion: '2012-08-10' }));


migrationsDbDeleteMigrationFromMigrationsLogDb = jest.spyOn(migrationsDb, "deleteMigrationFromMigrationsLogDb").mockReturnValue(Promise.resolve());
migrationsDbDeleteMigrationFromMigrationsLogDb = jest.spyOn(migrationsDb, "deleteMigrationFromMigrationsLogDb").mockReturnValue(Promise.resolve({ $metadata: {} }));
});


Expand Down
2 changes: 1 addition & 1 deletion tests/lib/actions/status.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import AWS from "aws-sdk";
import * as AWS from '@aws-sdk/client-dynamodb'
import { status } from "../../../src/lib/actions/status";

import * as migrationsDir from '../../../src/lib/env/migrationsDir';
Expand Down
6 changes: 3 additions & 3 deletions tests/lib/actions/up.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import AWS from 'aws-sdk';
import * as AWS from '@aws-sdk/client-dynamodb'
import sinon from 'sinon';
import { up } from "../../../src/lib/actions/up"

Expand All @@ -14,7 +14,7 @@ describe("up", () => {
let migrationsDbAddMigrationToMigrationsLogDb: jest.SpyInstance;
let migrationsDbCheckMigrationLog: jest.SpyInstance;
let migrationsDbConfigureMigrationsLogDbSchema: jest.SpyInstance;
const awsConfig = new AWS.DynamoDB({ apiVersion: '2012-08-10' });
const awsConfig = new AWS.DynamoDB ({ apiVersion: '2012-08-10' });

beforeEach(() => {
migrationsDbCheckMigrationLog = jest.spyOn(migrationsDb, "doesMigrationsLogDbExists").mockResolvedValue(true);
Expand Down Expand Up @@ -55,7 +55,7 @@ describe("up", () => {

jest.spyOn(migrationsDb, "getDdb").mockResolvedValue(awsConfig);

migrationsDbAddMigrationToMigrationsLogDb = jest.spyOn(migrationsDb, "addMigrationToMigrationsLogDb").mockReturnValue(Promise.resolve());
migrationsDbAddMigrationToMigrationsLogDb = jest.spyOn(migrationsDb, "addMigrationToMigrationsLogDb").mockReturnValue(Promise.resolve({ $metadata: {} }));
migrationsDbConfigureMigrationsLogDbSchema = jest.spyOn(migrationsDb, "configureMigrationsLogDbSchema").mockReturnValue(Promise.resolve());
});

Expand Down
Loading