Last active
September 25, 2021 08:20
-
-
Save Romakita/814750c35b77be5c5050d25e13566548 to your computer and use it in GitHub Desktop.
Stream S3 File object with Ts.ED
This file contains 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
import { Controller } from "@tsed/common"; | |
import { Inject, Injectable } from "@tsed/di"; | |
import AWS from "aws-sdk"; | |
@Controller("/medias") | |
export class MediasController { | |
@Inject() | |
protected s3: S3Client; | |
@Get() | |
async getImage(@QueryParams("id") imageKey: number, @Context() ctx: Context): Promise<Buffer> { | |
try { | |
const { object, metadata } = await this.s3.getObject(IMAGE_BUCKET, imageKey); | |
const buffer = object.createReadStream(); | |
// buffer.res.set("Content-Type", mime.lookup(key)); | |
ctx.response.set("Content-Length", metadata.ContentLength); // maybe not necessary | |
// use the last-modified header to use browser cache | |
ctx.response.set("Last-Modified", metadata.LastModified); | |
ctx.response.set("ETag", metadata.ETag); | |
// Ts.ED will handle the buffer | |
return buffer; | |
} catch (err) { | |
throw new BadRequest(`Unable to satisfy object request: ${imageKey}`); | |
} | |
} | |
} |
This file contains 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
import { Inject, Injectable } from "@tsed/di"; | |
import AWS from "aws-sdk"; | |
@Injectable() | |
class S3Client { | |
protected s3 = new AWS.S3(); | |
/** | |
* Grab an object from s3. | |
* e.g. s3://my-bucket/path/to/file.txt | |
* bucket: my-bucket, key: path/to/file.txt | |
* @param bucket Bucket containing object. | |
* @param key Key path to object. | |
*/ | |
async getObject(bucket: string, key: string) { | |
const params = { | |
Bucket: bucket, | |
Key: key | |
}; | |
const metadata = await this.s3.headObject(params).promise(); | |
return { | |
metadata, | |
object: this.s3.getObject(params) | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment