Skip to content

Instantly share code, notes, and snippets.

@lejonmanen
Created September 14, 2025 15:22
Show Gist options
  • Select an option

  • Save lejonmanen/ace4c0cf532ab646089570ffd103f6c1 to your computer and use it in GitHub Desktop.

Select an option

Save lejonmanen/ace4c0cf532ab646089570ffd103f6c1 to your computer and use it in GitHub Desktop.
Använda DynamoDB från Node
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import { DynamoDBDocumentClient, GetCommand, PutCommand, ScanCommand } from "@aws-sdk/lib-dynamodb";
/*
GetCommand används för att hämta en specifik Item i en Table. (AWS rekommenderar att man har allt i samma tabell.)
ScanCommand kan hämta hela innehållet i en tabell. Opraktiskt om man har mycket data.
PutCommand lägger till en ny Item.
UpdateItemCommand ändrar en Item.
DeleteCommand
*/
const client: DynamoDBClient = new DynamoDBClient({
region: "eu-north-1", // se till att använda den region som du använder för DynamoDB
credentials: {
accessKeyId: 'din access key som du skapar i IAM',
secretAccessKey: 'din secret access key som du skapar i IAM',
},
});
const db: DynamoDBDocumentClient = DynamoDBDocumentClient.from(client);
const myTable: string = 'namnet på din tabell'
// hämta en specifik item
type GetResult = Record<string, any> | undefined
let getCommand = new GetCommand({
TableName: myTable,
Key: { yourPartitionKeyName: "the item's partition key value" }
})
const result: GetResult = await db.send(getCommand)
// hämta alla items i en tabell - VARNING! Använd bara för små tabeller
type ScanResult = Record<string, any>[] | undefined
let scanCommand = new ScanCommand({
TableName: myTable
})
// lägg till en ny item
let newItem: YourInterface = { pkey: 'exempel', score: 500, createdAt: Date.now() }
let result: PutCommandOutput = await db.send(new PutCommand({
TableName: myTable,
Item: newItem
}));
// ta bort en item
let result: db.send(new DeleteCommand({
TableName: myTable,
Key: { yourPartitionKeyName: 'värdet på PK för den item som ska tas bort' },
ReturnValues: 'ALL_OLD' // för att DynamoDB ska returnera hela objektet innan det tas bort
})
// ändra en item
let result = db.send(new UpdateCommand({
TableName: myTable,
Key: { yourPartitionKeyName: 'värdet på PK för den item som ska ändras' },
UpdateExpression: 'SET #dt = :d, score = :s',
ExpressionAttributeNames: {
'#dt': 'date' // använd om man inte kan skriva t.ex. "date" direkt eftersom det är ett reserverat ord
},
ExpressionAttributeValues: {
// Detta är alla fält som ska ändras
':d': Date.now(),
':s': 500
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment