-
Notifications
You must be signed in to change notification settings - Fork 0
/
README.test.ts
97 lines (88 loc) · 2.49 KB
/
README.test.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import { s } from "shape-tape"
import { Table } from "../src"
import crypto from "crypto"
import { prepDdbTest } from "./test-utilities/DynamoDb"
import { GetCommand, PutCommand } from "@aws-sdk/lib-dynamodb"
test("Example from README", async () => {
// Create Table class instances based on your DynamoDB tables.
const blogPostsTable = new Table({
tableName: "BlogPosts",
itemShape: s.object({
id: s.string(),
name: s.string(),
content: s.string(),
numComments: s.integer()
}),
partitionKey: "id"
})
const commentsTable = new Table({
tableName: "Comments",
itemShape: s.object({
blogPostId: s.string(),
id: s.string(),
content: s.string()
}),
partitionKey: "blogPostId",
sortKey: "id"
})
// Perform operations on items in those tables.
// Example scenario - Handling an API request for adding a comment to a blog post:
async function handleCreateBlogPostComment(blogPostId: string, commentContent: string) {
// Get the blog post
const blogPost = await optimus.getItem({
table: blogPostsTable,
key: { id: blogPostId }
})
// Prepare a change to increase the blog post's numComments.
blogPost.numComments = blogPost.numComments + 1
// Prepare a new comment.
const comment = optimus.draftItem({
table: commentsTable,
item: {
blogPostId: blogPostId,
id: crypto.randomUUID(),
content: commentContent
}
})
// Commit those changes in a transaction.
await optimus.commitItems({ items: [blogPost, comment] })
return { id: comment.id }
}
const [optimus, ddbDocumentClient] = await prepDdbTest([blogPostsTable, commentsTable], [])
const blogPostId = crypto.randomUUID()
await ddbDocumentClient.send(new PutCommand({
TableName: "BlogPosts",
Item: {
id: blogPostId,
name: "My blog post",
content: "This is my blog post",
numComments: 0,
version: 0
}
}))
const createCommentRes = await handleCreateBlogPostComment(blogPostId, "Nice blog post")
const blogPostItem = (await ddbDocumentClient.send(new GetCommand({
TableName: "BlogPosts",
Key: { id: blogPostId }
}))).Item
const commentItem = (await ddbDocumentClient.send(new GetCommand({
TableName: "Comments",
Key: {
blogPostId: blogPostId,
id: createCommentRes.id
}
}))).Item
expect(blogPostItem).toStrictEqual({
id: blogPostId,
name: "My blog post",
content: "This is my blog post",
numComments: 1,
version: 1
})
expect(commentItem).toStrictEqual({
blogPostId: blogPostId,
id: createCommentRes.id,
content: "Nice blog post",
version: 0
})
})