Created
October 25, 2022 00:46
-
-
Save gtracy/c876167a1d14251f2056cd1103d14748 to your computer and use it in GitHub Desktop.
Create a new DynamoDB table from NodeJS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
/***********************************************/ | |
// configure these values for your Dynamo table | |
// | |
const TABLE_NAME = 'FIXME'; | |
const table_params = { | |
TableName : TABLE_NAME, | |
KeySchema: [ | |
{ AttributeName: "FIXME", KeyType: "HASH"}, | |
], | |
AttributeDefinitions: [ | |
{ AttributeName: "FIXME", AttributeType: "S" }, | |
], | |
ProvisionedThroughput: { | |
ReadCapacityUnits: 10, | |
WriteCapacityUnits: 25 | |
} | |
}; | |
let aws_config = {}; | |
if( process.env.NODE_ENV === 'prod' ) { | |
aws_config = { | |
region : 'us-east-2', | |
access_id : process.env.AWS_ACCESS_ID, | |
access_secret : process.env.AWS_ACCESS_SECRET | |
} | |
} else { | |
aws_config = { | |
region : 'local', | |
endpoint : 'http://localhost:8000' | |
} | |
} | |
/***********************************************/ | |
let AWS = require('aws-sdk'); | |
AWS.config.update(aws_config); | |
(async () => { | |
let ddb = new AWS.DynamoDB({apiVersion: '2012-08-10'}); | |
console.log("\nAWS config :"); | |
console.dir(aws_config); | |
try { | |
console.log("... create the table if it doesn't already exist - "+TABLE_NAME); | |
let aws_result = await ddb.createTable(table_params, async (err, data) => { | |
if (err) { | |
if( !(err.code === "ResourceInUseException") ) { | |
// totally fine if the table already exists. | |
// otherwise, exit. | |
console.dir(err); | |
process.exit(1); | |
} else { | |
console.error("... table " + TABLE_NAME + " already exists"); | |
} | |
} else { | |
console.log("Created table. Table description JSON:", JSON.stringify(data, null, 2)); | |
console.log("... take a quick break, and give AWS a chance to create the table ..."); | |
await new Promise(r => setTimeout(r, 5000)); | |
console.log("\nall done.\n"); | |
} | |
}); | |
} catch(err) { | |
console.log('fail.'); | |
console.log(err); | |
process.exit(-1); | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment