|
| 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