@mjamsek/prog-utils v0.3.3
Prog Utils
Utility library providing type definitions.
Installation
Run command: npm install --save @mjamsek/prog-utils
Documentation
EntityList
EntityList is a wrapper object for lists. It is used to group list with its metadata (size, offset & limit).
Example:
import { EntityList } from "@mjamsek/prog-utils";
const objectArray: MyObject[] = [/* ... */];
/*
* Provide list size separately.
* Useful to store information usually retrieved from
* X-Total-Count header, to represent size of larger collection.
*/
const list: EntityList<MyObject> = EntityList.of(objectList, 23);
/*
* If size is not provided, it defaults to size of given array.
*/
const list: EntityList<MyObject> = EntityList.of(objectList);
/*
* Additionally, you can also provide limit and offset values.
*/
const list: EntityList<MyObject> = EntityList.of(objectList, 23, /*limit: */ 10, /*offset: */ 0);
/*
* Creates empty list, with size 0
*/
const list: EntityList<MyObject> = EntityList.empty();When using Typescript, we can take advantage of generics, to specify type of entities contained in list.
Optional
This type is ported from Java SE platform and has the same behaviour. It is used to wrap values that can be null or undefined, to enable easier handling of such values.
Creating optional:
import { Optional } from "@mjamsek/prog-utils";
const noValue = Optional.empty();
const stringValue: Optional<string> = Optional.of("value");
const unknownValue = Optional.ofNullable(nullableVariable);Additionally, Optional<T> exposes following methods:
get(): TReturns value if present, otherwise throws error.isPresent(): booleanReturns true if value is present, false otherwise.ifPresent(func: Optional.ConsumerFunction<T>): voidExecutes given function if value is present.ifPresentOrElse(func: Optional.ConsumerFunction<T>, emptyFunc: Optional.EmptyFunction): voidExecutes first function if value is present, otherwise executes second function.filter(predicate: Optional.PredicateFunction<T>): Optional<T>Executes filter function. If value matches result, it returns itself, otherwise returns empty Optional.map<U>(func: Optional.MapFunction<T, U>): Optional<U>Maps value to another type, using given function.or(func: Optional.SupplierFunction<T>): Optional<T>If value is present, returns itself, otherwise returns new Optional with different value of same type.orElse(other: T): TIf value is present, returns value, otherwise returns specified value.orElseThrow<E extends Error>(supplier?: Optional.ExceptionSupplierFunction<E>): TThrows error if value is not present.flatMap(mapper: Optional.MapFunction<T, Optional<T>>): Optional<T>If value is present, returns result of mapper function, otherwise it returns empty Optional.
Opt
Sometimes using Optional would be impractical, therefore Opt is provided, to denote a variable may be of type T or null.
Utils
Utility functions that are provided by library:
getDayOfWeekReturns day of week with monday as 0 indexresetTimeTrims time from date (sets all parts to 0). DEPRECATED: usetruncateTimeinstead.truncateTimeTruncates time from date (sets all parts to 0).getDateDaysAfterReturns date x days after given dategetDateDaysBeforeReturns date x days before given datedaysDiffBetweenDatesReturns difference between two dates in daysstringIsIntegerChecks if string contains integer. DEPRECATED: useisIntegerinstead.isNumberChecks whether given value is a number typeisIntegerChecks if number is integerisFloatChecks if number is floatisUUID: Validates whether given string is of UUID-like format.
Typescript definitions
Additional definitions for Typescript types:
Without<T, U>Resulting type can only contain properties of typeT, but not of typeU.XOR<T, U>Resulting type can only contain properties of one or the other type, but not both.
And for function types:
VoidFuncFunction that doesn't accept nor return any value.BasicConsumer<T>Function that consumes value of typeTand returns nothing.BiConsumer<T1, T2>Function that consumes two values of typeT1andT2and returns nothing.BasicSupplier<T>Function that produces (returns) value of typeT.BasicMutator<T>Function that maps value of typeTto another value of typeT.BasicMapper<O, R>Function that maps value of typeOto value of typeR.
Errors
Library provides typed error definitions for easier dealing with multiple errors. You can define your own errors, by extending BaseError like this:
import { BaseError } from "@mjamsek/prog-utils";
export class MyNewError extends BaseError {
private readonly _myField: number;
constructor(message: string, myField: number, cause?: Error) {
super(message, MyNewError, cause);
this._myField = myField;
}
public get myField(): number {
return this._myField;
}
}Additionally, some typed errors are already provided by library:
HttpErrorError representing failure during HTTP call.UnknownErrorWhen error cannot be mapped to instance ofBaseError, you can map toUnknownError.
HTTP Helpers
HTTP Headers
Following header constants are provided:
X_SERVICE_NAME: x-service-nameX_SERVICE_VERSION: x-service-versionX_SERVICE_ENV: x-service-envX_REQUEST_ID: x-request-idX_TOTAL_COUNT: x-total-countX_LIMIT: x-limitX_OFFSET: x-offsetCONTENT_DISPOSITION: content-dispositionAUTHORIZATION: authorizationX_POWERED_BY: x-powered-by
HTTP Statuses
Following status constants are provided:
OK: 200,CREATED: 201,ACCEPTED: 202,NO_CONTENT: 204,BAD_REQUEST: 400,UNAUTHORIZED: 401,FORBIDDEN: 403,NOT_FOUND: 404,METHOD_NOT_ALLOWED: 405,CONFLICT: 409,GONE: 410,UNSUPPORTED_MEDIA_TYPE: 415,UNPROCESSABLE_ENTITY: 422,VALIDATION_FAILED: 422,INTERNAL_SERVER_ERROR: 500,SERVICE_UNAVAILABLE: 503,
Bugs & Features
Any issues, requests for a new feature, etc. can be filled using GitHub Issues.
License
MIT