0
Fork 0
mirror of https://github.com/logto-io/logto.git synced 2024-12-16 20:26:19 -05:00

feat(core,schemas): support region option for s3 storage (#4439)

This commit is contained in:
wangsijie 2023-09-14 14:46:27 +08:00 committed by GitHub
parent 06df010202
commit 17fd64e643
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 47 additions and 16 deletions

View file

@ -0,0 +1,6 @@
---
"@logto/schemas": minor
"@logto/core": minor
---
Support region option for s3 storage

View file

@ -11,12 +11,15 @@ export const buildUploadFile = (config: StorageProviderData): UploadFile => {
return storage.uploadFile; return storage.uploadFile;
} }
const storage = buildS3Storage( const { endpoint, bucket, accessKeyId, accessSecretKey, region } = config;
config.endpoint,
config.bucket, const storage = buildS3Storage({
config.accessKeyId, endpoint,
config.accessSecretKey bucket,
); accessKeyId,
secretAccessKey: accessSecretKey,
region,
});
return storage.uploadFile; return storage.uploadFile;
}; };

View file

@ -2,17 +2,38 @@ import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3';
import type { UploadFile } from './types.js'; import type { UploadFile } from './types.js';
export const buildS3Storage = ( const getRegionFromEndpoint = (endpoint?: string) => {
endpoint: string, if (!endpoint) {
bucket: string, return;
accessKeyId: string, }
secretAccessKey: string
) => { return /s3\.([^.]*)\.amazonaws/.exec(endpoint)?.[1];
};
type BuildS3StorageParameters = {
bucket: string;
accessKeyId: string;
secretAccessKey: string;
region?: string;
endpoint?: string;
};
export const buildS3Storage = ({
bucket,
accessKeyId,
secretAccessKey,
region,
endpoint,
}: BuildS3StorageParameters) => {
if (!region && !endpoint) {
throw new Error('Either region or endpoint must be provided');
}
// Endpoint example: s3.us-west-2.amazonaws.com // Endpoint example: s3.us-west-2.amazonaws.com
const region = /s3\.([^.]*)\.amazonaws/.exec(endpoint)?.[1] ?? 'us-east-1'; const finalRegion = region ?? getRegionFromEndpoint(endpoint) ?? 'us-east-1';
const client = new S3Client({ const client = new S3Client({
region, region: finalRegion,
endpoint, endpoint,
credentials: { credentials: {
accessKeyId, accessKeyId,
@ -40,7 +61,7 @@ export const buildS3Storage = (
} }
return { return {
url: `https://${bucket}.s3.${region}.amazonaws.com/${objectKey}`, url: `https://${bucket}.s3.${finalRegion}.amazonaws.com/${objectKey}`,
}; };
}; };

View file

@ -40,7 +40,8 @@ export const storageProviderDataGuard = z.discriminatedUnion('provider', [
}), }),
z.object({ z.object({
provider: z.literal(StorageProvider.S3Storage), provider: z.literal(StorageProvider.S3Storage),
endpoint: z.string(), endpoint: z.string().optional(),
region: z.string().optional(),
bucket: z.string(), bucket: z.string(),
accessKeyId: z.string(), accessKeyId: z.string(),
accessSecretKey: z.string(), accessSecretKey: z.string(),