Comments (4)
Hi @Ra100NZ ,
Can you share your entire code snippet?
It works fine for me:
import { DynamoDBClient, CreateTableCommand, waitUntilTableExists } from '@aws-sdk/client-dynamodb';
const client = new DynamoDBClient({ region: "us-east-1" });
try {
await client.send(new CreateTableCommand({
TableName: "6105",
AttributeDefinitions: [
{ AttributeName: "id", AttributeType: "S" }
],
KeySchema: [
{ AttributeName: "id", KeyType: "HASH" }
],
ProvisionedThroughput: {
ReadCapacityUnits: 5,
WriteCapacityUnits: 5
}
}));
const results = await waitUntilTableExists({
client: client,
maxWaitTime: 30,
minDelay: 1,
maxDelay: 3
}, {
TableName: "6105"
});
console.log(results);
} catch (error) {
console.log(error);
}
/*
{
state: 'SUCCESS',
reason: {
'$metadata': {
httpStatusCode: 200,
requestId: 'REDACTED',
extendedRequestId: undefined,
cfId: undefined,
attempts: 1,
totalRetryDelay: 0
},
Table: {
AttributeDefinitions: [Array],
CreationDateTime: 2024-05-16T18:58:36.265Z,
DeletionProtectionEnabled: false,
ItemCount: 0,
KeySchema: [Array],
ProvisionedThroughput: [Object],
TableArn: 'REDACTED/6105',
TableId: 'REDACTED',
TableName: '6105',
TableSizeBytes: 0,
TableStatus: 'ACTIVE'
}
}
}
*/
Thanks,
Ran~
from aws-sdk-js-v3.
client is set within the constructor -> this.client = new DynamoDBClient();
public async TableCreate(TableName: string, HashKeyField: string, Fields: string[]): Promise<void> {
Logger.info(`CustomTablesRepository.TableCreate("${TableName}", "${HashKeyField}", [${Fields}])`);
// Create table
const command = new CreateTableCommand({
TableName: TableName,
AttributeDefinitions: [ { AttributeName: HashKeyField, AttributeType: 'S' } ],
KeySchema: [ { AttributeName: HashKeyField, KeyType: 'HASH' } ],
BillingMode: 'PROVISIONED',
ProvisionedThroughput: {
ReadCapacityUnits: (process.env.aws_db_read_capacity) ? Number(process.env.aws_db_read_capacity) : 5,
WriteCapacityUnits: (process.env.aws_db_write_capacity) ? Number(process.env.aws_db_write_capacity) : 5
}
});
try {
const res = await this.client.send(command);
Logger.info(JSON.stringify(res));
// Wait for table being created
const results = await waitUntilTableExists({client: this.client, maxWaitTime: 30, minDelay: 1, maxDelay: 3 }, {
TableName: TableName
});
if (results.state === 'SUCCESS') {
// Put Dummy record
let dymmyRecord = {} as Record<string, string>;
dymmyRecord[HashKeyField] = this.dummyRecordKey;
Fields.forEach((field) => {
dymmyRecord[field] = field;
});
const input = {
TableName: TableName,
Item: dymmyRecord
};
const docClient = DynamoDBDocumentClient.from(this.client);
const command = new PutCommand(input);
await docClient.send(command);
} else {
Logger.error(`${results.state} ${results.reason}`);
}
} catch (e) {
Logger.error(JSON.stringify(e));
}
}
from aws-sdk-js-v3.
Hi @Ra100NZ ,
Your code looks fine, I'm not sure why you are seeing it. I even expanded my example to mimic your code:
import { DynamoDBClient, CreateTableCommand, waitUntilTableExists } from "@aws-sdk/client-dynamodb";
import { DynamoDBDocumentClient, PutCommand } from "@aws-sdk/lib-dynamodb";
const client = new DynamoDBClient({ region: "us-east-1" });
const TableName = "6105-b";
const HashKeyField = "id";
const dummyRecordKey = "exampleKey";
const Fields = ["additionalField1", "additionalField2"];
async function main() {
try {
await client.send(new CreateTableCommand({
TableName,
AttributeDefinitions: [
{ AttributeName: HashKeyField, AttributeType: "S" }
],
KeySchema: [
{ AttributeName: HashKeyField, KeyType: "HASH" }
],
ProvisionedThroughput: {
ReadCapacityUnits: 5,
WriteCapacityUnits: 5
}
}));
const results = await waitUntilTableExists({
client,
maxWaitTime: 30,
minDelay: 1,
maxDelay: 3
}, {
TableName
});
if (results.state === 'SUCCESS') {
let dummyRecord = {};
dummyRecord[HashKeyField] = dummyRecordKey;
Fields.forEach(field => {
dummyRecord[field] = field;
});
const docClient = DynamoDBDocumentClient.from(client);
const putCommand = new PutCommand({
TableName,
Item: dummyRecord
});
await docClient.send(putCommand);
console.log("Record inserted successfully.");
}
} catch (error) {
console.error("An error occurred:", error);
}
}
main();
// Record inserted successfully.
The waiter code should be synchronous and blocking. It seems like your doc client API call is being fired before the waiter is finished.
Since you have logging in different parts of your code, can you tell me what is the order of logs that you are seeing?
- Is the table creation fired successfully? ie this line fires
Logger.info(JSON.stringify(res));
- is the
ResourceNotFoundException
thrown from you the putItem() call?
My other guess is that because you have logging enabled (perhaps on your client code) you are seeing the underlying error thrown from the polling of the waiter. The CreateTable call might be firing, and the waiter polls right away and leads to an underlying ResourceNotFoundException
, which is expected. The idea behind the waiter is that it polls over and over until the resource is not only created, but ready. You might be able to circumvent this by setting a longer initial delay like minDelay: 5
Thanks,
Ran~
from aws-sdk-js-v3.
Hi @RanVaknin,
Yes, the table creation fired successfully.
No, the ResourceNotFoundException
is not coming from putItem(). It is coming from waitUntilTableExists
.
I changed the minDelay and maxDelay based on your suggestion:
const results = await waitUntilTableExists({client: this.client, maxWaitTime: 30, minDelay: 5, maxDelay: 8 }, {
TableName: TableName
});
and it works now. But I am not sure why :)
Btw, we have as well the delete table action, and waitUntilTableNotExists
works minDelay:1
Anyway, thanks for your suggestion and help.
from aws-sdk-js-v3.
Related Issues (20)
- What are the counterparts for types such as APIGatewayProxyEvent, DynamoDBStreamEvent etc. in v3? HOT 4
- Add possibility to retrieve savings plans inventory for the whole organization HOT 3
- what to put as a config? HOT 1
- Conflict in Peer Dependencies for @aws-sdk/client-sts @aws-sdk/client-secrets-manager HOT 4
- input/outputFilterSensitiveLog logs entire inputs and outputs of S3 object commands HOT 4
- SES Interface change is not compatible HOT 4
- [S3][Upload] : Wrong Location in response for file size greater than 5MB HOT 1
- client use http protocol failed
- Example code for lib-storage doesn't work HOT 1
- SNS Verify HTTPS endpoint signature HOT 1
- `ValidationError` should report the error fields starting from upper case that matches the command's input type HOT 1
- Add Policy Action Name used by a command HOT 1
- CloudwatchLogs `retention` field in `CreateLogGroupCommand`
- Error when importing @aws-sdk/client-s3 HOT 3
- Race conditions in S3 upload HOT 6
- (0 , import_core.parseJsonBody) is not a function HOT 3
- await Upload.done() never returns if stream is (still) empty HOT 1
- Provide SendCommandCommand Status Update Guide HOT 1
- Pass client logger to request handlers
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from aws-sdk-js-v3.