Skip to content

Commit da8c998

Browse files
committed
feat: add DynamoDB provider sample
Resolves #54
1 parent 7301439 commit da8c998

3 files changed

Lines changed: 656 additions & 111 deletions

File tree

apps/backend/package.json

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@
1717
"deploy": "dotenvx run -f .env.prod.local -f .env.prod -f .env -- sh scripts/deploy.sh"
1818
},
1919
"dependencies": {
20+
"@aws-sdk/client-dynamodb": "^3.927.0",
21+
"@aws-sdk/lib-dynamodb": "^3.927.0",
2022
"srvx": "^0.9.4"
2123
},
2224
"devDependencies": {
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
import { cacheProvider, getCachedProvider, isNonSharingPlatforms } from '#src/providers/index.js'
2+
import { DynamoDBClient } from '@aws-sdk/client-dynamodb'
3+
import { DynamoDBDocumentClient } from '@aws-sdk/lib-dynamodb'
4+
import { env } from 'std-env'
5+
6+
export const PROVIDER_NAME = 'dynamo-main'
7+
8+
export function getCachedDynamo(): Awaited<ReturnType<typeof initDynamo>> | undefined {
9+
return getCachedProvider(`${PROVIDER_NAME}--dynamo`)
10+
}
11+
12+
export async function getDynamo() {
13+
const cached = getCachedDynamo()
14+
15+
if (!cached && !isNonSharingPlatforms)
16+
throw new Error('Not initialized')
17+
18+
return cached ?? await initDynamo()
19+
}
20+
21+
export async function initDynamo() {
22+
const cached = getCachedDynamo()
23+
24+
if (!isNonSharingPlatforms && cached)
25+
console.warn('Already initialized')
26+
27+
const requiredEnvs = {
28+
region: env.DYNAMO_MAIN_REGION!,
29+
accessKeyId: env.DYNAMO_MAIN_ACCESS_KEY_ID!,
30+
secretAccessKey: env.DYNAMO_MAIN_SECRET_ACCESS_KEY!,
31+
}
32+
33+
const missingEnvs = Object.entries(requiredEnvs).flatMap(([key, value]) => value ? [] : key)
34+
if (missingEnvs.length)
35+
throw new Error(`Missing required env: ${missingEnvs.join(', ')}`)
36+
37+
const dynamo = await setupDynamo({
38+
...requiredEnvs,
39+
})
40+
41+
cacheProvider(`${PROVIDER_NAME}--dynamo`, dynamo)
42+
43+
return dynamo
44+
}
45+
46+
export type SetupDynamoConfig = {
47+
region: string
48+
accessKeyId: string
49+
secretAccessKey: string
50+
sessionToken?: string
51+
}
52+
export async function setupDynamo(config: SetupDynamoConfig) {
53+
const { region, accessKeyId, secretAccessKey, sessionToken } = config
54+
55+
const dbClient = new DynamoDBClient({
56+
region,
57+
credentials: {
58+
accessKeyId,
59+
secretAccessKey,
60+
sessionToken,
61+
},
62+
})
63+
const dbDocumentClient = DynamoDBDocumentClient.from(dbClient, {
64+
marshallOptions: {
65+
removeUndefinedValues: true,
66+
},
67+
})
68+
69+
return {
70+
dbClient,
71+
dbDocumentClient,
72+
}
73+
}

0 commit comments

Comments
 (0)