1 | import * as AWS from "aws-sdk";
|
2 | import * as path from "path";
|
3 | import { IS3UploadOptions, IUploadResult, IUploader } from "../interfaces/uploader";
|
4 | import { mimeTypes } from "./mimeTypes";
|
5 |
|
6 | const s3 = new AWS.S3();
|
7 |
|
8 | export class S3Uploader implements IUploader {
|
9 | private bucket: string = "static-asset";
|
10 | private acl: string = "public-read";
|
11 | private cacheControl: string = "public, max-age=0, s-maxage=86400";
|
12 |
|
13 | public async upload(options: IS3UploadOptions) {
|
14 | const ext = this.extension(options.key);
|
15 |
|
16 | return new Promise<IUploadResult>((resolve, reject) => {
|
17 | s3.putObject({
|
18 | Bucket: options.bucket || this.bucket,
|
19 | Key: options.key,
|
20 | ACL: options.acl || this.acl,
|
21 | Body: options.body,
|
22 | ContentType: mimeTypes[ext],
|
23 | CacheControl: options.cacheControl || this.cacheControl,
|
24 | }, (err, result) => {
|
25 | if (err) {
|
26 | return reject(err);
|
27 | }
|
28 |
|
29 | return resolve({
|
30 | key: options.key,
|
31 | etag: result.ETag,
|
32 | });
|
33 | });
|
34 | });
|
35 | }
|
36 |
|
37 | public extension(key) {
|
38 | return path.extname(key).replace(/^./, "");
|
39 | }
|
40 | }
|
41 |
|
\ | No newline at end of file |