@vladbasin/ts-services
v1.0.3
Published
Useful cross-cutting functionality services
Downloads
10
Maintainers
Readme
ts-services
Usefull services for cross-cutting functionality
Install
npm install @vladbasin/ts-services --save
Getting Started
Usage
Services can be imported as class and constructed by yourself or you can use @vladbasin/ts-dependencies
and @vladbasin/ts-dependencies-reactjs
libraries
import { addServices } from "@vladbasin/ts-services";
addServices(serviceCollectionBuilder);
Then resolve
import { ServiceIds } from "@vladbasin/ts-services";
const eventAggregator = useService<EventAggregatorContract>(ServiceIds.eventAggregator);
Services
- EventAggregator (publish\subscribe)
/**
* Emits event and waits for subscribers to handle it
* @param event Event name
* @param arg Argument to pass into event
* @returns Result which can be awaited untill subscribers complete their duties
*/
emitAwaitingSubscribersAsync<T extends any>(event: string, arg?: T) : Result<void>
/**
* Emits event
* @param event Event name
* @param arg Argument to pass into event
*/
emit<T extends any>(event: string, arg?: T)
/**
* Emits event optinally awaiting subscribers to complete duties
* @param event Event name
* @param awaitSubscribers Should we wait for subscribers
* @param arg Argument to pass into event
* @returns Result which can be awaited untill subscribers complete their duties
*/
emitAsync<T extends any>(event: string, awaitSubscribers: boolean, arg?: T): Result<void>
/**
* Subscribes to event once waiting for it to occur
* @param event Event name
* @param timeout Timeout for waiting for event to occur
* @returns Result which can be awaited untill event is processed
*/
subscribeOnceAwaitingAsync(event: string, timeout: number): Result<any>
/**
* Subscribe to event
* @param event Event name
* @param action Action to execute
* @returns Id of subscriber
*/
subscribe(event: string, action: SubscriberActionType): string
/**
* Unsubscribe from event
* @param subscriberId Id of subscriber
*/
unsubscribe(subscriberId: string)
- DateFormatter
/**
* Formats local value of the date from now (e.g. 4 years ago)
* @param date Date to format
* @returns String which represents the date
*/
fromNow(date: Moment): Maybe<string>
/**
* Formats local value of the date as in calendar (e.g. Tomorrow at 2:30 AM)
* @param date Date to format
* @returns String which represents the date
*/
calendar(date: Date): Maybe<string>
/**
* Formats local date by given pattern
* @param date Date to format
* @param formatString Format pattern
* @returns Formatted string or undefined if date is not defined
*/
formatLocalized(date: Date, formatString: string): Maybe<string>
/**
* Formats local date by given pattern
* @param date Date to format
* @param formatString Format pattern
* @returns Formatted string or undefined if date is not defined
*/
format(date: Maybe<Date>, formatString: string): Maybe<string>
- Monitor
/**
* Locks execution by given key
* @param key Key to lock
*/
lock(key: string)
/**
* Unlocks execution by given key
* @param key Key to unlock
*/
unlock(key: string)
/**
* Wait untill key is unlocked
* @param key Key to wait
* @returns Result which can be awaited untill key is unlocked
*/
continueWhenUnlockedAsync(key: string): Result<void>
/**
* Lock the key and wait untill key is unlocked
* @param key Key to wait
* @returns Result which can be awaited untill key is unlocked
*/
continueWhenUnlockedAndLockAsync(key: string): Result<void>
- UniqueIdProvider
/**
* Generates unique id
* @returns Unique id
*/
provide(): string
Extensions
Array extensions:
interface Array<T> {
/**
* Search items by multiple predicates
* @param predicates Predicate items must comply with
* @returns New array with found items
*/
search(predicates: SearchPredicateType<T>[]): Result<T>;
/**
* Filters out all duplicates
* @param keyProvider Provides unique key which corresponds to each item in array
* @returns New array with unique items
*/
distinct(keyProvider: (item: T) => string): Array<T>;
/**
* Finds n-th item in array
* @param index Index in array
* @returns Found value or undefined
*/
findNth(index: number): Maybe<T>;
/**
* Looks for the first item which complies predicate
* @param predicate Predicate to comply
* @param selector Transform found item
* @returns Found and tranformed value or undefined
*/
findFirst<K>(predicate: (arg: T) => boolean): Maybe<K>;
/**
* Same as map() but removing values which are not defined (null or undefined)
* @param mapper Maps items
* @param checkForUndefinedOnly Allow null values
*/
compactMap<K>(mapper: (arg: T) => K | undefined, checkForUndefinedOnly?: boolean): K[];
/**
* Takes the required number of first items from array
* @param count Required number of items
* @returns New array with required items
*/
take(count: number): T[];
/**
* Ensures that array has exact length
* @param size Required length of array
* @param generator Function that fills missing indexes if any
* @returns New array with required size
*/
ensureSize(size: number, generator: (arg: number) => T): T[];
/**
* Same as map() but each item might return an array
* @param mapper Mapper for each item
* @returns New mapped array
*/
mapMany<K>(mapper: (arg: T) => K[]): K[];
/**
* Swaps items
* @param first First index
* @param second Second index
* @result Same array with swapped items
*/
swap(first: number, second: number): T[];
/**
* Converts array to Map
* @param keySelector Selects the key for items
* @returns Map from selected keys and array values
*/
toMap(keySelector: (arg: T) => string): Map<string, T>;
/**
* Find last item which complies predicate
* @param predicate Predicate to comply
* @returns Found item or undefined
*/
findLast(predicate?: (arg: T) => boolean): Maybe<T>;
/**
* Go from the last to the first item and find item which complies predicate
* @param predicate Predicate to comply
* @returns Found item or undefined
*/
findFirstReversed(predicate?: (arg: T) => boolean): Maybe<T>;
}
interface ArrayConstructor {
/**
* Creates a new array with generated values
* @param length Array length
* @param valueFactory Function which generates items
* @returns New array with generated values
*/
create<T>(length: number, valueFactory: (index: number) => T): Array<T>;
}
Map extensions
interface Map<K, V> {
/**
* Checks whether map contains element or not
* @param predicate Predicate to check
* @returns True in case contains
*/
contains(predicate: (key: K, value: V) => boolean): boolean;
/**
* Finds element in map
* @param predicate Predicate to comply with
* @returns Element or undefined
*/
find(predicate: (key: K, value: V) => boolean): Maybe<V>;
}
String extensions
interface String {
/**
* Checks whether string is trimmed
* @returns Is string trimmed
*/
isTrimmed(): boolean;
/**
* Ensures first letter is capitalized
* @returns New string with capitalized first letter
*/
ensureFirstCapitalized(): string;
/**
* Ensures string ends with given string
* @param target Given string to end with
* @returns Same string if contains target at the end or new string with target at the end
*/
ensureEndsWith(target: string): string;
/**
* Ensures string starts with given string
* @param target Given string to start with
* @returns Same string if contains target at the start or new string with target at the start
*/
ensureStartsWith(target: string): string;
/**
* Gets all lowercased words in string
* @returns Array of lowercased words
*/
getAllWordsLowerCased(): string[];
/**
* Replaces regex pattern in string
* @param pattern Pattern to match
* @param replacement Replace string
* @returns String with replaced occurencies
*/
replaceRegex(pattern: string, replacement: string): string;
/**
* Tries to extract file name with extension assuming that current string is URL
* @returns File name with extension or undefined
*/
asUrlExtractFileName(): string | undefined;
/**
* Tries to extract file extension assuming that current string is URL
* @returns File extension or undefined
*/
asUrlExtractFileExtension(): Maybe<string>;
/**
* Tries to extract file name without extension assuming that current string is URL
* @returns File name without extension or undefined
*/
asUrlExtractFileNameWithoutExtension(): string | undefined;
/**
* Escapes file system path for special symbols with symbol
* @param symbol Symbol to use to replace string
* @returns Escaped string
*/
escapeForFileSystemPath(symbol: string): string;
/**
* Split string by separator and returns required chunk
* @param separator Separator for splitting
* @param chunkIndex Index of required chunk
* @returns Chunk value or undefined
*/
extractChunkBySplitting(separator: string, chunkIndex: number): string | undefined;
/**
* Trims start of the string removing target
* @param target Target to remove from the start
* @returns Trimmed string
*/
trimStartFor(target: string): string,
/**
* Trims end of the string removing target
* @param target Target to remove from the end
* @returns Trimmed string
*/
trimEndFor(target: string): string,
/**
* Maps string to another string
* @param selector Takes current character and returns new or undefined to ignore
* @returns Mapped string
*/
compactMap(selector: (currentChar: string, prevChar?: string) => Maybe<string>): string,
/**
* Ensures max length of the string
* @param maxLength Allowed length
* @returns Same string if allowed length or shortened string
*/
ensureMaxLength(maxLength: number): string,
}