@@ -3,34 +3,39 @@ import {
33 DeleteCommand ,
44 DynamoDBDocumentClient ,
55 GetCommand ,
6+ NumberValue ,
67 PutCommand ,
78 QueryCommand ,
89 ScanCommand ,
910 UpdateCommand ,
1011} from '@aws-sdk/lib-dynamodb'
12+ import { isRecordLike } from '@sim/utils/object'
1113import { awsClientConfig } from '@/lib/internal/aws/credentials'
1214import type { DynamoDBConnectionConfig , DynamoDBTableSchema } from '@/tools/dynamodb/types'
1315
1416type DynamoDBReturnValues = 'NONE' | 'ALL_OLD' | 'UPDATED_OLD' | 'ALL_NEW' | 'UPDATED_NEW'
1517
1618/**
1719 * Keeps integers beyond `Number.MAX_SAFE_INTEGER` (and other values a JS number cannot hold)
18- * as their exact DynamoDB string, since the SDK default turns them into a `BigInt` that the
19- * JSON response cannot serialize.
20+ * as a `NumberValue` holding the exact DynamoDB string, since the SDK default turns them into a
21+ * `BigInt` that the JSON response cannot serialize.
2022 */
21- function unwrapNumber ( value : string ) : number | string {
23+ function unwrapNumber ( value : string ) : number | NumberValue {
2224 const parsed = Number ( value )
23- if ( ! Number . isFinite ( parsed ) ) return value
24- if ( Number . isInteger ( parsed ) && ! Number . isSafeInteger ( parsed ) ) return value
25+ if ( ! Number . isFinite ( parsed ) || ( Number . isInteger ( parsed ) && ! Number . isSafeInteger ( parsed ) ) ) {
26+ return NumberValue . from ( value )
27+ }
2528 return parsed
2629}
2730
2831/**
2932 * Converts unmarshalled DynamoDB values into JSON-serializable shapes: string, number and
30- * binary sets become arrays, and binary values become base64 strings. Without this a set
31- * serializes as `{}` and a binary value as an object of byte indexes.
33+ * binary sets become arrays, binary values become base64 strings, and numbers a JS number
34+ * cannot hold become their exact string. Without this a set serializes as `{}` and a binary
35+ * value as an object of byte indexes.
3236 */
3337function toJsonSafe ( value : unknown ) : unknown {
38+ if ( value instanceof NumberValue ) return value . toString ( )
3439 if ( value instanceof Set ) return Array . from ( value , toJsonSafe )
3540 if ( value instanceof Uint8Array ) return Buffer . from ( value ) . toString ( 'base64' )
3641 if ( Array . isArray ( value ) ) return value . map ( toJsonSafe )
@@ -46,6 +51,42 @@ function toJsonSafeRecord(
4651 return value ? ( toJsonSafe ( value ) as Record < string , unknown > ) : undefined
4752}
4853
54+ /**
55+ * Encodes a `LastEvaluatedKey` so it can be passed back as `exclusiveStartKey`. Key
56+ * attributes are always scalar (S, N or B), so strings and safe numbers stay as-is while a
57+ * number a JS number cannot hold becomes `{ N }` and a binary key becomes `{ B }` (base64):
58+ * plain strings would otherwise be sent back as S and fail the key type check.
59+ */
60+ function toCursor ( key : Record < string , unknown > | undefined ) : Record < string , unknown > | undefined {
61+ if ( ! key ) return undefined
62+ return Object . fromEntries (
63+ Object . entries ( key ) . map ( ( [ name , value ] ) => {
64+ if ( value instanceof NumberValue ) return [ name , { N : toJsonSafe ( value ) } ]
65+ if ( value instanceof Uint8Array ) return [ name , { B : toJsonSafe ( value ) } ]
66+ return [ name , value ]
67+ } )
68+ )
69+ }
70+
71+ const DYNAMODB_NUMBER = / ^ - ? \d + ( \. \d + ) ? ( [ e E ] [ + - ] ? \d + ) ? $ /
72+
73+ /** Restores the `{ N }` and `{ B }` cursor values written by {@link toCursor}. */
74+ function fromCursor ( key : Record < string , unknown > ) : Record < string , unknown > {
75+ return Object . fromEntries (
76+ Object . entries ( key ) . map ( ( [ name , value ] ) => {
77+ if ( isRecordLike ( value ) && Object . keys ( value ) . length === 1 ) {
78+ if ( typeof value . N === 'string' && DYNAMODB_NUMBER . test ( value . N ) ) {
79+ return [ name , NumberValue . from ( value . N ) ]
80+ }
81+ if ( typeof value . B === 'string' ) {
82+ return [ name , new Uint8Array ( Buffer . from ( value . B , 'base64' ) ) ]
83+ }
84+ }
85+ return [ name , value ]
86+ } )
87+ )
88+ }
89+
4990export function createDynamoDBClient ( config : DynamoDBConnectionConfig ) : DynamoDBDocumentClient {
5091 const client = new DynamoDBClient ( {
5192 ...awsClientConfig ( config . region , config . accessKeyId , config . secretAccessKey ) ,
@@ -152,7 +193,7 @@ export async function queryItems(
152193 } ) ,
153194 ...( options ?. indexName && { IndexName : options . indexName } ) ,
154195 ...( options ?. limit && { Limit : options . limit } ) ,
155- ...( options ?. exclusiveStartKey && { ExclusiveStartKey : options . exclusiveStartKey } ) ,
196+ ...( options ?. exclusiveStartKey && { ExclusiveStartKey : fromCursor ( options . exclusiveStartKey ) } ) ,
156197 ...( options ?. scanIndexForward !== undefined && { ScanIndexForward : options . scanIndexForward } ) ,
157198 ...( options ?. projectionExpression && { ProjectionExpression : options . projectionExpression } ) ,
158199 ...( options ?. consistentRead !== undefined && { ConsistentRead : options . consistentRead } ) ,
@@ -163,7 +204,7 @@ export async function queryItems(
163204 items : ( response . Items ?? [ ] ) . map ( ( item ) => toJsonSafeRecord ( item ) ?? { } ) ,
164205 count : response . Count || 0 ,
165206 scannedCount : response . ScannedCount ?? null ,
166- lastEvaluatedKey : toJsonSafeRecord ( response . LastEvaluatedKey ) ,
207+ lastEvaluatedKey : toCursor ( response . LastEvaluatedKey ) ,
167208 }
168209}
169210
@@ -200,7 +241,7 @@ export async function scanItems(
200241 ExpressionAttributeValues : options . expressionAttributeValues ,
201242 } ) ,
202243 ...( options ?. limit && { Limit : options . limit } ) ,
203- ...( options ?. exclusiveStartKey && { ExclusiveStartKey : options . exclusiveStartKey } ) ,
244+ ...( options ?. exclusiveStartKey && { ExclusiveStartKey : fromCursor ( options . exclusiveStartKey ) } ) ,
204245 ...( options ?. indexName && { IndexName : options . indexName } ) ,
205246 ...( options ?. consistentRead !== undefined && { ConsistentRead : options . consistentRead } ) ,
206247 ...( options ?. segment !== undefined && { Segment : options . segment } ) ,
@@ -212,7 +253,7 @@ export async function scanItems(
212253 items : ( response . Items ?? [ ] ) . map ( ( item ) => toJsonSafeRecord ( item ) ?? { } ) ,
213254 count : response . Count || 0 ,
214255 scannedCount : response . ScannedCount ?? null ,
215- lastEvaluatedKey : toJsonSafeRecord ( response . LastEvaluatedKey ) ,
256+ lastEvaluatedKey : toCursor ( response . LastEvaluatedKey ) ,
216257 }
217258}
218259
0 commit comments