Skip to content

Instantly share code, notes, and snippets.

@loloDawit
Created November 19, 2021 02:13
Show Gist options
  • Select an option

  • Save loloDawit/5d8b8f71212e501ca8cad10ca1dd6f68 to your computer and use it in GitHub Desktop.

Select an option

Save loloDawit/5d8b8f71212e501ca8cad10ca1dd6f68 to your computer and use it in GitHub Desktop.
Util function
"use strict";
const AWS = require("aws-sdk");
const moment = require("moment");
const ErrorResponse = require("../common/error");
const s3 = new AWS.S3();
const {fetchAllDashboards, fetchDashboardDetails} = require("../newrelic/dashboard");
require("dotenv").config();
/**
* getErrorMessage
* @param {*} message
* @returns Formatted error message
*/
const getErrorMessage = (message) => ({
statusCode: 500,
body: JSON.stringify({
message
})
});
/**
* uploadToS3
* @param {*} bucket
* @param {*} key
* @param {*} buffer
* @returns Promise<data,err>
*/
const uploadToS3 = (bucket, key, buffer) =>
new Promise((resolve, reject) => {
s3.upload(
{
Bucket: bucket,
Key: key,
Body: buffer,
ContentEncoding: "base64",
ContentType: "application/json"
},
(err, data) => {
if (err) {
console.log(err);
reject(err);
}
console.log(`File uploaded successfully. ${data.Location}`);
resolve(data);
}
);
});
/**
* getDate
* @returns formatted current date
*/
const getDate = () => {
let now = new Date();
return moment(now).format("YYYY-MM-DD");
};
const getIds = async () => {
try {
let data = await fetchAllDashboards();
return convertArrayToObject(data, "guid");
} catch (error) {
new ErrorResponse(error.message, error.code);
}
};
const getDashboards = async () => {
try {
let data = await fetchDashboardDetails();
return convertArrayToObject(data, "guid");
} catch (error) {
new ErrorResponse(error.message, error.code);
}
};
/**
* convertArrayToObject
* @param {*} array
* @param {*} key
* @returns An object
*/
const convertArrayToObject = (array, key) => {
const initialValue = {};
return array.reduce((obj, item) => {
let name = item.name.replace(/\s/g, "");
let guid = item[key];
let lastEight = guid.substr(guid.length - 8) + name;
return {
...obj,
[lastEight]: item
};
}, initialValue);
};
module.exports = {getDate, getDashboards, convertArrayToObject, uploadToS3, getIds, getErrorMessage};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment