Skip to content

Commit 45defa9

Browse files
committed
Updated examples with get started, and organised the examples. Added stringifier method to the partiQL insert example
1 parent 986fde1 commit 45defa9

17 files changed

+320
-173
lines changed

.gitIgnore

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
node_modules/
22
.DS_Store
3-
draft.js
3+
draft.js
4+
.env

MoviesLoadData.js

Lines changed: 0 additions & 30 deletions
This file was deleted.

aws-config.js

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
require('dotenv').config()
2+
const AWS = require("aws-sdk");
3+
4+
AWS.config.update({
5+
6+
region: "us-east-1",
7+
8+
// For security reasons, do not store AWS Credentials in your files.
9+
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
10+
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY
11+
});
12+
13+
module.exports = { AWS };

current.js

Lines changed: 0 additions & 85 deletions
This file was deleted.

getting-started/create-table.js

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
const { AWS } = require('../aws-config')
2+
3+
const dynamoDB = new AWS.DynamoDB();
4+
5+
async function createMoviesTable() {
6+
const params = {
7+
TableName : "Movies",
8+
KeySchema: [
9+
{ AttributeName: "year", KeyType: "HASH"},
10+
{ AttributeName: "title", KeyType: "RANGE" }
11+
],
12+
AttributeDefinitions: [
13+
{ AttributeName: "year", AttributeType: "N" },
14+
{ AttributeName: "title", AttributeType: "S" }
15+
],
16+
ProvisionedThroughput: {
17+
ReadCapacityUnits: 5,
18+
WriteCapacityUnits: 5
19+
}
20+
};
21+
22+
try {
23+
const table = await dynamoDB.createTable(params).promise();
24+
} catch(e) {
25+
console.log("An error occurred while creating the table", e)
26+
throw new Error("Failed to create a table")
27+
}
28+
}
29+
30+
module.exports = { createMoviesTable };

getting-started/index.js

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
const { AWS } = require('../aws-config')
2+
const { createMoviesTable } = require('./create-table');
3+
const { uploadMoviesData } = require('./upload-data');
4+
5+
const dynamoDB = new AWS.DynamoDB();
6+
7+
const checkIfTableExists = async () => {
8+
try {
9+
const table = await dynamoDB.describeTable({TableName: 'Movies'}).promise();
10+
return true;
11+
} catch(e) {
12+
if (e.code === "ResourceNotFoundException") {
13+
return false;
14+
} else {
15+
throw new Error("An error occured while checking for table")
16+
}
17+
}
18+
}
19+
20+
const setupTableAndData = async() => {
21+
try {
22+
const isTableExist = await checkIfTableExists();
23+
if (isTableExist) {
24+
console.log(`A table called 'Movies' already exists.`)
25+
} else {
26+
console.log(`Creating Table called 'Movies'`)
27+
await createMoviesTable();
28+
await sleep(10000); // a small delay to wait for the table to be ready on dynamoDb side
29+
console.log(`Table called 'Movies' created. Uploading sample data. This will take a few minutes.`)
30+
await uploadMoviesData();
31+
console.log('Done');
32+
}
33+
} catch(e) {
34+
console.log("Something wrong happened", e)
35+
}
36+
}
37+
38+
function sleep(ms) {
39+
return new Promise((resolve) => {
40+
setTimeout(resolve, ms);
41+
});
42+
}
43+
44+
setupTableAndData();

getting-started/upload-data.js

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
const { AWS } = require('../aws-config')
2+
const sampleData = require('../sample-data/moviedata.json')
3+
4+
const docClient = new AWS.DynamoDB.DocumentClient();
5+
6+
async function uploadMoviesData() {
7+
const allMovies = sampleData;
8+
let num = 0;
9+
for (const movie of allMovies) {
10+
const params = {
11+
TableName: "Movies",
12+
Item: {
13+
"year": movie.year,
14+
"title": movie.title,
15+
"info": movie.info
16+
}
17+
};
18+
try {
19+
await docClient.put(params).promise();
20+
console.log(`Added ${movie.title}`)
21+
num++;
22+
} catch(err) {
23+
console.log("Unable to add movie", movie.title, ". Error JSON:", JSON.stringify(err, null, 2))
24+
}
25+
};
26+
console.log(`Added ${num} movies to the table`)
27+
}
28+
29+
30+
module.exports = { uploadMoviesData };

