Skip to content

Instantly share code, notes, and snippets.

@radzionc
Created February 26, 2018 11:17
Show Gist options
  • Save radzionc/f7844131660c31029ee5594a1f6e0130 to your computer and use it in GitHub Desktop.
Save radzionc/f7844131660c31029ee5594a1f6e0130 to your computer and use it in GitHub Desktop.
require('dotenv').config()
require('../src/utils/aws').setupAWS()
const _ = require('lodash')
const AWS = require('aws-sdk')
const { TABLES_PARAMS } = require('../src/constants/db')
const migrations = require('../src/migrations')
const prepareDB = async () => {
const database = new AWS.DynamoDB()
const neededTables = TABLES_PARAMS.map(({ TableName }) => TableName)
const existingTables = await database
.listTables()
.promise()
.then(data => data.TableNames)
const dbsToDelete = _.without(existingTables, ...neededTables)
const dbsToCreate = _.without(neededTables, ...existingTables)
await Promise.all(
dbsToDelete.map(TableName =>
database.deleteTable({ TableName }).promise()
)
)
await Promise.all(
dbsToCreate.map(TableName =>
database
.createTable(TABLES_PARAMS.find(t => t.TableName === TableName))
.promise()
)
)
const documentClient = new AWS.DynamoDB.DocumentClient()
const migration = await documentClient
.get({
TableName: 'Management',
Key: { id: 'migration' }
})
.promise()
.then(({ Item }) => Item)
if (
migration.lastMigration !== undefined &&
migration.lastMigration < migrations.length
) {
const migrationsToRun = migrations.slice(migration.lastMigration + 1)
await Promise.all(migrationsToRun.map(migration => migration()))
}
await documentClient
.put({
TableName: 'Management',
Item: {
id: 'migration',
lastMigration: migrations.length - 1
}
})
.promise()
}
prepareDB()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment