@wbg-mde/repository
Version:
Managing all common method for file system CRUD operations.
344 lines (343 loc) • 12.5 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const fs = require("fs");
const mkdirp = require("mkdirp");
const path = require("path");
const project_configuration_1 = require("../configuration/project.configuration");
const validator = require("jsen");
const copydir = require("copy-dir");
const _ = require('lodash');
class App_Repository_Utility {
static writeFile(filePath, data) {
let directory = path.dirname(filePath);
mkdirp.sync(directory);
fs.writeFileSync(filePath, data);
}
static readFile(filePath) {
return fs.readFileSync(filePath);
}
static copyFile(sourcepath, destpath) {
fs.createReadStream(sourcepath).pipe(fs.createWriteStream(destpath));
}
static deleteFile(filePath) {
if (fs.existsSync(filePath)) {
return fs.unlinkSync(filePath);
}
}
static getAvailableFilePath(filePath) {
try {
let pathInfo = path.parse(filePath);
let directoryName = pathInfo.dir;
let fileName = pathInfo.name;
let extension = pathInfo.ext;
let counter = 1;
let availableFilePath = path.join(directoryName, fileName + extension);
while (fs.existsSync(availableFilePath)) {
let newFileName = fileName + "(" + counter + ")";
availableFilePath = path.join(directoryName, newFileName + extension);
counter++;
}
return availableFilePath;
}
catch (e) {
this.LogText('Repository >> Util >> GetAvailableFilePath >>' + e, 3);
}
}
static LogText(content, type) {
if (!type || type === 1) {
console.log('%c Metada Editor: ', 'background: #000; color: #FFF', content + ' / ' + new Date());
}
else if (type === 2) {
console.warn('%c Metada Editor: ', 'background: #000; color: #FFF', content + ' / ' + new Date());
}
else if (type === 3) {
console.error('%c Metada Editor: ', 'background: #000; color: #FFF', content + ' / ' + new Date());
}
}
static deleteFolder(folderPath) {
try {
if (fs.existsSync(folderPath)) {
fs.readdirSync(folderPath).forEach((file) => {
var curPath = path.join(folderPath, file);
if (fs.lstatSync(curPath).isDirectory()) {
this.deleteFolder(curPath);
}
else {
fs.unlinkSync(curPath);
}
});
fs.rmdirSync(folderPath);
}
}
catch (e) {
this.LogText('Repository >> Util >> deleteFolder >>' + e, 3);
}
}
static getTypes(includeCustom) {
try {
let filePath = path.join(project_configuration_1.configuaration.masterDataPath, 'app.config.json');
let filestream = fs.readFileSync(filePath).toString();
let types = JSON.parse(filestream).datatypes;
if (includeCustom === true) {
types = [...types, ...this.getCustomTypes()];
}
return types;
}
catch (e) {
this.LogText('Repository >> get types >> error >> ' + e, 3);
return new Array();
}
}
static getCustomTypes() {
try {
return project_configuration_1.configuaration.customDataTypes || [];
}
catch (e) {
this.LogText('Repository >> getCustomTypes >> error >> ' + e, 3);
return new Array();
}
}
static getDataTypeByType(dataType) {
try {
let types = this.getTypes(true);
return _.find(types, (dType) => {
return dType.type === dataType;
});
}
catch (e) {
this.LogText('Repository >> getCustomTypes >> error >> ' + e, 3);
return new Array();
}
}
static getAppConfig() {
try {
let filePath = path.join(project_configuration_1.configuaration.masterDataPath, 'app.config.json');
let filestream = fs.readFileSync(filePath).toString();
let config = JSON.parse(filestream);
return config;
}
catch (e) {
this.LogText('Repository >> getAppConfig >> error >> ' + e, 3);
return {};
}
}
static formatFileNameByLanguage(name, language, extenstion) {
if (extenstion === undefined) {
extenstion = "json";
}
if (extenstion === false && name.indexOf('_' + language) === -1) {
return name.concat('_', language);
}
if (extenstion === false && name.indexOf('_' + language) !== -1) {
return name;
}
if (name.indexOf('_' + language) !== -1) {
return name.concat('.', extenstion);
}
return name.concat('_', language, '.', extenstion);
}
static concatExt(fileName, extension) {
if (!extension) {
extension = "json";
}
return fileName.concat('.', extension);
}
static setNestedProperty(object, property, value) {
try {
if (object && typeof object == "object") {
if (typeof property == "string" && property !== "") {
var split = property.split(".");
return split.reduce(function (obj, prop, idx) {
obj[prop] = obj[prop] || {};
if (split.length == (idx + 1)) {
obj[prop] = value;
}
return obj[prop];
}, object);
}
else if (typeof property == "number") {
object[property] = value;
return object[property];
}
else {
return object;
}
}
else {
return object;
}
}
catch (e) {
this.LogText("Repository >> utility >> setNestedProperty >> Error >> " + e, 3);
return undefined;
}
}
static getNestedProperty(object, property) {
try {
property = property.split(',')[0];
let paths = property.split('.'), current = object, i;
for (i = 0; i < paths.length; ++i) {
if (current[paths[i]] == undefined) {
if (i == paths.length - 1 && paths[i] == "#") {
if (!(current instanceof Object) && !(current instanceof Array)) {
return current;
}
}
return undefined;
}
else {
if (i == paths.length - 1) {
current = current[paths[i]];
}
else {
if (current[paths[i]] instanceof Array) {
current = current[paths[i]][0];
}
else {
current = current[paths[i]];
}
}
}
}
return current;
}
catch (e) {
this.LogText("Repository >> utility >> GetNestedProperty >> Error >> " + e, 3);
return undefined;
}
}
static getArrayNestedProperty(object, property) {
let currentArray = [];
try {
_.each(object, (res) => {
property = property.split(',')[0];
let paths = property.split('.'), current = res, i;
for (i = 0; i < paths.length; ++i) {
if (current[paths[i]] == undefined) {
return undefined;
}
else {
if (i == paths.length - 1) {
current = current[paths[i]];
}
else {
if (current[paths[i]] instanceof Array) {
current = current[paths[i]][0];
}
else {
current = current[paths[i]];
}
}
}
}
currentArray.push(current);
});
return currentArray;
}
catch (e) {
this.LogText("Repository >> utility >> getArrayNestedProperty >> Error >> " + e, 3);
return undefined;
}
}
static validateSchema(schema, data) {
try {
let validate = validator(schema, { greedy: true });
let isValid = validate(data);
if (isValid) {
return { result: 'ok' };
}
else {
return { result: 'error', Errors: validate.errors };
}
}
catch (e) {
this.LogText("Repository >> utility >> ValidateSchema >> Error >> " + e, 3);
return { result: 'error', Errors: e };
}
}
static generateGUID() {
let d = new Date().getTime();
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
let r = (d + Math.random() * 16) % 16 | 0;
d = Math.floor(d / 16);
return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
});
}
static getPropertyArray(obj) {
let propArray = new Array();
_.forEach(obj, (item, key) => {
if (item instanceof Array && item.length > 0) {
propArray = [...propArray, ...item];
}
});
return propArray;
}
static moveFolder(activeFilePath, newFilePath) {
try {
let activePath = path.join(activeFilePath, "CSV Data");
let newPath = path.join(newFilePath, "CSV Data");
if (fs.existsSync(activePath)) {
fs.mkdirSync(newPath);
copydir(activePath, newPath, function (err) {
if (err) {
}
else {
}
});
}
}
catch (e) {
this.LogText("Repository >> utility >> moveFolder >> Error >> " + e, 3);
return undefined;
}
}
static getAlli18nResources() {
try {
project_configuration_1.configuaration.refresh();
return project_configuration_1.configuaration.i18nResources;
}
catch (e) {
this.LogText("Repository >> utility >> getAlli18nResources >> Error >> " + e, 3);
return undefined;
}
}
static formatString(text, appenders) {
if (appenders.length == 0) {
return text;
}
var str = text;
for (var i = 0; i < appenders.length; i++) {
var placeHolder = '{' + (i) + '}';
str = str.replace(placeHolder, appenders[i]);
}
return str;
}
static formatURLPath(url, params) {
if (_.isEmpty(params)) {
return url;
}
var str = url;
for (var placeholder in params) {
var regex = new RegExp("\\$\\{" + placeholder + "\\}", "g");
str = str.replace(regex, params[placeholder]);
}
return str;
}
static getFormattedDate() {
let name = new Date().toLocaleDateString();
name = name.split('/');
return name.join('-').replace(/ /g, '');
}
static isEmpty(val) {
if (val === undefined) {
return true;
}
else if ((val instanceof Array || val instanceof Object) && _.isEmpty(val)) {
return true;
}
else {
return false;
}
}
}
exports.App_Repository_Utility = App_Repository_Utility;