#node.js #amazon-dynamodb
Вопрос:
Я создаю веб-приложение с использованием Node JS и DynamoDB. Честно говоря, я новичок в DynamoDB. Я использую DynamoDB локально. Я мог бы создавать таблицы локально, запустив свой код. Но когда я подключаюсь из приложения, оно выдает ошибку.
У меня есть utils/Database.js со следующим кодом.
const AWS = require("aws-sdk");
const uuid = require('uuid');
AWS.config.update({
region: "local",
endpoint: "http://localhost:8000"
});
exports.dynamodb = new AWS.DynamoDB();
exports.documentClient = new AWS.DynamoDB.DocumentClient();
Как вы можете видеть, я использую локальную версию. Я создал файл Javascript/ NodeJS для создания таблицы под названием, db/Scripts.js со следующим кодом.
require('dotenv').config();
const database = require('../utils/Database.js');
const DynamoDB = database.dynamodb;
const appTableName = 'collect'
const createAppTable = () => {
const params = {
TableName: appTableName,
KeySchema: [
{
AttributeName: "pk",
KeyType: "HASH", // HASH - partition key and RANGE - sort key
},
{
AttributeName: "sk",
KeyType: "RANGE"
}
],
AttributeDefinitions: [{
AttributeName: "pk",
AttributeType: "S"// S = string, B = binary, N = number
},{
AttributeName: "sk",
AttributeType: "S"// S = string, B = binary, N = number
}],
ProvisionedThroughput: {
ReadCapacityUnits: 10,
WriteCapacityUnits: 10
}
};
DynamoDB.createTable(params, function(err, data) {
if (err) {
console.error("Unable to create table", err);
} else {
console.log("Created table", data);
}
});
}
module.exports = {
createAppTable,
}
Затем я выполняю следующую команду для создания таблицы.
node -e 'require("./db/scripts.js").createAppTable()'
В терминале я вижу, что таблица была создана без каких-либо проблем. Затем в моем приложении у меня есть файл под названием RegionRepository.js со следующим кодом.
let database = require('../utils/Database.js')
let dynamodb = database.dynamodb;
let documentClient = database.documentClient;
const REGION_PREFIX = "REGION";
const REGION_LIST_PK = "REGIONS";// this is not the prfix.
const REGION_LIST_SK = "REGIONS_LIST";
const appTableName ='collect';
const pkName = 'pk';
const skName = 'sk';
const all = async () => {
return new Promise(function(resolve, reject) {
documentClient.get({
TableName: appTableName,
Key: {
[pkName]: REGION_LIST_PK,
[skName]: REGION_LIST_SK
}
})
.promise()
.then(data => {
if (data.Item) {
resolve({
error: false,
items: [ ]
})
} else {
resolve({
error: false,
items: data.Item.data // format [ {id, region_name}, {id: region_name} ]
})
}
})
.catch(error => {
reject({
error: true,
message: error.message
})
})
});
}
// data = { name, latitude, longitude }
const create = async (data) => {
// create or update the array for the regions based on the existance
// also update the existing rows.
return new Promise(function(resolve, reject) {
all()
.then(result => {
data.id = database.generateHashKey();
let regions = [ ];
if (result.items amp;amp; result.items.length > 0) {
// update existing region
regions = [ ...result.items ];
regions.push(data);
} else {
//TODO: create new region
regions = [ data ];
}
const params = {
TableName: appTableName,
Item: {
[pkName]: REGION_LIST_PK,
[skName]: REGION_LIST_SK,
data: data
}
}
documentClient.put(params, (error) => {
if (error) {
reject({
error: true,
message: error.message
})
return
}
console.log("New region have been created")
})
})
.catch(error => {
//TODO: throw error
console.log(`Unable to fetch regions, ${appTableName}`, error)
})
});
}
exports.create = create;
exports.all = all;
Then when the app invokes the all() function or the create() function, it is throwing the following error in the console.
Cannot do operations on a non-existent table
But the table was created successfully running the command. What’s wrong with my code and how can I fix it?