insert-data/insert-documentAPI.js

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
const { AWS } = require('../aws-config')
2+
3+
const documentClient = new AWS.DynamoDB.DocumentClient();
4+
5+
async function insertWithDocumentClient(movie) {
6+
console.time("Document Client Insert Duration")
7+
const params = {
8+
TableName: "Movies",
9+
Item: movie
10+
};
11+
12+
try {
13+
await documentClient.put(params).promise();
14+
console.log(`New Movie with title of '${movie.title}' inserted successfully`)
15+
console.timeEnd("Document Client Insert Duration")
16+
} catch(err) {
17+
console.error("Unable to insert item", err);
18+
}
19+
};
20+
21+
const movieDetails = {
22+
"year": 2020,
23+
"title": `The Big New Movie: ${Math.random().toString(36).slice(-6)}`,
24+
"info":{
25+
"plot": "Nothing happens at all.",
26+
"rating": 0
27+
}
28+
}
29+
30+
insertWithDocumentClient(movieDetails);

insert-data/insert-partiQL.js

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
const { AWS } = require('../aws-config')
2+
3+
const dynamoDB = new AWS.DynamoDB();
4+
5+
async function insertWithPartiQL(movie) {
6+
try {
7+
console.time("PartiQL Insert Duration")
8+
const item = stringify(movie);
9+
await dynamoDB.executeStatement({Statement: `INSERT INTO Movies VALUE ${item}`}).promise();
10+
console.log(`New Movie with title of '${movie.title}' inserted successfully`)
11+
console.timeEnd("PartiQL Insert Duration")
12+
} catch(err) {
13+
console.error("Unable to write item", JSON.stringify(err, null, 2));
14+
}
15+
}
16+
17+
const movieDetails = {
18+
"year": 2020,
19+
"title": `The Big New Movie: ${Math.random().toString(36).slice(-6)}`,
20+
"info":{
21+
"plot": "Nothing happens at all.",
22+
"rating": 0
23+
}
24+
}
25+
26+
insertWithPartiQL(movieDetails);
27+
28+
29+
// Crude implementation of a custom JSON stringifier which uses single quotes instead of double quotes
30+
// Credit to the code for this from this article by Juan Dalmasso titled `Creating your own simplified implementation of JSON.stringify()`
31+
// https://levelup.gitconnected.com/creating-your-own-simplified-implementation-of-json-stringify-ed8e50b9144a
32+
function stringify(value) {
33+
const lastKey = Object.keys(value).pop();
34+
let objString = '';
35+
if (typeof value === 'object') {
36+
objString += '{';
37+
for (const key in value) {
38+
objString += `'${key}':${stringify(value[key])}`;
39+
if (key !== lastKey) {
40+
objString += ',';
41+
}
42+
}
43+
objString += '}';
44+
} else if (typeof value === 'string') {
45+
objString += `'${value}'`;
46+
} else if (typeof value === 'number') {
47+
objString += `${value}`;
48+
}
49+
return objString;
50+
}

package-lock.json

Lines changed: 10 additions & 4 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,24 @@
11
{
2-
"name": "dynnamoDb-partiQL-javascript",
2+
"name": "dynamodb-partiql-javascript",
33
"version": "1.0.0",
4-
"description": "",
4+
"description": "Code examples and a getting started part to follow along with blog article.",
55
"main": "index.js",
66
"scripts": {
7+
"get-started": "node ./getting-started/index.js",
78
"test": "echo \"Error: no test specified\" && exit 1"
89
},
9-
"keywords": [],
10-
"author": "",
10+
"keywords": [
11+
"dynamoDb",
12+
"partiQL",
13+
"aws",
14+
"javascript"
15+
],
16+
"author": "Abdullah Althawr",
1117
"license": "MIT",
1218
"dependencies": {
13-
"aws-sdk": "^2.799.0"
19+
"aws-sdk": "^2.842.0"
20+
},
21+
"devDependencies": {
22+
"dotenv": "^8.2.0"
1423
}
1524
}

0 commit comments

Comments
 (0)