From d8d5e7890bfc9470c284483527d4a1ef6e47b2cf Mon Sep 17 00:00:00 2001 From: Alessio Date: Sat, 14 Sep 2024 22:13:43 +0200 Subject: [PATCH] v3.0.0 --- README.md | 114 ++++++++------------------------- package/README.md | 114 ++++++++------------------------- package/package.json | 7 +- package/src/ClientFilters.ts | 74 --------------------- package/src/GenericUtils.ts | 41 +++++++----- package/src/Logger.ts | 108 ------------------------------- package/src/index.ts | 4 +- package/types/generic.types.ts | 28 ++++---- package/types/locales.types.ts | 9 --- test/test.ts | 68 +++++++++----------- test/utils.ts | 5 +- 11 files changed, 127 insertions(+), 445 deletions(-) delete mode 100644 package/src/ClientFilters.ts delete mode 100644 package/src/Logger.ts delete mode 100644 package/types/locales.types.ts diff --git a/README.md b/README.md index e76ec1f..57f6f88 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ -`v2.1.2` +`v3.0.0` This is a package i made for myself but can surely be helpful to others, feel free to contribute if you like it. @@ -11,10 +11,11 @@ This is a package i made for myself but can surely be helpful to others, feel fr > If you need excel js install[fast-js-excel](https://github.com/alessioVelluso/FastExcel) or take a look at [word-file-utils](https://github.com/alessioVelluso/WordFileUtils) if you need some file utilities without the use of exceljs library. > **DO NOT INSTALL ALL THREE LIBS CAUSE ONE IS THE "PARENT" OF THE OTHER:** > 1. `utils-stuff` -> 2. `word-file-utils` (including utils-stuff) -> 3. `fast-js-excel` (including exceljs, word-file-utils (including utils-stuff)) +> 2. `utils-logger` (including utils-stuff) +> 3. `word-file-utils` (including utils-logger) +> 4. `fast-js-excel` (including exceljs, word-file-utils (including utils-stuff)) > ->So if you install word-file utils you can use the classes of utils-stuff and so on, choose the one for your pourpose. +>So if you install word-file utils you don't need to install utils-logger and so on, choose the one for your pourpose. @@ -36,34 +37,14 @@ You can import two different classes, `GenericUtils` as default & `ClientFilters At the moment, the interface of the class is as it follows: ```ts -interface IGenericUtils { - parseDate: (date?:string) => string - catchRes: (isOk:false, response:T | null, error?:string | null) => CatchedResponse - catchResError:(err:any) => CatchedResponse - isAxiosOk: (res:{ status:number, [Key:string]: GenericType} /* pass an AxiosResponse */) => boolean; - isStringValid: (str?:string) => boolean - arrayDiff: (originalArray:T[], currentArray:T[]) => { removed:T[], added:T[] }; - isNumeric: (str:string) => boolean; - - log: (message:any, color:LogColors) => void; - logColor: (coloredMessage:any, ...messages:any[]) => void; - logDetail: (...messages:any[]) => void; - logError: (...errs:any[]) => void; - - logFile: (message:string, type?:"log" | "error", isClosing?:boolean) => void; -} - - - -interface IClientFilters { - values:T - currentParams:string; - currentHref:string; - currentWholeUrl:string; - - buildParams:() => string | null; - buildWholeUrl:() => string | null; - // setHref:() => string | null; --- private +export interface IGenericUtils { + parseDate: (date?:string) => string + resOk: (response:T) => CatchedResponse + resError:(err:any) => CatchedResponse + isAxiosOk: (res:{ status:number, [Key:string]: GenericType} /* pass an AxiosResponse */) => boolean; + isStringValid: (str?:string) => boolean; + arrayDiff: (originalArray:T[], currentArray:T[]) => ArrayDifference; + isNumeric: (str:string) => boolean; } ``` @@ -73,14 +54,19 @@ interface IClientFilters { ## Initialize the class ```ts -import { GenericUtils , ClientFilters} from "word-file-utils" +import { GenericUtils } from "word-file-utils" ``` **GenericUtils:** I suggest you to create a generic utils class extending mine if you want a solid way to store all your utils functions or whatever. You can find an example in the `test3/utils.ts` file in this repo. The constructor of GenericUtils follows this interface: ```ts -constructor(data?:LoggerConstructor) -interface LoggerConstructor { logFilePath?:string, debug?:boolean } +protected readonly dateLocale:DateLocales = "en-US"; +protected readonly isNumericRegex:RegExp = /^-?\d+(\.\d+)?$/ +constructor(constructor?:GenericUtilsConstructor) +export interface GenericUtilsConstructor { + locale?:DateLocales, + numericValidation?:RegExp +} ``` While the logFilePath is required only if you have to write log files somewhere in prod, the debug flag is by default set to true and will avoid any logging in console if set to false *(for the log methods of this class)*. @@ -94,70 +80,22 @@ class MyGenericUtils extends GenericUtils { return `Hello ${name}` } } -const mgu = new MyGenericUtils(/*{ debug: env.DEBUG }*/) +const mgu = new MyGenericUtils(/*{ locale: "it-IT" }*/) // Or simply export mine directly -const gu = new GenericUtils(/*{ debug: env.DEBUG }*/) +const gu = new GenericUtils(/*{ locale: "it-IT" }*/) ``` Export it however you want but i raccomand you to init a single object and use it through all the project. ```ts -export default new GenericUtils(/*{ debug: env.DEBUG }*/) +export default new GenericUtils(/*{ locale: "it-IT" }*/) // Or destruct the single functions const gu = new GenericUtils(/*{ debug: env.DEBUG }*/) -const { log, logDetails, logError } = gu; -export { log, logDetails, logError } +const { resOk, resError, isStringValid } = gu; +export { resOk, resError, isStringValid } ``` The related methods are really simple and can be easily read in the realted `/package/src/GenericUtils.ts` file in this repo. The only method not-so-easy to read is the `isNumeric` RegExp wich will return true if the passed string is any int, float, double or negative number. - - -**ClientFilters**: For the ClientFilters class i reccomand you to initialize a new object every file that requires it. - -I reccomand you to create a `/types/filters.ts` file to store all different filters interface you'll use through app as those can be helpful for queries or other logics. -```ts -interface ExampleFilter extends ClientFilter { startDate:Date, endDate:Date, type:number, active?:boolean } -interface AnotherFilter extends ClientFilter { startDate:Date, endDate:Date, name?:string } -``` - -To create a ClientFilters object consider this code: -```ts -const filter = new ClientFilters({ - startDate: new Date(), - endDate: new Date(), - type: 2, -}); -``` -In this case we will have a `filter` object having: -1. `.values`: the current values of the filters (the ones specified in the constructors) -2. `.currentParams`: a string rapresenting the current values parsed as a param string (`?value1=1&value2=true`) -3. `.currentHref`: if the object is initialized in a client, this will be set as the related window.location.href value, else null. -4. `.currentWholeUrl`: if the currentHref is not null, this prop will hold the combination of currentHref and currentParams, else it will be null. - - - - -## Types - -```ts -// --- Generic Utils -export interface GenericObject { [Key:string]: string | number | boolean | Date | GenericObject } -export type GenericType = string | number | boolean | Date | GenericObject -export interface CatchedResponse { isOk:boolean, response: T | null, error?:string | null } -export interface PaginatedParams{ currentPage:number, quantity:number, filter?:T } -export interface PaginatedResponse{ totalPages:number, data:T } -export interface SelectOptions { id:string, text:string } - - -// --- Logger -export type LogColors = "red" | "green" | "yellow" | "blue" | "magenta" | "cyan" | "gray" | null -export interface LoggerConstructor { logFilePath?:string, debug?:boolean } - - -// --- Custom Navigation -export type ClientFilterTypes = string | number | Date | boolean | Array | undefined -export interface ClientFilter { [Key:string]: ClientFilterTypes } -``` diff --git a/package/README.md b/package/README.md index e76ec1f..57f6f88 100644 --- a/package/README.md +++ b/package/README.md @@ -2,7 +2,7 @@ -`v2.1.2` +`v3.0.0` This is a package i made for myself but can surely be helpful to others, feel free to contribute if you like it. @@ -11,10 +11,11 @@ This is a package i made for myself but can surely be helpful to others, feel fr > If you need excel js install[fast-js-excel](https://github.com/alessioVelluso/FastExcel) or take a look at [word-file-utils](https://github.com/alessioVelluso/WordFileUtils) if you need some file utilities without the use of exceljs library. > **DO NOT INSTALL ALL THREE LIBS CAUSE ONE IS THE "PARENT" OF THE OTHER:** > 1. `utils-stuff` -> 2. `word-file-utils` (including utils-stuff) -> 3. `fast-js-excel` (including exceljs, word-file-utils (including utils-stuff)) +> 2. `utils-logger` (including utils-stuff) +> 3. `word-file-utils` (including utils-logger) +> 4. `fast-js-excel` (including exceljs, word-file-utils (including utils-stuff)) > ->So if you install word-file utils you can use the classes of utils-stuff and so on, choose the one for your pourpose. +>So if you install word-file utils you don't need to install utils-logger and so on, choose the one for your pourpose. @@ -36,34 +37,14 @@ You can import two different classes, `GenericUtils` as default & `ClientFilters At the moment, the interface of the class is as it follows: ```ts -interface IGenericUtils { - parseDate: (date?:string) => string - catchRes: (isOk:false, response:T | null, error?:string | null) => CatchedResponse - catchResError:(err:any) => CatchedResponse - isAxiosOk: (res:{ status:number, [Key:string]: GenericType} /* pass an AxiosResponse */) => boolean; - isStringValid: (str?:string) => boolean - arrayDiff: (originalArray:T[], currentArray:T[]) => { removed:T[], added:T[] }; - isNumeric: (str:string) => boolean; - - log: (message:any, color:LogColors) => void; - logColor: (coloredMessage:any, ...messages:any[]) => void; - logDetail: (...messages:any[]) => void; - logError: (...errs:any[]) => void; - - logFile: (message:string, type?:"log" | "error", isClosing?:boolean) => void; -} - - - -interface IClientFilters { - values:T - currentParams:string; - currentHref:string; - currentWholeUrl:string; - - buildParams:() => string | null; - buildWholeUrl:() => string | null; - // setHref:() => string | null; --- private +export interface IGenericUtils { + parseDate: (date?:string) => string + resOk: (response:T) => CatchedResponse + resError:(err:any) => CatchedResponse + isAxiosOk: (res:{ status:number, [Key:string]: GenericType} /* pass an AxiosResponse */) => boolean; + isStringValid: (str?:string) => boolean; + arrayDiff: (originalArray:T[], currentArray:T[]) => ArrayDifference; + isNumeric: (str:string) => boolean; } ``` @@ -73,14 +54,19 @@ interface IClientFilters { ## Initialize the class ```ts -import { GenericUtils , ClientFilters} from "word-file-utils" +import { GenericUtils } from "word-file-utils" ``` **GenericUtils:** I suggest you to create a generic utils class extending mine if you want a solid way to store all your utils functions or whatever. You can find an example in the `test3/utils.ts` file in this repo. The constructor of GenericUtils follows this interface: ```ts -constructor(data?:LoggerConstructor) -interface LoggerConstructor { logFilePath?:string, debug?:boolean } +protected readonly dateLocale:DateLocales = "en-US"; +protected readonly isNumericRegex:RegExp = /^-?\d+(\.\d+)?$/ +constructor(constructor?:GenericUtilsConstructor) +export interface GenericUtilsConstructor { + locale?:DateLocales, + numericValidation?:RegExp +} ``` While the logFilePath is required only if you have to write log files somewhere in prod, the debug flag is by default set to true and will avoid any logging in console if set to false *(for the log methods of this class)*. @@ -94,70 +80,22 @@ class MyGenericUtils extends GenericUtils { return `Hello ${name}` } } -const mgu = new MyGenericUtils(/*{ debug: env.DEBUG }*/) +const mgu = new MyGenericUtils(/*{ locale: "it-IT" }*/) // Or simply export mine directly -const gu = new GenericUtils(/*{ debug: env.DEBUG }*/) +const gu = new GenericUtils(/*{ locale: "it-IT" }*/) ``` Export it however you want but i raccomand you to init a single object and use it through all the project. ```ts -export default new GenericUtils(/*{ debug: env.DEBUG }*/) +export default new GenericUtils(/*{ locale: "it-IT" }*/) // Or destruct the single functions const gu = new GenericUtils(/*{ debug: env.DEBUG }*/) -const { log, logDetails, logError } = gu; -export { log, logDetails, logError } +const { resOk, resError, isStringValid } = gu; +export { resOk, resError, isStringValid } ``` The related methods are really simple and can be easily read in the realted `/package/src/GenericUtils.ts` file in this repo. The only method not-so-easy to read is the `isNumeric` RegExp wich will return true if the passed string is any int, float, double or negative number. - - -**ClientFilters**: For the ClientFilters class i reccomand you to initialize a new object every file that requires it. - -I reccomand you to create a `/types/filters.ts` file to store all different filters interface you'll use through app as those can be helpful for queries or other logics. -```ts -interface ExampleFilter extends ClientFilter { startDate:Date, endDate:Date, type:number, active?:boolean } -interface AnotherFilter extends ClientFilter { startDate:Date, endDate:Date, name?:string } -``` - -To create a ClientFilters object consider this code: -```ts -const filter = new ClientFilters({ - startDate: new Date(), - endDate: new Date(), - type: 2, -}); -``` -In this case we will have a `filter` object having: -1. `.values`: the current values of the filters (the ones specified in the constructors) -2. `.currentParams`: a string rapresenting the current values parsed as a param string (`?value1=1&value2=true`) -3. `.currentHref`: if the object is initialized in a client, this will be set as the related window.location.href value, else null. -4. `.currentWholeUrl`: if the currentHref is not null, this prop will hold the combination of currentHref and currentParams, else it will be null. - - - - -## Types - -```ts -// --- Generic Utils -export interface GenericObject { [Key:string]: string | number | boolean | Date | GenericObject } -export type GenericType = string | number | boolean | Date | GenericObject -export interface CatchedResponse { isOk:boolean, response: T | null, error?:string | null } -export interface PaginatedParams{ currentPage:number, quantity:number, filter?:T } -export interface PaginatedResponse{ totalPages:number, data:T } -export interface SelectOptions { id:string, text:string } - - -// --- Logger -export type LogColors = "red" | "green" | "yellow" | "blue" | "magenta" | "cyan" | "gray" | null -export interface LoggerConstructor { logFilePath?:string, debug?:boolean } - - -// --- Custom Navigation -export type ClientFilterTypes = string | number | Date | boolean | Array | undefined -export interface ClientFilter { [Key:string]: ClientFilterTypes } -``` diff --git a/package/package.json b/package/package.json index e0d8315..3671f51 100644 --- a/package/package.json +++ b/package/package.json @@ -1,6 +1,6 @@ { "name": "utils-stuff", - "version": "2.1.2", + "version": "3.0.0", "author": "Alessio Velluso", "license": "MIT", "description": "Generic utils, both for server or client uses", @@ -26,10 +26,9 @@ "build": "tsup" }, "keywords": [ - "log", - "filters", + "frontend", + "backend", "client", - "color", "utils", "utilities" ] diff --git a/package/src/ClientFilters.ts b/package/src/ClientFilters.ts deleted file mode 100644 index 979335e..0000000 --- a/package/src/ClientFilters.ts +++ /dev/null @@ -1,74 +0,0 @@ -import { ClientFilter, ClientFilterTypes } from "../types/generic.types"; - -export interface IClientFilters { - values:T - currentParams:string; - currentHref:string; - currentWholeUrl:string; - buildParams:() => string | null; - buildWholeUrl:() => string | null; - // setHref:() => string | null; --- private -} - -export default class GenericClientFilter implements IClientFilters -{ - constructor(filter: T) { - this.values = new Proxy(filter, this.handler); - this.currentParams = this.buildParams(); - this.currentHref = this.setHref(); - this.currentWholeUrl = this.buildWholeUrl(); - } - - - public values = {} as T; - public currentParams:string = null!; - public currentHref:string = null!; - public currentWholeUrl:string = null!; - private readonly handler:ProxyHandler = { - get: (target: any, prop: string) => { - if (prop in target) return target[prop]; - else return undefined; - }, - set: (target: any, prop: string, value: any) => { - target[prop] = value; - this.currentParams = this.buildParams(); - this.currentWholeUrl = this.buildWholeUrl(); - return true; - } - }; - - - public buildParams = () => { - const keys = Object.keys(this.values).filter(x => this.values[x] !== undefined); - if (keys.length === 0) return null!; - - let params = "?"; - let key = "", value = "" as ClientFilterTypes; - for (let i = 0; i < keys.length; i++) { - key = keys[i]; - value = this.values[key]; - if (value instanceof Date) value = value.toISOString(); - else if (Array.isArray(value)) value = value.join(",") - - params += `${key}=${value}`; - if (i !== keys.length -1) params += "&"; - } - - return params; - } - - public buildWholeUrl = () => { - let wholeUrl:string = null!; - if (this.currentHref !== null) { - wholeUrl = this.currentHref; - if (this.currentParams !== null) wholeUrl += this.currentParams; - } - - return wholeUrl; - } - - private setHref = () => { - try { return window.location.href; } - catch { return null!; } - } -} diff --git a/package/src/GenericUtils.ts b/package/src/GenericUtils.ts index 2ed2f5a..1f82098 100644 --- a/package/src/GenericUtils.ts +++ b/package/src/GenericUtils.ts @@ -1,26 +1,30 @@ -import { CatchedResponse, GenericType, LoggerConstructor } from "../types/generic.types"; -import Logger from "./Logger"; +import { CatchedResponse, GenericType, DateLocales, ArrayDifference, GenericUtilsConstructor } from "../types/generic.types"; export interface IGenericUtils { parseDate: (date?:string) => string - catchRes: (isOk:false, response:T | null, error?:string | null) => CatchedResponse - catchResError:(err:any) => CatchedResponse + resOk: (response:T) => CatchedResponse + resError:(err:any) => CatchedResponse isAxiosOk: (res:{ status:number, [Key:string]: GenericType} /* pass an AxiosResponse */) => boolean; isStringValid: (str?:string) => boolean; - arrayDiff: (originalArray:T[], currentArray:T[]) => { removed:T[], added:T[] }; + arrayDiff: (originalArray:T[], currentArray:T[]) => ArrayDifference; isNumeric: (str:string) => boolean; } -export default class GenericUtils extends Logger implements IGenericUtils +export default class GenericUtils implements IGenericUtils { - constructor(data?:LoggerConstructor) { - super(data); + protected readonly dateOptions: Intl.DateTimeFormatOptions = { day: '2-digit', month: '2-digit', year: 'numeric' }; + protected readonly timeOptions: Intl.DateTimeFormatOptions = { hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false } + + protected readonly dateLocale:DateLocales = "en-US"; + protected readonly isNumericRegex:RegExp = /^-?\d+(\.\d+)?$/ + constructor(constructor?:GenericUtilsConstructor) { + this.dateLocale = constructor?.locale ?? this.dateLocale + this.isNumericRegex = constructor?.numericValidation ?? this.isNumericRegex } - public readonly isNumericRegex:RegExp = /^-?\d+(\.\d+)?$/ parseDate = (date?:string):string => { @@ -29,13 +33,12 @@ export default class GenericUtils extends Logger implements IGenericUtils }; - catchRes = (isOk: boolean, response: T | null, error: string | null = null): CatchedResponse => { - return { isOk, response, error } + resOk = (response: T): CatchedResponse => { + return { isOk:true, response, error:null } }; - catchResError = (err:any):CatchedResponse => { - this.logError(err) + resError = (err:any):CatchedResponse => { return { isOk: false, response:null, error:err.message ? err.message : err } } @@ -54,11 +57,17 @@ export default class GenericUtils extends Logger implements IGenericUtils } - arrayDiff = (originalArray:T[], currentArray:T[]):{ removed:T[], added:T[] } => { + arrayDiff = (originalArray:T[], currentArray:T[]):ArrayDifference => { + const added:T[] = []; + const same:T[] = []; const removed = originalArray.filter(x => !currentArray.includes(x)); - const added = currentArray.filter(x => !originalArray.includes(x)); - return { removed, added } + for (const item of originalArray) { + if (currentArray.includes(item)) same.push(item); + else added.push(item); + } + + return { removed, added, same } } isNumeric = (str:string):boolean => { diff --git a/package/src/Logger.ts b/package/src/Logger.ts deleted file mode 100644 index d8fc960..0000000 --- a/package/src/Logger.ts +++ /dev/null @@ -1,108 +0,0 @@ -import { WriteStream, createWriteStream } from "fs"; -import { LogColors, LoggerConstructor } from "../types/generic.types"; -import { DateLocales } from "../types/locales.types"; - -export interface ILogger { - log: (message:any, color:LogColors) => void; - logColor: (coloredMessage:any, ...messages:any[]) => void; - logDetail: (...messages:any[]) => void; - logError: (...errs:any[]) => void; - - logFile: (message:string, type?:"log" | "error", isClosing?:boolean) => void; -} - - -export default class Logger implements ILogger -{ - private readonly isDebug:boolean = true; - private readonly fileStream:WriteStream = null!; - protected readonly dateLocale:DateLocales = "it-IT"; - protected readonly primaryColor:LogColors = "cyan"; - constructor(data?:LoggerConstructor) { - if (data?.logFilePath) this.fileStream = createWriteStream(data.logFilePath, { flags: 'a' }); - if (data?.debug) this.isDebug = data.debug; - if (data?.locale) this.dateLocale = data.locale; - if (data?.primaryColor) this.primaryColor = data.primaryColor; - } - - - protected readonly dateOptions: Intl.DateTimeFormatOptions | undefined = { day: '2-digit', month: '2-digit', year: 'numeric' }; - protected readonly timeOptions: Intl.DateTimeFormatOptions | undefined = { hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false } - public readonly colors = { - red: "\x1b[31m%s\x1b[0m", - green: "\x1b[32m%s\x1b[0m", - yellow: "\x1b[33m%s\x1b[0m", - blue: "\x1b[34m%s\x1b[0m", - magenta: "\x1b[35m%s\x1b[0m", - cyan: "\x1b[36m%s\x1b[0m", - gray: "\x1b[90m%s\x1b[0m" - } - - - - getDateTimeString = () => { - const dateObj = new Date(); - return `[${dateObj.toLocaleDateString(this.dateLocale, this.dateOptions)} ${dateObj.toLocaleTimeString(this.dateLocale, this.timeOptions)}] `; - } - - log = (message:any, color:LogColors) => { - if (!this.isDebug) return; - - const dateString = this.getDateTimeString(); - if (!color) console.log(dateString, message); - else { - if (typeof message === "object") console.log(this.colors[color], `${dateString}${JSON.stringify(message, null, 2)}`); - else console.log(this.colors[color], `${dateString}${message}`); - } - } - - logColor = (coloredMessage:any, ...messages:any[]) => { - if (!this.isDebug) return; - - this.log(coloredMessage, this.primaryColor); - for (let i = 0; i < messages.length; i++) { - this.logDetail(messages[i]); - } - } - - - logDetail = (...messages:any[]) => { - if (!this.isDebug) return; - - for (const message of messages) { - if (typeof message === "object") console.log(this.colors["gray"], JSON.stringify(message, null, 2)); - else console.log(this.colors["gray"], `${message}`); - } - } - - - logError = (...errs:any) => { - if (!this.isDebug) return; - - let errorMessage:string = null!; - let stackTrace:string = null!; - - for(const err of errs) { - if (err.message) errorMessage = err.message; - if (err.stack) stackTrace = err.stack.split("\n")[1]; - - if (!errorMessage) this.log(err, "red"); - else { - this.log(errorMessage, "red") - if (stackTrace) console.log(this.colors["gray"], stackTrace) - } - } - } - - - - logFile = (message:string, type:"log" | "error" = "log", isClosing:boolean = true) => { - if (!this.fileStream) return this.log("LOGFILE: Specify filepath destination in class constructor or function parameter", "red"); - - const dateObj = new Date(); - const date = this.getDateTimeString().trim(); - const logType = type === "log" ? " LOG" : "ERROR" - this.fileStream.write(`${date}\t\t${logType}: ${message}\n`); - if (isClosing) this.fileStream.close(); - } -} diff --git a/package/src/index.ts b/package/src/index.ts index 247f54e..e0ad925 100644 --- a/package/src/index.ts +++ b/package/src/index.ts @@ -1,6 +1,4 @@ export * from "../types/generic.types" -export * from "../types/generic.types" import GenericUtils from "./GenericUtils"; -import ClientFilters from "./ClientFilters"; -export { GenericUtils, ClientFilters }; +export { GenericUtils }; diff --git a/package/types/generic.types.ts b/package/types/generic.types.ts index ee4073c..e875448 100644 --- a/package/types/generic.types.ts +++ b/package/types/generic.types.ts @@ -1,5 +1,3 @@ -import { DateLocales } from "./locales.types" - // --- Generic Utils export interface GenericObject { [Key:string]: GenericType } @@ -10,18 +8,24 @@ export interface CatchedResponse { isOk:boolean, response: T | null, error?:s export interface PaginatedParams{ currentPage:number, quantity:number, filter?:T } export interface PaginatedResponse{ totalPages:number, data:T } -export type SelectOptions = { id:Key, text:Val } - - - +export type SelectOption = { id:Key, text:Val } -// --- Logger -export type LogColors = "red" | "green" | "yellow" | "blue" | "magenta" | "cyan" | "gray" | null +export type ArrayDifference = { removed:T[], added:T[], same:T[] } -export interface LoggerConstructor { logFilePath?:string, debug?:boolean, locale?: DateLocales, primaryColor?:LogColors } +export interface GenericUtilsConstructor { + locale?:DateLocales, + numericValidation?:RegExp +} -// --- Custom Navigation -export type ClientFilterTypes = string | number | Date | boolean | Array | undefined -export interface ClientFilter { [Key:string]: ClientFilterTypes } +// --- Locales +export type DateLocales = + | "en-US" + | "en-GB" + | "fr-FR" + | "de-DE" + | "it-IT" + | "es-ES" + | "ja-JP" + | "zh-CN"; diff --git a/package/types/locales.types.ts b/package/types/locales.types.ts deleted file mode 100644 index 01eb10a..0000000 --- a/package/types/locales.types.ts +++ /dev/null @@ -1,9 +0,0 @@ -export type DateLocales = - | "en-US" - | "en-GB" - | "fr-FR" - | "de-DE" - | "it-IT" - | "es-ES" - | "ja-JP" - | "zh-CN"; diff --git a/test/test.ts b/test/test.ts index 8700029..78b0740 100644 --- a/test/test.ts +++ b/test/test.ts @@ -1,41 +1,31 @@ -import { ClientFilters, CatchedResponse, ClientFilter } from "utils-stuff" +import { CatchedResponse } from "utils-stuff" import gu from "./utils"; - -// --- Logger - -gu.log("Hello there, this is a log" + " " + gu.parseDate(), "blue"); -gu.logFile("Hello there", "log", false); -gu.logFile("An Error", "error"); - - -const functionResult = (function testCatch():CatchedResponse { - try { throw new Error("Test"); } - catch(err) { return gu.catchResError(err); } -})() -gu.logColor("Test Catch", functionResult); - -gu.logColor("Another test", { test: 1, test2: true, prova: { test3: [ "Hello", 2, false] } }, false, 12.3); -gu.logError("An incredible error", functionResult) - - - - - - -// --- Filter - -interface ExampleFilter extends ClientFilter { startDate:Date, endDate:Date, type:number, active?:boolean } -const filter = new ClientFilters({ - startDate: new Date(), - endDate: new Date(), - type: 2, -}); - -filter.values.active = true; -gu.logColor(filter.currentParams); - - -filter.values.active = undefined; -filter.values.startDate = new Date("5/30/2024 15:00") -gu.logColor(filter.currentParams); +const dateNow = gu.parseDate(); +const isStrValid = gu.isStringValid(""); +const arrayDifference = gu.arrayDiff([0,1,5], [3,5,6]) +const isNumericTrue = gu.isNumeric("143.56"); +const isNumericFalse = gu.isNumeric("12,3"); +const isNumericFalse2 = gu.isNumeric("Not a number"); +const isNumericFalse3 = gu.isNumeric("-13"); + +const testCatchGood = (function testCatchGood():CatchedResponse { + try { return gu.resOk("Response string"); } + catch(err) { return gu.resError(err); } +})(); +const testCatchResponse = (function testCatch():CatchedResponse { + try { throw new Error("Error Message"); } + catch(err) { return gu.resError(err); } +})(); + + +console.log(dateNow) +console.log(isStrValid) +console.log(arrayDifference) +console.log(isNumericTrue) +console.log(isNumericFalse) +console.log(isNumericFalse2) +console.log(isNumericFalse3) + +console.log(testCatchGood); +console.log(testCatchResponse); diff --git a/test/utils.ts b/test/utils.ts index ef4ca1d..d9b2e32 100644 --- a/test/utils.ts +++ b/test/utils.ts @@ -10,7 +10,4 @@ class MyGenericUtils extends GenericUtils { } } -export default new MyGenericUtils({ - debug:true, - logFilePath: "../files/logs.txt" -}); +export default new MyGenericUtils({ locale:"it-IT" });