-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paths3Service.ts
135 lines (108 loc) · 3.07 KB
/
s3Service.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
import * as AWS from 'aws-sdk';
import * as _ from 'lodash'
/**
* wrapper for aws s3 that support Promises
*
* @export
* @class S3Service
*/
export class S3Service {
private _s3Bucket: string;
private _s3 : AWS.S3;
constructor(s3Bucket: string) {
if (!s3Bucket) {
throw "Invalid S3 Bucket";
}
this._s3Bucket = s3Bucket;
}
public listObjectNames(prefix?: string) : Promise<any> {
const maxKeys = 2147483647;
const delimiter = '/';
return new Promise((resolve, reject) => {
try {
let files = [];
let f = function (data) {
files = files.concat(_.map(data.Contents, 'Key'));
if (data.IsTruncated) {
this._s3.listObjectsV2({
Bucket: this._s3Bucket,
MaxKeys: maxKeys,
Delimiter: delimiter,
Prefix: prefix,
ContinuationToken: data.NextContinuationToken
}, (err, data) => {
if (err) {
reject("Error calling listObjectsV2 on S3. Error: " + err);
} else {
f.call(this, data);
}});
}
else
{
resolve(files);
}
}
this._connect();
this._s3.listObjectsV2({
Bucket: this._s3Bucket,
MaxKeys: maxKeys,
Delimiter: delimiter,
Prefix: prefix,
StartAfter: prefix
}, (err, data) => {
if (err) {
reject("Error calling listObjectsV2 on S3. Error: " + err);
} else {
f.call(this, data);
}});
} catch (e) {
reject("Exception occurred in S3Service::listObjectNames(): " + e);
}
});
}
public exists(key: string, prefix?: string) : Promise<any> {
return new Promise((resolve, reject) => {
try {
this._connect();
this._s3.headObject({
Bucket: this._s3Bucket,
Key: (prefix || '') + key,
}, (err, data) => {
if (err) {
resolve(false);
} else {
resolve(true);
}});
} catch (e) {
reject("Exception occurred in S3Service::exists(): " + e);
}
});
}
public putObject(key: string, body: string, acl: string, keepMetadata: boolean, prefix?: string, metadata?: any) : Promise<any> {
return new Promise((resolve, reject) => {
try {
this._connect();
//TODO: if keepMetadata, retrieve current list of metadata keys and merge with metadata object
this._s3.putObject({
Bucket: this._s3Bucket,
Body: body,
Key: (prefix || '') + key,
ACL: acl,
Metadata: (metadata || null)
}, (err, data) => {
if (err) {
reject("Error calling putObject on S3. Error: " + err);
} else {
resolve();
}});
} catch (e) {
reject("Exception occurred in S3Service::putObject(): " + e);
}
});
}
private _connect() {
if (!this._s3) {
this._s3 = new AWS.S3({params: {Bucket: this._s3Bucket}});
}
}
}