wololo/mappings/utils.ts

223 lines
5.8 KiB
TypeScript
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import * as fs from 'node:fs'
import fetch from 'node-fetch';
let show_debug = 0
// show_debug = 1
let output_folder = 'output';
const prefix_phone_fr_only = true
// console.log('----------------------show_debug', show_debug)
/**
* wrapper de log qui se montre uniquemnt si show_debug a été activé
* @param args
*/
function debugLog(...args: any[]) {
if (show_debug) {
console.log('### debug: ',)
args.map((elem: any) => console.log(' - ', elem))
}
}
const truthyValues = [true, 'true', '1', 'yes', 1]
const falsyValues = [false, 'false', '0', 'no', 0]
let listOfBooleanKeys = [
"prise_type_ef",
"prise_type_2",
"prise_type_combo_ccs",
"prise_type_chademo",
"gratuit",
"paiement_acte",
"paiement_cb",
"cable_t2_attache"
]
function boolToAddable(someBooleanValue: boolean) {
return someBooleanValue ? 1 : 0
}
function isTruthyValue(someValue: string) {
let convertedValue;
if (truthyValues.indexOf(someValue + ''.toLowerCase()) !== -1) {
convertedValue = true
}
if (falsyValues.indexOf(someValue + ''.toLowerCase()) !== -1) {
convertedValue = false
}
return convertedValue
}
/**
*
* @param pointKeyName
* @returns {boolean}
*/
function isBooleanKey(pointKeyName: string): boolean {
return listOfBooleanKeys.indexOf(pointKeyName) !== -1
}
/**
* crée un fichier dans le dossier par défaut, output
* @param fileName
* @param fileContent
*/
function writeFile(fileName: string, fileContent: any, outputPathOverride: string = '') {
if (outputPathOverride) {
output_folder = outputPathOverride
} else {
console.log('pas de output', outputPathOverride
)
}
let destination = `./${output_folder}/${fileName}`.replaceAll('//', '/');
console.log('write file ', destination)
return fs.writeFile(
destination,
fileContent,
'utf8',
(err) => {
if (err) {
console.log(`Error writing file: ${err}`)
} else {
console.log(`File ${fileName} is written successfully!`)
}
}
)
}
/**
* trouve le max dans une string séparée par des points-virgules
* @param str
* @returns
*/
function find_max_in_string(str: string, separator: string = ';') {
let max = 0;
if (str.indexOf(separator) !== -1) {
let explode = str.split(separator);
explode.forEach((item: string) => {
// keep only the number
let value = parseInt(item.replaceAll(/[^0-9]/g, ''));
if (value && value > max) {
max = value;
}
});
return max;
}
return parseInt(str.replaceAll(/[^0-9]/g, ''));
}
/**
* tronque une string à une longueur donnée
* @param str
* @param limit
* @returns
*/
function truncate_enums_to_limit(str: string, limit: number = 255) {
if (str.indexOf(';') !== -1) {
let elements = str.split(';');
let result: string[] = [];
let currentLength = 0;
for (let element of elements) {
// +1 pour le point-virgule qui sera ajouté
if (currentLength + element.length + 1 <= limit) {
result.push(element);
currentLength += element.length + 1;
}
}
let joined = result.join(';');
return joined;
}
if (str.length > limit) {
return str.substring(0, limit)
}
return str
}
function convertToBoolean(originalValue: any): boolean {
if (truthyValues.indexOf(originalValue + ''.toLowerCase()) !== -1) {
return true;
}
if (falsyValues.indexOf(originalValue + ''.toLowerCase()) !== -1) {
return false;
}
return false; // valeur par défaut
}
function convertToYesOrNo(originalValue: any): string {
let intermediateValue = '' + originalValue
let convertedValue = '';
// handle lists with ; as separator
// on ne peut pas conclure ce que l'on doit garder avec une liste
if (intermediateValue.indexOf(';') !== -1) {
return ''
}
intermediateValue = intermediateValue.split(';')[0]
debugLog('convertProperty: ==========> original value', originalValue, intermediateValue)
if (truthyValues.indexOf((originalValue + '').toLowerCase()) !== -1) {
return 'yes'
} else {
debugLog('convertProperty: ==========> !!! NOT in truthy values', originalValue)
}
if (falsyValues.indexOf((originalValue + '').toLowerCase()) !== -1) {
return 'no'
} else {
debugLog('convertProperty: ==========> !!! NOT in falsy values', originalValue)
}
return convertedValue;
}
async function replaceFile(sourceFilePathGeoJson: string, url: string) {
const response = await fetch(url)
if (!response.ok) {
throw new Error(`Erreur lors du téléchargement: ${response.status} ${response.statusText}`)
}
// afficher la taille du fichier téléchargé
const contentLength = response.headers.get('content-length')
const data = await response.text()
if (contentLength) {
const sizeInMB = (parseInt(contentLength) / (1024 * 1024)).toFixed(2)
console.log(`Taille du fichier téléchargé: ${sizeInMB} Mo`)
} else {
// mesurer la taille des données
const sizeInMB = (data.length / (1024 * 1024)).toFixed(2)
console.log(`Taille des données: ${sizeInMB} Mo`)
}
fs.writeFileSync(sourceFilePathGeoJson, data)
console.log('fichier téléchargé avec succès:', sourceFilePathGeoJson)
}
export default {
// debug tools
debugLog,
// typing
boolToAddable,
isBooleanKey,
isTruthyValue,
truthyValues,
falsyValues,
// booleans
convertToBoolean,
convertToYesOrNo,
// research
find_max_in_string,
// formatting
truncate_enums_to_limit,
prefix_phone_fr_only,
// file tools
writeFile,
replaceFile,
}