forked from pecigonzalo/dolar-ar
/
storage.js
94 lines (85 loc) · 2.49 KB
/
storage.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
const aws = require("aws-sdk");
const s3 = new aws.S3({
endpoint: process.env.S3_ENDPOINT || "",
s3ForcePathStyle: true,
});
const fs = require("fs");
const logger = require("./logger");
const s3FileInfo = {
Bucket: process.env.STORE_BUCKET || "",
Key: process.env.STORE_KEY || "",
};
// S3 Functions
const loadStoredRates = (success, error) => {
if (process.env.BACKEND !== "s3") {
return loadStoredRatesLocal(success, error);
}
logger.info("Loading rates from S3");
s3.getObject(s3FileInfo, function (err, data) {
if (err) {
// TODO: handle this a bit better
if (err.code === "NoSuchBucket") {
logger.warn("Bucket not found, creating");
let bucketParams = {
Bucket: s3FileInfo.Bucket,
};
s3.createBucket(bucketParams, function (err, data) {
if (err) {
logger.error("Error", err);
} else {
logger.info("Created: ", data.Location);
loadStoredRates();
}
error();
});
} else {
logger.error("Error. Probably no initial rates found...", err);
error();
}
} else {
const loadedRates = JSON.parse(data.Body.toString());
logger.info("Previous rates found", loadedRates);
success(loadedRates);
}
});
};
const loadStoredRatesLocal = (success, error) => {
logger.info("Loading rates from file");
fs.readFile(s3FileInfo.Key, function (err, data) {
if (err) return error(err);
logger.info("Read from file", JSON.parse(data.toString()));
const loadedRates = JSON.parse(data.toString());
logger.info("Previous rates found", loadedRates);
success(loadedRates);
});
};
const saveRates = (currentRates, callback) => {
if (process.env.BACKEND !== "s3") {
return saveRatesLocal(currentRates, callback);
}
logger.info("Saving rates to S3", currentRates);
s3.putObject(
{
Bucket: s3FileInfo.Bucket,
Key: s3FileInfo.Key,
Body: JSON.stringify(currentRates),
ContentType: "application/json",
},
function (error, response) {
if (error) console.error(error);
else logger.info("Saved rates to S3");
if (callback) callback();
}
);
};
const saveRatesLocal = (currentRates, callback) => {
logger.info("Saving rates to file", currentRates);
fs.writeFile(s3FileInfo.Key, JSON.stringify(currentRates), function (err) {
if (err) return console.error(err);
if (callback) callback();
});
};
module.exports = {
loadStoredRates,
saveRates,
};