-
Notifications
You must be signed in to change notification settings - Fork 154
/
Copy pathunmarshallDynamoDB.ts
83 lines (74 loc) · 2.55 KB
/
unmarshallDynamoDB.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
import type { AttributeValue } from '@aws-sdk/client-dynamodb';
class UnmarshallDynamoDBAttributeError extends Error {
constructor(message: string) {
super(message);
this.name = 'UnmarshallDynamoDBAttributeError';
}
}
// biome-ignore lint/suspicious/noExplicitAny: we need to use any here to support the different types of DynamoDB attributes
const typeHandlers: Record<string, (value: any) => unknown> = {
NULL: () => null,
S: (value) => value,
B: (value) => value,
BS: (value) => new Set(value),
SS: (value) => new Set(value),
BOOL: (value) => Boolean(value),
N: (value) => convertNumber(value),
NS: (value) => new Set((value as Array<string>).map(convertNumber)),
L: (value) => (value as Array<AttributeValue>).map(convertAttributeValue),
M: (value) =>
Object.entries(value).reduce(
(acc, [key, value]) => {
acc[key] = convertAttributeValue(value as AttributeValue);
return acc;
},
{} as Record<string, unknown>
),
};
const convertAttributeValue = (
data: AttributeValue | Record<string, AttributeValue>
): unknown => {
const [type, value] = Object.entries(data)[0];
if (value !== undefined) {
const handler = typeHandlers[type];
if (!handler) {
throw new UnmarshallDynamoDBAttributeError(
`Unsupported type passed: ${type}`
);
}
return handler(value);
}
throw new UnmarshallDynamoDBAttributeError(
`Value is undefined for type: ${type}`
);
};
const convertNumber = (numString: string) => {
const num = Number(numString);
const infinityValues = [Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY];
const isLargeFiniteNumber =
(num > Number.MAX_SAFE_INTEGER || num < Number.MIN_SAFE_INTEGER) &&
!infinityValues.includes(num);
if (isLargeFiniteNumber) {
try {
return BigInt(numString);
} catch (error) {
throw new UnmarshallDynamoDBAttributeError(
`${numString} can't be converted to BigInt`
);
}
}
return num;
};
/**
* Unmarshalls a DynamoDB AttributeValue to a JavaScript object.
*
* The implementation is loosely based on the official AWS SDK v3 unmarshall function but
* without support the customization options and with assumed support for BigInt.
*
* @param data - The DynamoDB AttributeValue to unmarshall
*/
const unmarshallDynamoDB = (
data: AttributeValue | Record<string, AttributeValue>
// @ts-expect-error - We intentionally wrap the data into a Map to allow for nested structures
) => convertAttributeValue({ M: data });
export { unmarshallDynamoDB, UnmarshallDynamoDBAttributeError };