diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index b7e8304..c27663c 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -12,7 +12,7 @@ jobs: steps: - uses: actions/checkout@v2 with: - fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis + fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis - name: Use Node.js uses: actions/setup-node@v1 with: @@ -21,4 +21,4 @@ jobs: - run: npm run lint - run: npm test env: - CI: true \ No newline at end of file + CI: true diff --git a/run b/run index 3e54f3a..6c3ae40 100644 --- a/run +++ b/run @@ -12,5 +12,5 @@ require(`${__dirname}/node_modules/@villedemontreal/scripting/dist/src/run`).run caporal, projectRoot: __dirname, scriptsIndexModule: `./scripts/index`, - testsLocations: [`./dist/src/**/*.test.js`] + testsLocations: [`./dist/src/**/*.test.js`], }); diff --git a/src/apiError.test.ts b/src/apiError.test.ts index b767d37..28a09e2 100644 --- a/src/apiError.test.ts +++ b/src/apiError.test.ts @@ -10,7 +10,7 @@ import { createNotImplementedError, createServerError, createUnauthorizedError, - createUnprocessableEntityError + createUnprocessableEntityError, } from './apiErrorBuilder'; import { globalConstants } from './config/globalConstants'; import { LogLevel } from './logLevel'; @@ -29,7 +29,10 @@ describe('API errors', () => { assert.strictEqual(error.logLevel, LogLevel.ERROR); assert.strictEqual(error.logMessage, 'myLogMessage'); assert.strictEqual(error.logStackTrace, true); - assert.strictEqual(error.error.code, globalConstants.errors.apiGeneralErrors.codes.GENERIC_ERROR); + assert.strictEqual( + error.error.code, + globalConstants.errors.apiGeneralErrors.codes.GENERIC_ERROR, + ); assert.strictEqual(error.error.message, 'Server error'); }); @@ -39,7 +42,10 @@ describe('API errors', () => { assert.strictEqual(error.logLevel, LogLevel.ERROR); assert.strictEqual(error.logMessage, 'myLogMessage'); assert.strictEqual(error.logStackTrace, true); - assert.strictEqual(error.error.code, globalConstants.errors.apiGeneralErrors.codes.GENERIC_ERROR); + assert.strictEqual( + error.error.code, + globalConstants.errors.apiGeneralErrors.codes.GENERIC_ERROR, + ); assert.strictEqual(error.error.message, 'myPublicMessage'); }); @@ -69,7 +75,10 @@ describe('API errors', () => { assert.strictEqual(error.logLevel, LogLevel.DEBUG); assert.strictEqual(error.logMessage, 'myPublicMessage'); assert.strictEqual(error.logStackTrace, false); - assert.strictEqual(error.error.code, globalConstants.errors.apiGeneralErrors.codes.INVALID_PARAMETER); + assert.strictEqual( + error.error.code, + globalConstants.errors.apiGeneralErrors.codes.INVALID_PARAMETER, + ); assert.strictEqual(error.error.message, 'myPublicMessage'); assert.isTrue(error.error.details === undefined || error.error.details.length === 0); }); @@ -78,12 +87,12 @@ describe('API errors', () => { const details: IApiError[] = [ { code: 'myDetailCode1', - message: 'myDetailMessage1' + message: 'myDetailMessage1', }, { code: 'myDetailCode2', - message: 'myDetailMessage2' - } + message: 'myDetailMessage2', + }, ]; const error = createInvalidParameterError('myPublicMessage', details, LogLevel.INFO, true); @@ -91,7 +100,10 @@ describe('API errors', () => { assert.strictEqual(error.logLevel, LogLevel.INFO); assert.strictEqual(error.logMessage, 'myPublicMessage'); assert.strictEqual(error.logStackTrace, true); - assert.strictEqual(error.error.code, globalConstants.errors.apiGeneralErrors.codes.INVALID_PARAMETER); + assert.strictEqual( + error.error.code, + globalConstants.errors.apiGeneralErrors.codes.INVALID_PARAMETER, + ); assert.strictEqual(error.error.message, 'myPublicMessage'); assert.strictEqual(error.error.details.length, 2); assert.strictEqual(error.error.details[0].code, 'myDetailCode1'); @@ -106,7 +118,10 @@ describe('API errors', () => { assert.strictEqual(error.logLevel, LogLevel.DEBUG); assert.strictEqual(error.logMessage, 'myPublicMessage'); assert.strictEqual(error.logStackTrace, false); - assert.strictEqual(error.error.code, globalConstants.errors.apiGeneralErrors.codes.UNPROCESSABLE_ENTITY); + assert.strictEqual( + error.error.code, + globalConstants.errors.apiGeneralErrors.codes.UNPROCESSABLE_ENTITY, + ); assert.strictEqual(error.error.message, 'myPublicMessage'); assert.isTrue(error.error.details === undefined || error.error.details.length === 0); }); @@ -116,12 +131,12 @@ describe('API errors', () => { { code: 'myDetailCode1', message: 'myDetailMessage1', - target: 'aJsonPath' + target: 'aJsonPath', }, { code: 'myDetailCode2', - message: 'myDetailMessage2' - } + message: 'myDetailMessage2', + }, ]; const error = createUnprocessableEntityError('myPublicMessage', details, LogLevel.INFO, true); @@ -129,7 +144,10 @@ describe('API errors', () => { assert.strictEqual(error.logLevel, LogLevel.INFO); assert.strictEqual(error.logMessage, 'myPublicMessage'); assert.strictEqual(error.logStackTrace, true); - assert.strictEqual(error.error.code, globalConstants.errors.apiGeneralErrors.codes.UNPROCESSABLE_ENTITY); + assert.strictEqual( + error.error.code, + globalConstants.errors.apiGeneralErrors.codes.UNPROCESSABLE_ENTITY, + ); assert.strictEqual(error.error.message, 'myPublicMessage'); assert.strictEqual(error.error.details.length, 2); assert.strictEqual(error.error.details[0].code, 'myDetailCode1'); @@ -144,7 +162,10 @@ describe('API errors', () => { assert.strictEqual(error.logLevel, LogLevel.INFO); assert.strictEqual(error.logMessage, 'Not implemented'); assert.strictEqual(error.logStackTrace, false); - assert.strictEqual(error.error.code, globalConstants.errors.apiGeneralErrors.codes.NOT_IMPLEMENTED); + assert.strictEqual( + error.error.code, + globalConstants.errors.apiGeneralErrors.codes.NOT_IMPLEMENTED, + ); assert.strictEqual(error.error.message, 'Not implemented yet'); }); @@ -154,7 +175,10 @@ describe('API errors', () => { assert.strictEqual(error.logLevel, LogLevel.INFO); assert.strictEqual(error.logMessage, 'myLogMessage'); assert.strictEqual(error.logStackTrace, false); - assert.strictEqual(error.error.code, globalConstants.errors.apiGeneralErrors.codes.NOT_IMPLEMENTED); + assert.strictEqual( + error.error.code, + globalConstants.errors.apiGeneralErrors.codes.NOT_IMPLEMENTED, + ); assert.strictEqual(error.error.message, 'myPublicMessage'); }); @@ -164,7 +188,10 @@ describe('API errors', () => { assert.strictEqual(error.logLevel, LogLevel.INFO); assert.strictEqual(error.logMessage, 'Unauthorized'); assert.strictEqual(error.logStackTrace, false); - assert.strictEqual(error.error.code, globalConstants.errors.apiGeneralErrors.codes.UNAUTHORIZED); + assert.strictEqual( + error.error.code, + globalConstants.errors.apiGeneralErrors.codes.UNAUTHORIZED, + ); assert.strictEqual(error.error.message, 'Please authenticate yourself first.'); }); @@ -174,7 +201,10 @@ describe('API errors', () => { assert.strictEqual(error.logLevel, LogLevel.INFO); assert.strictEqual(error.logMessage, 'myLogMessage'); assert.strictEqual(error.logStackTrace, false); - assert.strictEqual(error.error.code, globalConstants.errors.apiGeneralErrors.codes.UNAUTHORIZED); + assert.strictEqual( + error.error.code, + globalConstants.errors.apiGeneralErrors.codes.UNAUTHORIZED, + ); assert.strictEqual(error.error.message, 'myPublicMessage'); }); @@ -207,18 +237,18 @@ describe('API errors', () => { for (const value of [ { code: 'some code', - message: 'some message' + message: 'some message', }, { code: 'some code', message: 'some message', - details: [] + details: [], }, { code: 'some code', message: 'some message', - target: 'target' - } + target: 'target', + }, ] as any) { assert.isTrue(isApiError(value)); } @@ -227,15 +257,15 @@ describe('API errors', () => { it('is not an ApiError', async () => { for (const value of [ { - code: 'some code' + code: 'some code', }, { - message: 'some message' + message: 'some message', }, { code: 'some code', message: 'some message', - nope: 'nope' + nope: 'nope', }, { code: 'some code', @@ -243,10 +273,10 @@ describe('API errors', () => { target: 'target', details: [], innererror: { - code: 'some code' + code: 'some code', }, - nope: 123 - } + nope: 123, + }, ] as any) { assert.isFalse(isApiError(value)); } diff --git a/src/apiError.ts b/src/apiError.ts index 37a8dc8..f010f30 100644 --- a/src/apiError.ts +++ b/src/apiError.ts @@ -32,7 +32,7 @@ export interface IErrorResponse { /** * Error Reponse Type Guard */ -export let isErrorResponse = (obj: any): obj is IErrorResponse => { +export const isErrorResponse = (obj: any): obj is IErrorResponse => { return obj && utils.isObjectStrict(obj) && 'error' in obj && isApiError(obj.error); }; @@ -70,7 +70,7 @@ export interface IApiError { /** * Error Type Guard */ -export let isApiError = (obj: any): obj is IApiError => { +export const isApiError = (obj: any): obj is IApiError => { if (!obj || !utils.isObjectStrict(obj) || !('code' in obj) || !('message' in obj)) { return false; } @@ -147,7 +147,7 @@ export interface IApiErrorAndInfo { /** * IApiErrorAndInfo Type Guard */ -export let isApiErrorAndInfo = (obj: any): obj is IApiErrorAndInfo => { +export const isApiErrorAndInfo = (obj: any): obj is IApiErrorAndInfo => { return ( obj && utils.isObjectStrict(obj) && @@ -171,7 +171,7 @@ export class ApiErrorAndInfo extends Error implements IApiErrorAndInfo { public logMessage: any, public httpStatus: number, public logLevel: LogLevel, - public logStackTrace: boolean + public logStackTrace: boolean, ) { super( ((): string => { @@ -180,7 +180,7 @@ export class ApiErrorAndInfo extends Error implements IApiErrorAndInfo { } return (logMessage as any).msg || (logMessage as any).message || ''; - })() + })(), ); } } diff --git a/src/apiErrorBuilder.ts b/src/apiErrorBuilder.ts index f390999..53ed443 100644 --- a/src/apiErrorBuilder.ts +++ b/src/apiErrorBuilder.ts @@ -89,7 +89,7 @@ export class ErrorBuilder { public build = (): ApiErrorAndInfo => { const error: IApiError = { code: this._code, - message: this._publicMessage || 'An error occured' + message: this._publicMessage || 'An error occured', }; if (this._target !== undefined) { @@ -109,7 +109,7 @@ export class ErrorBuilder { this._logMessage, this._httpStatus || HttpStatusCodes.INTERNAL_SERVER_ERROR, this._logLevel !== undefined ? this._logLevel : LogLevel.ERROR, - this._logStackTrace !== undefined ? this._logStackTrace : true + this._logStackTrace !== undefined ? this._logStackTrace : true, ); return errorAndInfo; @@ -119,7 +119,7 @@ export class ErrorBuilder { /** * ErrorBuilder Type Guard */ -export let isErrorBuilder = (obj: any): obj is ErrorBuilder => { +export const isErrorBuilder = (obj: any): obj is ErrorBuilder => { return obj && obj.addDetail !== undefined && obj.build !== undefined; }; @@ -136,7 +136,10 @@ export function createError(code: string, logMessage: any): ErrorBuilder { * * The log message is mandatory. */ -export function createServerError(logMessage: any, publicMessage: string = 'Server error'): ApiErrorAndInfo { +export function createServerError( + logMessage: any, + publicMessage = 'Server error', +): ApiErrorAndInfo { return createError(globalConstants.errors.apiGeneralErrors.codes.GENERIC_ERROR, logMessage) .httpStatus(HttpStatusCodes.INTERNAL_SERVER_ERROR) .publicMessage(publicMessage) @@ -155,9 +158,9 @@ export function createServerError(logMessage: any, publicMessage: string = 'Serv */ export function createNotFoundError( logMessage: any, - publicMessage: string = 'Not Found', + publicMessage = 'Not Found', logLevel: LogLevel = LogLevel.DEBUG, - logStackTrace: boolean = false + logStackTrace = false, ): ApiErrorAndInfo { return createError(globalConstants.errors.apiGeneralErrors.codes.NOT_FOUND, logMessage) .httpStatus(HttpStatusCodes.NOT_FOUND) @@ -179,7 +182,7 @@ export function createInvalidParameterError( publicMessage: string, details: IApiError[] = [], logLevel: LogLevel = LogLevel.DEBUG, - logStackTrace: boolean = false + logStackTrace = false, ): ApiErrorAndInfo { return createError(globalConstants.errors.apiGeneralErrors.codes.INVALID_PARAMETER, publicMessage) .httpStatus(HttpStatusCodes.BAD_REQUEST) @@ -202,9 +205,12 @@ export function createUnprocessableEntityError( publicMessage: string, details: IApiError[] = [], logLevel: LogLevel = LogLevel.DEBUG, - logStackTrace: boolean = false + logStackTrace = false, ): ApiErrorAndInfo { - return createError(globalConstants.errors.apiGeneralErrors.codes.UNPROCESSABLE_ENTITY, publicMessage) + return createError( + globalConstants.errors.apiGeneralErrors.codes.UNPROCESSABLE_ENTITY, + publicMessage, + ) .httpStatus(HttpStatusCodes.UNPROCESSABLE_ENTITY) .publicMessage(publicMessage) .details(details) @@ -218,7 +224,7 @@ export function createUnprocessableEntityError( */ export function createNotImplementedError( logMessage: any = 'Not implemented', - publicMessage: string = 'Not implemented yet' + publicMessage = 'Not implemented yet', ) { return createError(globalConstants.errors.apiGeneralErrors.codes.NOT_IMPLEMENTED, logMessage) .publicMessage(publicMessage) @@ -234,7 +240,7 @@ export function createNotImplementedError( */ export function createUnauthorizedError( logMessage: any = 'Unauthorized', - publicMessage: string = 'Please authenticate yourself first.' + publicMessage = 'Please authenticate yourself first.', ) { return createError(globalConstants.errors.apiGeneralErrors.codes.UNAUTHORIZED, logMessage) .publicMessage(publicMessage) @@ -249,7 +255,10 @@ export function createUnauthorizedError( * the user is authenticated but doesn't have sufficient * rights to access the requested resource. */ -export function createForbiddenError(logMessage: any = 'Forbidden', publicMessage: string = 'Access denied.') { +export function createForbiddenError( + logMessage: any = 'Forbidden', + publicMessage = 'Access denied.', +) { return createError(globalConstants.errors.apiGeneralErrors.codes.FORBIDDEN, logMessage) .publicMessage(publicMessage) .httpStatus(HttpStatusCodes.FORBIDDEN) diff --git a/src/collectionUtils.test.ts b/src/collectionUtils.test.ts index 0fc23fa..472a283 100644 --- a/src/collectionUtils.test.ts +++ b/src/collectionUtils.test.ts @@ -10,7 +10,7 @@ import { isMatching, removeEmptyValues, removeMissingValues, - toDictionary + toDictionary, } from './collectionUtils'; export const EMPTY_STRING = ''; @@ -29,7 +29,15 @@ Object.freeze(EMPTY_MAP); const EMPTY_SET = new Set(); Object.freeze(EMPTY_SET); -export const EMPTY_VALUES = [undefined, null, EMPTY_STRING, EMPTY_ARRAY, EMPTY_OBJECT, EMPTY_MAP, EMPTY_SET]; +export const EMPTY_VALUES = [ + undefined, + null, + EMPTY_STRING, + EMPTY_ARRAY, + EMPTY_OBJECT, + EMPTY_MAP, + EMPTY_SET, +]; Object.freeze(EMPTY_VALUES); const EMPTY_VALUES_MAP = toDictionary(EMPTY_VALUES, getValueDescriptionWithType); @@ -58,7 +66,7 @@ export const NOT_EMPTY_VALUES = [ new Error(), Number(123), NOT_EMPTY_MAP, - NOT_EMPTY_SET + NOT_EMPTY_SET, ]; Object.freeze(NOT_EMPTY_VALUES); @@ -73,12 +81,12 @@ Object.freeze(NOT_MISSING_VALUES_MAP); describe('Collection Utility', () => { describe('#isEmpty', () => { - EMPTY_VALUES.forEach(value => { + EMPTY_VALUES.forEach((value) => { it(`should return \`true\` for ${getValueDescriptionWithType(value)}`, () => { assert.isTrue(isEmpty(value)); }); }); - NOT_EMPTY_VALUES.forEach(value => { + NOT_EMPTY_VALUES.forEach((value) => { it(`should return \`false\` for ${getValueDescriptionWithType(value)}`, () => { assert.isFalse(isEmpty(value)); }); diff --git a/src/collectionUtils.ts b/src/collectionUtils.ts index c8286e2..3932c5e 100644 --- a/src/collectionUtils.ts +++ b/src/collectionUtils.ts @@ -33,7 +33,8 @@ export const getCartesianProduct = (...vectors: any[]): any[] => // Rationale: Lodash's `#isEmpty` only deals with collections... export function isEmpty(value: any) { // Easy cases: - let result: boolean | undefined = value === undefined || value === null || value === '' || undefined; + let result: boolean | undefined = + value === undefined || value === null || value === '' || undefined; const valueType = typeof value; @@ -78,7 +79,7 @@ export function isCollection(value: any) { * @see #isEmpty */ export function removeEmptyValues(collection: C): C { - return filter(collection, value => !isEmpty(value)); + return filter(collection, (value) => !isEmpty(value)); } /** @@ -90,7 +91,7 @@ export function removeEmptyValues(collection: C): C { * @param collection Collection from which to remove the missing values. */ export function removeMissingValues(collection: C): C { - return filter(collection, value => !_.isNil(value)); + return filter(collection, (value) => !_.isNil(value)); } /** @@ -98,7 +99,10 @@ export function removeMissingValues(collection: C): C { * * @param collection Collection from which to filter the values. */ -export function filter(collection: C, predicate: (value: any) => boolean): C { +export function filter( + collection: C, + predicate: (value: any) => boolean, +): C { let result: any = collection; if (!_.isNil(predicate)) { @@ -120,7 +124,7 @@ export function filter(collection: C, predicate: (value: */ export function toDictionary( collection: C, - mapper: (value: T, index: number) => string = (value: T, index: number) => String(index) + mapper: (value: T, index: number) => string = (value: T, index: number) => String(index), ): { [key: string]: T } { return _.reduce( collection, @@ -129,7 +133,7 @@ export function toDictionary( accumulator[key] = value; return accumulator; }, - {} + {}, ); } @@ -175,7 +179,7 @@ export function isCompatible(model: any, expectedModel: any, keyFilter?: string[ const _expectedModel: any = {}; const compatibilityRules: CompatibilityRuleSet = {}; - let isCompatibleRulesEmpty: boolean = true; + let isCompatibleRulesEmpty = true; _.forEach(expectedModel, (value, key) => { if (isEmpty(keyFilter) || (keyFilter && keyFilter.indexOf(key) > -1)) { if (typeof value !== 'function') { diff --git a/src/config/constants.ts b/src/config/constants.ts index b752a30..6a89c92 100644 --- a/src/config/constants.ts +++ b/src/config/constants.ts @@ -34,4 +34,4 @@ export class Constants { } } -export let constants: Constants = new Constants(); +export const constants: Constants = new Constants(); diff --git a/src/config/globalConstants.ts b/src/config/globalConstants.ts index cb8b862..9bf8c50 100644 --- a/src/config/globalConstants.ts +++ b/src/config/globalConstants.ts @@ -13,7 +13,7 @@ export class GlobalConstants { return { API: '/api', DOCUMENTATION: '/documentation', - DIAGNOSTICS: '/diagnostics' + DIAGNOSTICS: '/diagnostics', }; } @@ -35,7 +35,7 @@ export class GlobalConstants { /** * "production" seems to be the standard Node label, not "prod". */ - PROD: 'production' + PROD: 'production', }; } @@ -57,9 +57,9 @@ export class GlobalConstants { NOT_IMPLEMENTED: 'notImplemented', UNAUTHORIZED: 'unauthorized', UNPROCESSABLE_ENTITY: 'unprocessableEntity', - FORBIDDEN: 'forbidden' - } - } + FORBIDDEN: 'forbidden', + }, + }, }; } @@ -76,7 +76,7 @@ export class GlobalConstants { */ ENV_TYPE: 'NODE_ENV', - NODE_APP_INSTANCE: 'NODE_APP_INSTANCE' + NODE_APP_INSTANCE: 'NODE_APP_INSTANCE', }; } @@ -90,7 +90,7 @@ export class GlobalConstants { * in an API. * This allows local configs to be picked. */ - TESTS: 'tests' + TESTS: 'tests', }; } @@ -102,4 +102,4 @@ export class GlobalConstants { } } -export let globalConstants: GlobalConstants = new GlobalConstants(); +export const globalConstants: GlobalConstants = new GlobalConstants(); diff --git a/src/dateUtils.test.ts b/src/dateUtils.test.ts index 07982a4..c1a3235 100644 --- a/src/dateUtils.test.ts +++ b/src/dateUtils.test.ts @@ -16,7 +16,7 @@ import { ISO_DATE_PATTERN, isValidIso8601Date, parseDate, - startOfDay + startOfDay, } from './dateUtils'; const VALID_DATE_UTC_REPRESENTATION = '2018-07-31T12:34:56.789Z'; @@ -40,10 +40,10 @@ describe('Date Utility', () => { }); describe('#isDateCompatible', () => { - const dateRepr: string = '2018-09-12T21:45:12.243Z'; + const dateRepr = '2018-09-12T21:45:12.243Z'; const dateValues = [dateRepr, new Date(dateRepr), moment(dateRepr)]; - getCartesianProduct(dateValues, dateValues).forEach(dateParameters => { + getCartesianProduct(dateValues, dateValues).forEach((dateParameters) => { const parameter1 = dateParameters[0]; const parameter2 = dateParameters[1]; const parameter1TypeName = parameter1.constructor.name; @@ -59,13 +59,13 @@ describe('Date Utility', () => { const date2Repr = '2018-09-12T21:45:12.243Z'; const date2Values = [date2Repr, new Date(date2Repr), moment(date2Repr)]; - getCartesianProduct(date1Values, date2Values).forEach(dateRangeParameter => { + getCartesianProduct(date1Values, date2Values).forEach((dateRangeParameter) => { const dateRangeLowBoundary = dateRangeParameter[0]; const dateRangeHighBoundary = dateRangeParameter[1]; const dateRangeLowBoundaryTypeName = dateRangeLowBoundary.constructor.name; const dateRangeHighBoundaryTypeName = dateRangeHighBoundary.constructor.name; - dateValues.forEach(dateValue => { + dateValues.forEach((dateValue) => { const dateValueParameterType = dateValue.constructor.name; it(`should support \`${dateValueParameterType}\` & [\`${dateRangeLowBoundaryTypeName}\`:\`${dateRangeHighBoundaryTypeName}\`] parameters`, () => { @@ -75,18 +75,33 @@ describe('Date Utility', () => { }); }); - const INVALID_DATE_VALUES = [undefined, null, true, false, 123, NaN, 'pouet', _.noop, /^$/, {}, []]; - const VALID_DATE_VALUES = [new Date(2018, 7, 31, 23, 59, 59, 999), new Date(2019, 0, 1, 0, 0, 0, 0)]; + const INVALID_DATE_VALUES = [ + undefined, + null, + true, + false, + 123, + NaN, + 'pouet', + _.noop, + /^$/, + {}, + [], + ]; + const VALID_DATE_VALUES = [ + new Date(2018, 7, 31, 23, 59, 59, 999), + new Date(2019, 0, 1, 0, 0, 0, 0), + ]; describe('#isDate', () => { - INVALID_DATE_VALUES.forEach(value => { + INVALID_DATE_VALUES.forEach((value) => { const valueDescription = getValueDescriptionWithType(value); it(`should return \`false\` for ${valueDescription}`, () => { assert.isFalse(utils.isValidDate(value)); }); }); - VALID_DATE_VALUES.forEach(value => { + VALID_DATE_VALUES.forEach((value) => { const valueDescription = getValueDescription(value); it(`should return \`true\` for ${valueDescription}`, () => { assert.isTrue(utils.isValidDate(value)); @@ -97,22 +112,24 @@ describe('Date Utility', () => { const INVALID_DATE_RANGE_VALUES = getCartesianProduct(INVALID_DATE_VALUES, INVALID_DATE_VALUES); const VALID_DATE_RANGE_VALUES = getCartesianProduct(VALID_DATE_VALUES, VALID_DATE_VALUES); // Append open ranges in valid date range values: - VALID_DATE_VALUES.forEach(date => { + VALID_DATE_VALUES.forEach((date) => { VALID_DATE_RANGE_VALUES.push([date, null]); VALID_DATE_RANGE_VALUES.push([null, date]); }); // Append 3-value items into the invalid date range values: - VALID_DATE_RANGE_VALUES.forEach(dateRange => INVALID_DATE_RANGE_VALUES.push(dateRange.concat(null))); + VALID_DATE_RANGE_VALUES.forEach((dateRange) => + INVALID_DATE_RANGE_VALUES.push(dateRange.concat(null)), + ); describe('#isDateRange', () => { INVALID_DATE_RANGE_VALUES.forEach((value: any[]) => { - const valueDescription = value.map(item => getValueDescriptionWithType(item)); + const valueDescription = value.map((item) => getValueDescriptionWithType(item)); it(`should return \`false\` for [${valueDescription}]`, () => { assert.isFalse(isDateRange(value)); }); }); - VALID_DATE_RANGE_VALUES.forEach(value => { + VALID_DATE_RANGE_VALUES.forEach((value) => { const valueDescription = getValueDescription(value); it(`should return \`true\` for ${valueDescription}`, () => { assert.isTrue(isDateRange(value)); @@ -125,7 +142,7 @@ describe('Date Utility', () => { const expectations = { '2018-12-07T12:34:56.789': new Date(Date.UTC(2018, 11, 7, 12, 34, 56, 789)), '20181207T123456.789': new Date(Date.UTC(2018, 11, 7, 12, 34, 56, 789)), - '2018-12-07': new Date(Date.UTC(2018, 11, 7, 0, 0, 0, 0)) + '2018-12-07': new Date(Date.UTC(2018, 11, 7, 0, 0, 0, 0)), }; _.forEach(expectations, (expectedResult, value) => { const valueDescription = getValueDescription(value); @@ -135,10 +152,10 @@ describe('Date Utility', () => { }); const expectedlyFailingValues = [null, undefined, 'true', 'false', '???']; - expectedlyFailingValues.forEach(value => { + expectedlyFailingValues.forEach((value) => { const valueDescription = getValueDescription(value); it(`should fail with ${valueDescription}`, () => { - let failed: boolean = false; + let failed = false; try { getSafeDate(value); } catch (error) { @@ -170,7 +187,10 @@ describe('Date Utility', () => { describe('#parseDate', () => { it('should parse date representations properly', () => { assert.deepStrictEqual(parseDate(VALID_DATE_UTC_REPRESENTATION), VALID_DATE); - assert.deepStrictEqual(parseDate(VALID_DATE_UTC_REPRESENTATION, DEFAULT_DATE_FORMAT), VALID_DATE); + assert.deepStrictEqual( + parseDate(VALID_DATE_UTC_REPRESENTATION, DEFAULT_DATE_FORMAT), + VALID_DATE, + ); const FUNKY_FORMAT = 'YYYY/MM/DD@HH:mm:ss.SSS'; let result: Date = parseDate('2018/07/31@12:34:56.789', [FUNKY_FORMAT]); @@ -199,7 +219,7 @@ describe('Date Utility', () => { '20180731 123456,789-1011': ['20180731', '', '123456', '', '789', '-1011'], '20180731T123456,789+10:11': ['20180731', '', '123456', '', '789', '+10:11'], '20180731 12:34:56,789-1011': ['20180731', '', '12:34:56', ':', '789', '-1011'], - '2018-07-31 12:34:56.789Z': ['2018-07-31', '-', '12:34:56', ':', '789', 'Z'] + '2018-07-31 12:34:56.789Z': ['2018-07-31', '-', '12:34:56', ':', '789', 'Z'], }; _.forEach(expectations, (expectation, value) => { it(`should match « ${value} »`, () => { @@ -229,9 +249,9 @@ describe('Date Utility', () => { '20180731T123456.7891011', // missing time-offset separator '2018-07-31 01:23:45.678+1', // bad offset format '2018-07-31 12:34:56.789+1011Z', // bad offset format - '2018-07-31 01:23:45.678+2400' // offset overflow + '2018-07-31 01:23:45.678+2400', // offset overflow ]; - invalidDateValues.forEach(value => { + invalidDateValues.forEach((value) => { it(`should *NOT* match « ${value} »`, () => { assert.isNull(ISO_DATE_PATTERN.exec(value)); assert.isFalse(isValidIso8601Date(value)); diff --git a/src/dateUtils.ts b/src/dateUtils.ts index bb7b2de..68c8f8a 100644 --- a/src/dateUtils.ts +++ b/src/dateUtils.ts @@ -16,7 +16,7 @@ export function isDateEqual(value: DateDefinition, expectedDate: DateDefinition) export function isDateBetween( value: DateDefinition, expectedDate: DateRangeDefinition, - inclusivity: '()' | '[)' | '(]' | '[]' = '[]' + inclusivity: '()' | '[)' | '(]' | '[]' = '[]', ) { const _moment: Moment = moment(value); const from = expectedDate[0]; @@ -53,8 +53,8 @@ export function isDateRange(value: any[]): boolean { let result: boolean = !!value && value.length === 2; if (result) { - let dateItemCount: number = 0; - let otherItemCount: number = 0; + let dateItemCount = 0; + let otherItemCount = 0; for (const item of value) { if (utils.isValidDate(item)) { @@ -97,8 +97,12 @@ export function getSafeDate(dateDefinition: DateDefinition): Date { * @see `#getSafeDate` */ export function getSafeDateRange(dateRangeDefinition: DateRangeDefinition): [Date, Date] { - const lowBoundary = dateRangeDefinition[0] ? getSafeDate(dateRangeDefinition[0]) : (dateRangeDefinition[0] as any); - const highBoundary = dateRangeDefinition[1] ? getSafeDate(dateRangeDefinition[1]) : (dateRangeDefinition[1] as any); + const lowBoundary = dateRangeDefinition[0] + ? getSafeDate(dateRangeDefinition[0]) + : (dateRangeDefinition[0] as any); + const highBoundary = dateRangeDefinition[1] + ? getSafeDate(dateRangeDefinition[1]) + : (dateRangeDefinition[1] as any); return [lowBoundary, highBoundary]; } @@ -127,7 +131,7 @@ export type TimeUnitSymbol = 'ms' | 's' | 'm' | 'h' | 'd' | 'w'; export function getDateRangeAround( value: DateDefinition, marginValue: number, - marginUnit: TimeUnitSymbol + marginUnit: TimeUnitSymbol, ): DateRangeDefinition { const _moment = moment(value); return [_moment.subtract(marginValue, marginUnit), _moment.add(marginValue, marginUnit)]; @@ -137,7 +141,8 @@ export function getDateRangeAround( * Pattern matching most ISO 8601 date representations (including time), and which can be used for any kind of validation. * @example `2018-07-31T12:34:56.789+10:11` */ -export const ISO_DATE_PATTERN: RegExp = /^(\d{4}(-?)(?:0\d|1[0-2])\2?(?:[0-2]\d|3[0-1]))(?:[T ]([0-2][0-3](:?)[0-5]\d\4[0-5]\d)(?:[.,](\d{3}))?([+-](?:[01]\d(?::?[0-5]\d)?)|Z)?)?$/; +export const ISO_DATE_PATTERN = + /^(\d{4}(-?)(?:0\d|1[0-2])\2?(?:[0-2]\d|3[0-1]))(?:[T ]([0-2][0-3](:?)[0-5]\d\4[0-5]\d)(?:[.,](\d{3}))?([+-](?:[01]\d(?::?[0-5]\d)?)|Z)?)?$/; /** * Tells whether the provided date representation is valid as per ISO 8601. @@ -145,7 +150,7 @@ export const ISO_DATE_PATTERN: RegExp = /^(\d{4}(-?)(?:0\d|1[0-2])\2?(?:[0-2]\d| * @see `ISO_DATE_PATTERN` */ export function isValidIso8601Date(representation: string): boolean { - let valid: boolean = false; + let valid = false; if (representation !== undefined && representation !== null) { valid = ISO_DATE_PATTERN.test(representation); @@ -167,7 +172,10 @@ export const DEFAULT_DATE_FORMAT = 'YYYY-MM-DDTHH:mm:ss.SSSZ'; * Parses the given date representation using the provided format (or the default ISO format). * @see `#formatDate` */ -export function parseDate(representation: string, format: string | string[] = DEFAULT_DATE_FORMAT): Date { +export function parseDate( + representation: string, + format: string | string[] = DEFAULT_DATE_FORMAT, +): Date { const formats: string[] = format instanceof Array ? format : [format]; return moment.utc(representation, formats).toDate(); } @@ -219,7 +227,10 @@ export function formatUtcDate(date: DateDefinition, format: string = DEFAULT_DAT * on how the server is configured. This is why a timezone must be * specified here. */ -export function startOfDay(isoDate: Date | string, timezone: string | Zone = 'America/Montreal'): Date { +export function startOfDay( + isoDate: Date | string, + timezone: string | Zone = 'America/Montreal', +): Date { if (_.isNil(isoDate)) { return isoDate; } @@ -247,7 +258,10 @@ export function startOfDay(isoDate: Date | string, timezone: string | Zone = 'Am * information. * */ -export function endOfDay(isoDate: Date | string, timezone: string | Zone = 'America/Montreal'): Date { +export function endOfDay( + isoDate: Date | string, + timezone: string | Zone = 'America/Montreal', +): Date { if (_.isNil(isoDate)) { return isoDate; } diff --git a/src/logLevel.ts b/src/logLevel.ts index 77a4b78..440e366 100644 --- a/src/logLevel.ts +++ b/src/logLevel.ts @@ -16,7 +16,7 @@ export enum LogLevel { DEBUG, INFO, WARNING, - ERROR + ERROR, } /** diff --git a/src/orderBy.ts b/src/orderBy.ts index 298f2e2..b50cef8 100644 --- a/src/orderBy.ts +++ b/src/orderBy.ts @@ -34,5 +34,5 @@ export const isOrderByArray = (objs: any): objs is IOrderBy[] => { export enum OrderByDirection { ASC = 'ASC', - DESC = 'DESC' + DESC = 'DESC', } diff --git a/src/pagination.test.ts b/src/pagination.test.ts index dff090d..cfb7c9f 100644 --- a/src/pagination.test.ts +++ b/src/pagination.test.ts @@ -16,15 +16,15 @@ describe('pagination object', () => { { name: 'seven', value: 7 }, { name: 'eight', value: 8 }, { name: 'nine', value: 9 }, - { name: 'ten', value: 10 } + { name: 'ten', value: 10 }, ]; const result: IPaginatedResult = { items: numberlist.slice(0, 3), paging: { limit: 3, offset: 0, - totalCount: numberlist.length - } + totalCount: numberlist.length, + }, }; assert.isOk(result); diff --git a/src/pagination.ts b/src/pagination.ts index 7b9dfb7..4b4680e 100644 --- a/src/pagination.ts +++ b/src/pagination.ts @@ -14,7 +14,7 @@ export interface IPaginatedResult { /** * IPaginatedResult Type Guard */ -export let isPaginatedResult = (obj: any): obj is IPaginatedResult => { +export const isPaginatedResult = (obj: any): obj is IPaginatedResult => { return ( obj && 'paging' in obj && diff --git a/src/stringUtils.test.ts b/src/stringUtils.test.ts index fb47035..82a81fa 100644 --- a/src/stringUtils.test.ts +++ b/src/stringUtils.test.ts @@ -39,16 +39,24 @@ describe('String Utility', () => { assert.strictEqual(deDuplicateChars('a b', ' ', '_'), 'a_b'); assert.strictEqual( deDuplicateChars(' \r\n \t a \r\n \t \n \t b \r\n \t ', ' \t\r\n', ' '), - ' a b ' + ' a b ', + ); + assert.strictEqual( + deDuplicateChars(' \r\n \t a \r\n \t \n \t b \r\n \t ', ' \t\r\n', ''), + 'ab', ); - assert.strictEqual(deDuplicateChars(' \r\n \t a \r\n \t \n \t b \r\n \t ', ' \t\r\n', ''), 'ab'); }); it('With trim', () => { assert.strictEqual(deDuplicateChars(' a b ', ' ', ' ', true), 'a b'); assert.strictEqual( - deDuplicateChars(' \r\n \t a \r\n \t \n \t b \r\n \t ', ' \t\r\n', ' ', true), - 'a b' + deDuplicateChars( + ' \r\n \t a \r\n \t \n \t b \r\n \t ', + ' \t\r\n', + ' ', + true, + ), + 'a b', ); }); }); @@ -62,8 +70,10 @@ describe('String Utility', () => { assert.strictEqual(trimAll(' '), ''); assert.strictEqual(trimAll(' \r\n \r \t \n \r\t \t'), ''); assert.strictEqual( - trimAll(' \r\n \r \t \n \r\t \t a \r\n \r \t \n \r\t \tb \r\n \r \t \n \r\t \t'), - 'a b' + trimAll( + ' \r\n \r \t \n \r\t \t a \r\n \r \t \n \r\t \tb \r\n \r \t \n \r\t \t', + ), + 'a b', ); }); }); diff --git a/src/stringUtils.ts b/src/stringUtils.ts index f75fcec..1beaca2 100644 --- a/src/stringUtils.ts +++ b/src/stringUtils.ts @@ -67,9 +67,14 @@ export function deDuplicateChars( value: string, continuousCharsToReplace: string, replacement: string, - trimStartEnd: boolean = false + trimStartEnd = false, ): string { - if (_.isNil(value) || _.isNil(continuousCharsToReplace) || continuousCharsToReplace === '' || _.isNil(replacement)) { + if ( + _.isNil(value) || + _.isNil(continuousCharsToReplace) || + continuousCharsToReplace === '' || + _.isNil(replacement) + ) { return value; } diff --git a/src/timer.test.ts b/src/timer.test.ts index 408ec4a..b41bf81 100644 --- a/src/timer.test.ts +++ b/src/timer.test.ts @@ -6,7 +6,7 @@ import { utils } from './utils'; // Timer object tests // ========================================== describe('Timer object', () => { - it('Milliseconds', async function() { + it('Milliseconds', async function () { this.timeout(4000); const timer = new Timer(); @@ -27,7 +27,7 @@ describe('Timer object', () => { assert.isTrue(milliSecs > 2000, `was "${milliSecs}"`); }); - it('Default format', async function() { + it('Default format', async function () { this.timeout(4000); const timer = new Timer(); @@ -43,7 +43,7 @@ describe('Timer object', () => { assert.isTrue(elapsed.startsWith('00:00:02.'), `was "${elapsed}"`); }); - it('Custom format', async function() { + it('Custom format', async function () { this.timeout(4000); const timer = new Timer(); diff --git a/src/timer.ts b/src/timer.ts index ac37111..9347eb2 100644 --- a/src/timer.ts +++ b/src/timer.ts @@ -42,7 +42,7 @@ export class Timer { * documentation to see how to define a custom format : * https://momentjs.com/docs/#/displaying/format/ */ - public toString(format: string = 'HH:mm:ss.SSS'): string { + public toString(format = 'HH:mm:ss.SSS'): string { const millisecs = this.getMillisecondsElapsed(); return moment.utc(millisecs).format(format); } diff --git a/src/utils.test.ts b/src/utils.test.ts index 618f318..b3a0cb0 100644 --- a/src/utils.test.ts +++ b/src/utils.test.ts @@ -15,12 +15,12 @@ import { ExecError, utils, Utils } from './utils'; // A regular "function" is required here for the call to "this.timeout(...)" // @see https://github.com/mochajs/mocha/issues/2018 // tslint:disable-next-line:only-arrow-functions ter-prefer-arrow-callback -describe("App's utilities functions", function() { +describe("App's utilities functions", function () { // ========================================== // tsc() // ========================================== describe('tsc', () => { - it("Compiles a TypeScript file using the 'tsc()' utility", async function() { + it("Compiles a TypeScript file using the 'tsc()' utility", async function () { if (!fs.existsSync(constants.testDataDirPath)) { fs.mkdirSync(constants.testDataDirPath); } @@ -37,7 +37,10 @@ describe("App's utilities functions", function() { const fileName = uuid(); const filesPathPrefix = tmpRepPath + '/' + fileName; const tsFilePath = filesPathPrefix + '.ts'; - fs.writeFileSync(tsFilePath, `import * as path from 'path';\nlet t = 'a';\nt = t + path.sep;`); + fs.writeFileSync( + tsFilePath, + `import * as path from 'path';\nlet t = 'a';\nt = t + path.sep;`, + ); const distRepPath = constants.libRoot + '/dist'; @@ -281,10 +284,18 @@ describe("App's utilities functions", function() { result = utils.isIntegerValue(['string', 2, false]); assert.isFalse(result); - result = utils.isIntegerValue({ firstStringValue: 'a', secondStringValue: 'b', thirdStringValue: 'c' }); + result = utils.isIntegerValue({ + firstStringValue: 'a', + secondStringValue: 'b', + thirdStringValue: 'c', + }); assert.isFalse(result); - result = utils.isIntegerValue({ firstNumberValue: 1, secondNumberValue: 2, thirdNumberValue: 3 }); + result = utils.isIntegerValue({ + firstNumberValue: 1, + secondNumberValue: 2, + thirdNumberValue: 3, + }); assert.isFalse(result); result = utils.isIntegerValue({ stringValue: 'string', numberValue: 2, booleanValue: false }); @@ -933,7 +944,7 @@ describe("App's utilities functions", function() { fs.removeSync(constants.testDataDirPath); }); - it('compile', async function() { + it('compile', async function () { // May take some time to compile... this.timeout(7000); @@ -941,9 +952,12 @@ describe("App's utilities functions", function() { const filesPathPrefix = tmpRepPath + '/' + fileName; const tsFilePath = filesPathPrefix + '.ts'; - const content = fs.readFileSync(constants.libRoot + '/tests-resources/throwNotManagedSuccess.txt', { - encoding: 'utf-8' - }); + const content = fs.readFileSync( + constants.libRoot + '/tests-resources/throwNotManagedSuccess.txt', + { + encoding: 'utf-8', + }, + ); fs.writeFileSync(tsFilePath, content); await utils.tsc([tsFilePath]); @@ -953,7 +967,7 @@ describe("App's utilities functions", function() { fs.removeSync(distRepPath); }); - it("doesn't compile", async function() { + it("doesn't compile", async function () { // May take some time to compile... this.timeout(7000); @@ -966,9 +980,12 @@ describe("App's utilities functions", function() { const filesPathPrefix = tmpRepPath + '/' + fileName; const tsFilePath = filesPathPrefix + '.ts'; - const content = fs.readFileSync(constants.libRoot + '/tests-resources/throwNotManagedFail.txt', { - encoding: 'utf-8' - }); + const content = fs.readFileSync( + constants.libRoot + '/tests-resources/throwNotManagedFail.txt', + { + encoding: 'utf-8', + }, + ); fs.writeFileSync(tsFilePath, content); try { @@ -1003,7 +1020,7 @@ describe("App's utilities functions", function() { [], [123], // tslint:disable-next-line:prefer-array-literal - new Array(), + [], null, undefined, '', @@ -1013,7 +1030,7 @@ describe("App's utilities functions", function() { new Date(), () => { /* ok */ - } + }, ] as any) { assert.isFalse(utils.isObjectStrict(value)); } @@ -1028,8 +1045,8 @@ describe("App's utilities functions", function() { const array = [ { aaa: 123, - myKey: 'myValue' - } + myKey: 'myValue', + }, ]; assert.isTrue(utils.arrayContainsObjectWithKeyEqualsTo(array, 'myKey', 'myValue')); }); @@ -1038,8 +1055,8 @@ describe("App's utilities functions", function() { const array = [ { aaa: 123, - myKey: 12345 - } + myKey: 12345, + }, ]; assert.isTrue(utils.arrayContainsObjectWithKeyEqualsTo(array, 'myKey', 12345)); }); @@ -1049,8 +1066,8 @@ describe("App's utilities functions", function() { const array = [ { aaa: 123, - myKey: someDate - } + myKey: someDate, + }, ]; assert.isTrue(utils.arrayContainsObjectWithKeyEqualsTo(array, 'myKey', someDate)); }); @@ -1066,17 +1083,17 @@ describe("App's utilities functions", function() { '', null, { - juju: 123.45 - } + juju: 123.45, + }, ], - tata: undefined as number + tata: undefined as number, }; const array = [ { aaa: 123, - myKey: obj - } + myKey: obj, + }, ]; assert.isTrue(utils.arrayContainsObjectWithKeyEqualsTo(array, 'myKey', obj)); }); @@ -1092,17 +1109,17 @@ describe("App's utilities functions", function() { '', null, { - juju: 123.45 - } + juju: 123.45, + }, ], - tata: undefined as number + tata: undefined as number, }; const array = [ { aaa: 123, - nope: obj - } + nope: obj, + }, ]; assert.isFalse(utils.arrayContainsObjectWithKeyEqualsTo(array, 'myKey', obj)); }); @@ -1118,17 +1135,17 @@ describe("App's utilities functions", function() { '', null, { - juju: 123.45 - } + juju: 123.45, + }, ], - tata: undefined as number + tata: undefined as number, }; const array = [ { aaa: 123, - myKey: obj - } + myKey: obj, + }, ]; assert.isFalse( utils.arrayContainsObjectWithKeyEqualsTo(array, 'myKey', { @@ -1139,11 +1156,11 @@ describe("App's utilities functions", function() { '', null, { - juju: 123.45 - } + juju: 123.45, + }, ], - tata: undefined as number - }) + tata: undefined as number, + }), ); }); @@ -1274,26 +1291,26 @@ describe("App's utilities functions", function() { it('custom exit code - success', async () => { const exitCode = await utils.exec(`node`, [dummyJs, `customExitCode`, `123`], { - successExitCodes: 123 + successExitCodes: 123, }); assert.deepEqual(exitCode, 123); }); it('custom exit code - multiple', async () => { let exitCode = await utils.exec(`node`, [dummyJs, `customExitCode`, `123`], { - successExitCodes: [0, 123] + successExitCodes: [0, 123], }); assert.deepEqual(exitCode, 123); exitCode = await utils.exec(`node`, [dummyJs, `success`], { - successExitCodes: [0, 123] + successExitCodes: [0, 123], }); assert.deepEqual(exitCode, 0); let error; try { await utils.exec(`node`, [dummyJs, `customExitCode`, `1`], { - successExitCodes: [0, 123] + successExitCodes: [0, 123], }); } catch (err) { error = err; @@ -1331,7 +1348,7 @@ describe("App's utilities functions", function() { outputHandler: (stdoutOutput: string, stderrOutput: string): void => { execOut += stdoutOutput ? stdoutOutput : ''; execErr += stderrOutput ? stderrOutput : ''; - } + }, }); assert.isTrue(execOut.includes(`in dummy - info`)); @@ -1374,7 +1391,7 @@ describe("App's utilities functions", function() { execOut += stdoutOutput ? stdoutOutput : ''; execErr += stderrOutput ? stderrOutput : ''; }, - disableConsoleOutputs: true + disableConsoleOutputs: true, }); assert.isTrue(execOut.includes(`in dummy - info`)); @@ -1400,7 +1417,7 @@ describe("App's utilities functions", function() { (stdoutOutput: string, stderrOutput: string): void => { execOut += stdoutOutput ? stdoutOutput : ''; execErr += stderrOutput ? stderrOutput : ''; - } + }, ); assert.isUndefined(exitCode); // no exit code diff --git a/src/utils.ts b/src/utils.ts index 4c00a05..8c8497f 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -84,7 +84,7 @@ export class Utils { * to "clean" it, e.g., getting rid of unmeaningful * decimal zeros or whitespaces. */ - public isIntegerValue(value: any, positiveOnly: boolean = false, includeZero: boolean = true): boolean { + public isIntegerValue(value: any, positiveOnly = false, includeZero = true): boolean { if (this.isNaNSafe(value)) { return false; } @@ -305,7 +305,7 @@ export class Utils { return; } - const cmd: string = 'node'; + const cmd = 'node'; const args = [constants.libRoot + '/node_modules/typescript/lib/tsc.js'] .concat(this.tscCompilerOptions) .concat(files); @@ -319,7 +319,7 @@ export class Utils { * Both "start" and "end" are inclusive. */ public range = (start: number, end: number): number[] => { - return [...Array(1 + end - start).keys()].map(v => start + v); + return [...Array(1 + end - start).keys()].map((v) => start + v); }; /** @@ -435,12 +435,12 @@ export class Utils { command: string, args: string[], dataHandler: (stdoutData: string, stderrData: string) => void = null, - useShellOption: boolean = false + useShellOption = false, ): Promise { return this.exec(command, args, { outputHandler: dataHandler, useShellOption, - disableConsoleOutputs: !dataHandler + disableConsoleOutputs: !dataHandler, }).then((_val: number) => { // nothing, returns void }); @@ -494,7 +494,7 @@ export class Utils { disableConsoleOutputs?: boolean; stdio?: StdioOptions; useShellOption?: boolean; - } + }, ): Promise { const optionsClean = options ?? {}; optionsClean.useShellOption = optionsClean.useShellOption ?? true; @@ -515,7 +515,7 @@ export class Utils { detached: false, stdio: optionsClean.stdio, shell: optionsClean.useShellOption, - windowsVerbatimArguments: false + windowsVerbatimArguments: false, }); spawnedProcess.on('close', (code: number) => { @@ -524,8 +524,8 @@ export class Utils { reject( new ExecError( `Expected success codes were "${successExitCodes.toString()}", but the process exited with "${code}".`, - code - ) + code, + ), ); } else { resolve(code); @@ -562,7 +562,10 @@ export class Utils { */ // tslint:disable-next-line: max-classes-per-file export class ExecError extends Error { - constructor(message: string, public exitCode: number) { + constructor( + message: string, + public exitCode: number, + ) { super(message); } } @@ -576,4 +579,4 @@ export function getValueDescriptionWithType(value: any): string { return getValueDescription(value) + ` (${valueType})`; } -export let utils: Utils = new Utils(); +export const utils: Utils = new Utils(); diff --git a/tests-resources/exec/execTest.ts b/tests-resources/exec/execTest.ts index efacaf8..c998a43 100644 --- a/tests-resources/exec/execTest.ts +++ b/tests-resources/exec/execTest.ts @@ -16,7 +16,7 @@ if (action === 'error') { throw new Error(`Some error`); } -})().catch(err => { +})().catch((err) => { console.error(err.message); process.exit(1); });