Skip to content

Commit

Permalink
Merge pull request #39 from lpsinger/get-and-list
Browse files Browse the repository at this point in the history
Add methods to list versions and get by version
  • Loading branch information
dakota002 authored Nov 16, 2023
2 parents d9725bc + 87cbfe3 commit 2a9bf78
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 0 deletions.
50 changes: 50 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
type PutCommandInput,
PutCommand,
GetCommand,
QueryCommand,
} from '@aws-sdk/lib-dynamodb'
import type { NativeAttributeValue } from '@aws-sdk/util-dynamodb'

Expand Down Expand Up @@ -177,6 +178,55 @@ export class DynamoDBAutoIncrement extends BaseDynamoDBAutoIncrement {
* ```
*/
export class DynamoDBHistoryAutoIncrement extends BaseDynamoDBAutoIncrement {
async list(): Promise<number[]> {
const { Items } = await this.props.doc.send(
new QueryCommand({
TableName: this.props.tableName,
ExpressionAttributeNames: {
...Object.fromEntries(
Object.keys(this.props.counterTableKey).map((key, i) => [
`#${i}`,
key,
])
),
'#counter': this.props.attributeName,
},
ExpressionAttributeValues: Object.fromEntries(
Object.values(this.props.counterTableKey).map((value, i) => [
`:${i}`,
value,
])
),
KeyConditionExpression: Object.keys(this.props.counterTableKey)
.map((_, i) => `#${i} = :${i}`)
.join(' AND '),
ProjectionExpression: '#counter',
})
)

return Items?.map((item) => item[this.props.attributeName]).sort() ?? []
}

async get(version?: number) {
const { Item } = await this.props.doc.send(
new GetCommand(
version === undefined
? {
TableName: this.props.counterTableName,
Key: this.props.counterTableKey,
}
: {
TableName: this.props.tableName,
Key: {
...this.props.counterTableKey,
[this.props.attributeName]: version,
},
}
)
)
return Item
}

protected async next(item: Record<string, NativeAttributeValue>) {
let nextCounter

Expand Down
8 changes: 8 additions & 0 deletions src/test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,10 @@ describe('autoincrementVersion', () => {
'tracked attribute set to %s',
(trackedAttributeValue) => {
test('increments version on put', async () => {
expect(await autoincrement.list()).toEqual([])
expect(await autoincrement.get()).toEqual(initialItem)
expect(await autoincrement.get(1)).toEqual(undefined)

// Create new version
const newVersion = await autoincrement.put({
name: 'Handy Widget',
Expand All @@ -228,6 +232,10 @@ describe('autoincrementVersion', () => {
).Items

expect(historyItems?.length).toBe(Number(hasInitialItem))

expect(await autoincrement.list()).toEqual(
historyItems?.map((_, i) => i + 1) ?? []
)
})

test('correctly handles a large number of parallel puts', async () => {
Expand Down

0 comments on commit 2a9bf78

Please sign in to comment.