forked from webaverse/api-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaws.js
101 lines (88 loc) · 1.97 KB
/
aws.js
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
const stream = require('stream');
const AWS = require('aws-sdk');
let config = require('fs').existsSync('./config.json') ? require('./config.json') : null;
const accessKeyId = process.env.accessKeyId || config.accessKeyId;
const secretAccessKey = process.env.secretAccessKey || config.secretAccessKey;
const awsConfig = new AWS.Config({
credentials: new AWS.Credentials({
accessKeyId,
secretAccessKey,
}),
region: 'us-west-1',
});
const s3 = new AWS.S3(awsConfig);
const ddb = new AWS.DynamoDB({
...awsConfig,
apiVersion: '2012-08-10',
});
const ddbd = new AWS.DynamoDB.DocumentClient({
...awsConfig,
apiVersion: '2012-08-10',
});
const defaultDynamoTable = 'sidechain-cache';
async function getDynamoItem(id, TableName) {
const params = {
TableName,
Key: {
id,
},
};
try {
return await ddbd.get(params).promise();
} catch (e) {
console.error(e);
return null;
}
}
async function putDynamoItem(id, data, TableName) {
const params = {
TableName,
Item: {
...data,
id,
},
};
try {
return ddbd.put(params).promise();
} catch (e) {
console.error(e);
return false;
}
}
async function getDynamoAllItems(TableName = defaultDynamoTable) {
const params = {
TableName,
};
try {
const o = await ddbd.scan(params).promise();
const items = (o && o.Items) || [];
return items;
} catch (e) {
console.error(e);
return null;
}
}
function uploadFromStream(bucket, key, type) {
const pass = new stream.PassThrough();
const params = {Bucket: bucket, Key: key, Body: pass, ACL: 'public-read'};
if (type) {
params['ContentType'] = type;
}
s3.upload(params, function(err, data) {
console.log('emit done', !!err, !!data);
if (err) {
pass.emit('error', err);
} else {
pass.emit('done', data);
}
});
return pass;
}
module.exports = {
ddb,
ddbd,
getDynamoItem,
putDynamoItem,
getDynamoAllItems,
uploadFromStream,
}