Created
May 15, 2023 15:21
-
-
Save AjayPoshak/bf6aee32ef1fb155978176b02b1dfb5c to your computer and use it in GitHub Desktop.
Streaming file from S3 NestJS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Get(':hash') | |
@Header('Content-Type', 'image/png') | |
async getActiveImageByHash( | |
@Param('hash') hash: string, | |
@Res() response: Response, | |
): Promise<any> { | |
const res = await this.usersService.getActiveImageByHash(hash); | |
// Connect to s3 | |
const client = new S3Client({ | |
region: REGION, | |
credentials: { | |
accessKeyId: AWS_ACCESS_KEY, | |
secretAccessKey: AWS_SECRET_KEY, | |
}, | |
}); | |
const command = new GetObjectCommand({ | |
Bucket: BUCKET, | |
Key: res[0].active_image, | |
}); | |
// Get Object from S3 | |
const obj = await client.send(command); | |
// Read object body which is often a stream of bytes | |
const { Body } = obj; | |
// @ts-ignore | |
Body.pipe(response); // Connecting the read stream to write stream so that S3 read can be streamed to API response | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment