-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdynamoObject.ts
More file actions
82 lines (72 loc) · 2.1 KB
/
dynamoObject.ts
File metadata and controls
82 lines (72 loc) · 2.1 KB
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
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import { DynamoDBDocumentClient } from "@aws-sdk/lib-dynamodb";
export type Index<T> = {
partitionKey: Exclude<keyof T, "_meta">;
sortKey?: Exclude<keyof T, "_meta">;
};
export interface DynamoMeta<T> {
tableName: string;
partitionKey: Exclude<keyof T, "_meta">;
sortKey?: Exclude<keyof T, "_meta">;
indexes?: { [name: string]: Index<T> };
}
export abstract class DynamoObject<T> {
abstract readonly _meta: DynamoMeta<T>;
/**
* @deprecated Please use the `.create` method instead to fill all required fields.
*/
constructor() {}
}
class SharedDynamoClient {
private client: DynamoDBDocumentClient = {} as DynamoDBDocumentClient;
public set(client: DynamoDBDocumentClient) {
this.client = client;
}
public initialize(marshallEmptyValues = true) {
const dynamoDBClient = new DynamoDBClient();
const docClient = DynamoDBDocumentClient.from(dynamoDBClient, {
marshallOptions: { convertEmptyValues: marshallEmptyValues },
});
this.set(docClient);
}
public get(): DynamoDBDocumentClient {
if (!("send" in this.client)) {
console.error("SharedDynamoClient missing. Use sharedDynamoClient.set()");
throw new Error(
"SharedDynamoClient missing. Use sharedDynamoClient.set()",
);
}
return this.client;
}
}
export const sharedDynamoClient = new SharedDynamoClient();
export function getMeta<T extends DynamoObject<T>>(
cls:
| {
new (): T;
}
| T,
): T["_meta"] {
if ("_meta" in cls) return cls._meta;
return new cls()._meta;
}
export function removeMeta<
T extends
| { [key: string]: any }
| Array<any>
| Set<any>
| string
| number
| null
| undefined,
>(input: T): T {
if (Array.isArray(input)) return input.map((item) => removeMeta(item)) as T;
if (input === null || typeof input !== "object" || input instanceof Set)
return input;
const result: { [key: string]: any } = {};
Object.keys(input).forEach((key) => {
if (key === "_meta") return;
result[key] = removeMeta(input[key]);
});
return result as T;
}