UNPKG

@hyperlane-xyz/sdk

Version:

The official SDK for the Hyperlane Network

69 lines 2.13 kB
import { GetObjectCommand, S3Client } from '@aws-sdk/client-s3'; import { streamToString } from '@hyperlane-xyz/utils'; export const S3_BUCKET_REGEX = /^(?:https?:\/\/)?(.*)\.s3\.(.*)\.amazonaws.com\/?$/; export class S3Wrapper { config; client; cache; static fromBucketUrl(bucketUrl) { const match = bucketUrl.match(S3_BUCKET_REGEX); if (!match) throw new Error('Could not parse bucket url'); return new S3Wrapper({ bucket: match[1], region: match[2], caching: true, }); } constructor(config) { this.config = config; this.client = new S3Client({ ...config, // explicitly set empty credentials to allow usage without env vars credentials: { accessKeyId: '', secretAccessKey: '', }, signer: { sign: async (req) => req }, }); if (config.caching) { this.cache = {}; } } formatKey(key) { return this.config.folder ? `${this.config.folder}/${key}` : key; } async getS3Obj(key) { const Key = this.formatKey(key); if (this.cache?.[Key]) { return this.cache[Key]; } const command = new GetObjectCommand({ Bucket: this.config.bucket, Key, }); try { const response = await this.client.send(command); const body = await streamToString(response.Body); const result = { data: JSON.parse(body), modified: response.LastModified, }; if (this.cache) { this.cache[Key] = result; } return result; } catch (e) { if (e.message.includes('The specified key does not exist.')) { return; } throw e; } } url(key) { const Key = this.formatKey(key); return `https://${this.config.bucket}.s3.${this.config.region}.amazonaws.com/${Key}`; } } //# sourceMappingURL=s3.js.map