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;
}
const storage = buildS3Storage(
config.endpoint,
config.bucket,
config.accessKeyId,
config.accessSecretKey
);
const { endpoint, bucket, accessKeyId, accessSecretKey, region } = config;
const storage = buildS3Storage({
endpoint,
bucket,
accessKeyId,
secretAccessKey: accessSecretKey,
region,
});
return storage.uploadFile;
};

View file

@ -2,17 +2,38 @@ import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3';
import type { UploadFile } from './types.js';
export const buildS3Storage = (
endpoint: string,
bucket: string,
accessKeyId: string,
secretAccessKey: string
) => {
const getRegionFromEndpoint = (endpoint?: string) => {
if (!endpoint) {
return;
}
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
const region = /s3\.([^.]*)\.amazonaws/.exec(endpoint)?.[1] ?? 'us-east-1';
const finalRegion = region ?? getRegionFromEndpoint(endpoint) ?? 'us-east-1';
const client = new S3Client({
region,
region: finalRegion,
endpoint,
credentials: {
accessKeyId,
@ -40,7 +61,7 @@ export const buildS3Storage = (
}
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({
provider: z.literal(StorageProvider.S3Storage),
endpoint: z.string(),
endpoint: z.string().optional(),
region: z.string().optional(),
bucket: z.string(),
accessKeyId: z.string(),
accessSecretKey: z.string(),