-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
134 lines (94 loc) · 2.63 KB
/
index.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
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
const AWS = require('aws-sdk')
class S3DB {
constructor(s3_key, s3_secret, s3_bucket, s3_prefix = '', s3_acl = 'private', s3_endpoint = false) {
this.s3_key = s3_key
this.s3_secret = s3_secret
this.s3_bucket = s3_bucket
this.s3_prefix = s3_prefix
this.s3_acl = s3_acl
var s3_config = {
accessKeyId: s3_key,
secretAccessKey: s3_secret
}
if (s3_endpoint) {
const endpoint = new AWS.Endpoint(s3_endpoint);
s3_config.endpoint = endpoint
}
AWS.config.update(s3_config);
this.s3Bucket = new AWS.S3({
params: {
Bucket: s3_bucket,
timeout: 6000000
}
});
}
async insert(table, data) {
// get the current data
const curdata = await this.get_all(table)
// generate a new id
const id = this.generate_id()
data._id = id
// add the new data
curdata.push(data)
// save
await this.save(table, curdata)
return id
}
async update(table, data, id) {
// get the current data
const curdata = await this.get_all(table)
// get array key based on _id
const index = curdata.findIndex(x => x._id === id)
curdata[index] = data
// save
await this.save(table, curdata)
return id
}
async delete(table, id) {
// get the current data
const curdata = await this.get_all(table)
// get array key based on _id
const index = curdata.findIndex(x => x._id === id);
const newdata = curdata.slice(0, index).concat(curdata.slice(index + 1, curdata.length))
// save
await this.save(table, newdata)
return id
}
async get_all(table) {
var params = {
Bucket: this.s3_bucket,
Key: this.s3_prefix + table + '.json'
};
return await this.s3Bucket.getObject(params).promise()
.then(function(data) {
return JSON.parse(data.Body.toString('utf-8'))
})
.catch(function(error) {
return []
})
}
async get(table, id) {
// get the current data
const curdata = await this.get_all(table)
// get array key based on _id
const data = curdata.find(x => x._id === id)
return data
}
async save(table, data) {
// save
var params = {
ACL: this.s3_acl,
Key: this.s3_prefix + table + '.json',
Body: JSON.stringify(data),
ContentType: 'application/json'
};
return await this.s3Bucket.putObject(params).promise()
}
generate_id() {
var dt = new Date()
var now = dt.getFullYear() + ("0" + (dt.getMonth() + 1)).slice(-2) + ("0" + dt.getDate()).slice(-2)
var id = now + '-' + Math.floor(Math.random() * Math.floor(99999))
return id
}
}
module.exports = S3DB;