From c7f0099e2d82252dfb4e70ff6af2116f970e1e74 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Lenon?= Date: Thu, 7 Sep 2023 09:59:53 +0100 Subject: [PATCH] feat(is): add Is.Module() method --- package-lock.json | 4 +- package.json | 4 +- src/exceptions/InvalidNumberException.ts | 2 +- src/exceptions/InvalidUuidException.ts | 2 +- src/exceptions/NodeCommandException.ts | 2 +- src/exceptions/NotFoundFileException.ts | 2 +- src/exceptions/NotFoundFolderException.ts | 2 +- src/exceptions/NotFoundResolveException.ts | 2 +- src/exceptions/OrdinalNanException.ts | 2 +- src/exceptions/RouteMatchException.ts | 2 +- src/helpers/Clean.ts | 8 +- src/helpers/Color.ts | 6 +- src/helpers/Exception.ts | 6 +- src/helpers/Exec.ts | 16 ++-- src/helpers/FakeApi.ts | 6 +- src/helpers/File.ts | 54 ++++++------ src/helpers/Folder.ts | 84 +++++++++---------- src/helpers/HttpClient.ts | 18 ++-- src/helpers/Is.ts | 30 +++++-- src/helpers/Json.ts | 16 ++-- src/helpers/Module.ts | 18 ++-- src/helpers/Number.ts | 2 +- src/helpers/Options.ts | 2 +- src/helpers/Parser.ts | 12 +-- src/helpers/Path.ts | 17 ++++ src/helpers/Route.ts | 6 +- src/helpers/String.ts | 6 +- src/helpers/Uuid.ts | 2 +- src/types/PathDirs.ts | 1 + .../http-client/RetryStrategyCallback.ts | 2 +- src/types/index.ts | 4 +- tests/stubs/config/app.ts | 2 +- tests/unit/CleanTest.ts | 12 +-- tests/unit/CollectionTest.ts | 4 +- tests/unit/ExceptionTest.ts | 4 +- tests/unit/ExecTest.ts | 8 +- tests/unit/FakeApiTest.ts | 2 +- tests/unit/FileTest.ts | 4 +- tests/unit/FolderTest.ts | 16 ++-- tests/unit/HttpClientTest.ts | 4 +- tests/unit/IsTest.ts | 23 +++-- tests/unit/JsonTest.ts | 34 ++++---- tests/unit/NumberTest.ts | 4 +- tests/unit/OptionsTest.ts | 4 +- tests/unit/ParserTest.ts | 16 ++-- tests/unit/PathTest.ts | 4 +- tests/unit/RouteTest.ts | 4 +- 47 files changed, 268 insertions(+), 217 deletions(-) diff --git a/package-lock.json b/package-lock.json index c571cb2..852dcf1 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@athenna/common", - "version": "4.9.1", + "version": "4.10.0", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "@athenna/common", - "version": "4.9.1", + "version": "4.10.0", "license": "MIT", "dependencies": { "@fastify/formbody": "^7.4.0", diff --git a/package.json b/package.json index fad9581..9f636dc 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@athenna/common", - "version": "4.9.2", + "version": "4.10.0", "description": "The Athenna common helpers to use in any Node.js ESM project.", "license": "MIT", "author": "João Lenon ", @@ -143,7 +143,7 @@ }, "prettier": { "singleQuote": true, - "trailingComma": "all", + "trailingComma": "none", "arrowParens": "avoid", "endOfLine": "lf", "semi": false, diff --git a/src/exceptions/InvalidNumberException.ts b/src/exceptions/InvalidNumberException.ts index 84e576c..e223bde 100644 --- a/src/exceptions/InvalidNumberException.ts +++ b/src/exceptions/InvalidNumberException.ts @@ -14,7 +14,7 @@ export class InvalidNumberException extends Exception { super({ code: 'E_INVALID_NUMBER', help: 'Use a valid string number instead.', - message: `The number ${number} is not a valid string number.`, + message: `The number ${number} is not a valid string number.` }) } } diff --git a/src/exceptions/InvalidUuidException.ts b/src/exceptions/InvalidUuidException.ts index 23c0c93..2ea26b4 100644 --- a/src/exceptions/InvalidUuidException.ts +++ b/src/exceptions/InvalidUuidException.ts @@ -14,7 +14,7 @@ export class InvalidUuidException extends Exception { super({ code: 'E_INVALID_UUID', help: 'Use a valid UUID instead.', - message: `The value ${value} is not a valid UUID.`, + message: `The value ${value} is not a valid UUID.` }) } } diff --git a/src/exceptions/NodeCommandException.ts b/src/exceptions/NodeCommandException.ts index 01d75ac..ec0fd5a 100644 --- a/src/exceptions/NodeCommandException.ts +++ b/src/exceptions/NodeCommandException.ts @@ -22,7 +22,7 @@ export class NodeCommandException extends Exception { super({ help, code: 'E_NODE_EXEC', - message: `Error has occurred when executing the command "${command}"`, + message: `Error has occurred when executing the command "${command}"` }) } } diff --git a/src/exceptions/NotFoundFileException.ts b/src/exceptions/NotFoundFileException.ts index 4b3ca6e..3ed5097 100644 --- a/src/exceptions/NotFoundFileException.ts +++ b/src/exceptions/NotFoundFileException.ts @@ -14,7 +14,7 @@ export class NotFoundFileException extends Exception { super({ code: 'E_NOT_FOUND_FILE', message: `The file ${filePath} doesnt exist.`, - help: 'Try using File.create method to create the file.', + help: 'Try using File.create method to create the file.' }) } } diff --git a/src/exceptions/NotFoundFolderException.ts b/src/exceptions/NotFoundFolderException.ts index 63c4846..7bdae60 100644 --- a/src/exceptions/NotFoundFolderException.ts +++ b/src/exceptions/NotFoundFolderException.ts @@ -14,7 +14,7 @@ export class NotFoundFolderException extends Exception { super({ code: 'E_NOT_FOUND_FILE', message: `The folder ${filePath} doesnt exist.`, - help: 'Try using Folder.create method to create the folder.', + help: 'Try using Folder.create method to create the folder.' }) } } diff --git a/src/exceptions/NotFoundResolveException.ts b/src/exceptions/NotFoundResolveException.ts index 8e1df06..0e14d83 100644 --- a/src/exceptions/NotFoundResolveException.ts +++ b/src/exceptions/NotFoundResolveException.ts @@ -14,7 +14,7 @@ export class NotFoundResolveException extends Exception { super({ code: 'E_NOT_FOUND_RESOLVE', message: `The importa.meta.resolve function does not exist in import.meta object.`, - help: 'The resolve function is not defined because the --experimental-import-meta-resolve option in Node CLI is required when running your application. Try to set up this option when running your application.', + help: 'The resolve function is not defined because the --experimental-import-meta-resolve option in Node CLI is required when running your application. Try to set up this option when running your application.' }) } } diff --git a/src/exceptions/OrdinalNanException.ts b/src/exceptions/OrdinalNanException.ts index 8715542..ffc4581 100644 --- a/src/exceptions/OrdinalNanException.ts +++ b/src/exceptions/OrdinalNanException.ts @@ -14,7 +14,7 @@ export class OrdinalNanException extends Exception { super({ code: 'E_ORDINAL_NAN', message: 'Cannot ordinal NaN or infinite numbers.', - help: 'Use a valid number instead of NaN or infinite.', + help: 'Use a valid number instead of NaN or infinite.' }) } } diff --git a/src/exceptions/RouteMatchException.ts b/src/exceptions/RouteMatchException.ts index 1c2b54f..583385d 100644 --- a/src/exceptions/RouteMatchException.ts +++ b/src/exceptions/RouteMatchException.ts @@ -14,7 +14,7 @@ export class RouteMatchException extends Exception { super({ code: 'E_ROUTE_MATCH', message: `The route ${routeWithParams} does not match ${routeWithValues}`, - help: 'Please open an issue in https://github.com/AthennaIO/Common/issues', + help: 'Please open an issue in https://github.com/AthennaIO/Common/issues' }) } } diff --git a/src/helpers/Clean.ts b/src/helpers/Clean.ts index 28b355a..62e6d17 100644 --- a/src/helpers/Clean.ts +++ b/src/helpers/Clean.ts @@ -19,11 +19,11 @@ export class Clean { options: { removeEmpty?: boolean recursive?: boolean - } = {}, + } = {} ) { options = Options.create(options, { removeEmpty: false, - recursive: false, + recursive: false }) return array @@ -54,11 +54,11 @@ export class Clean { options: { removeEmpty?: boolean recursive?: boolean - } = {}, + } = {} ): T { options = Options.create(options, { removeEmpty: false, - recursive: false, + recursive: false }) const cleanedObject: any = {} diff --git a/src/helpers/Color.ts b/src/helpers/Color.ts index 903a90d..0a55821 100644 --- a/src/helpers/Color.ts +++ b/src/helpers/Color.ts @@ -227,7 +227,7 @@ export class Color { return Color.chalk.reset(value).replace( // eslint-disable-next-line no-control-regex /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g, - '', + '' ) } @@ -242,7 +242,7 @@ export class Color { * Paint by the http method. */ public static httpMethod( - method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'OPTIONS' | 'HEAD', + method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'OPTIONS' | 'HEAD' ): ChalkInstance { return this[method] } @@ -276,7 +276,7 @@ export class Color { matches.forEach(match => { const [chalkMethodsInBrackets, chalkMethodsString] = match.match( - /\{(.*?)}/, + /\{(.*?)}/ ) as any const message = match diff --git a/src/helpers/Exception.ts b/src/helpers/Exception.ts index 16bd084..12af66b 100644 --- a/src/helpers/Exception.ts +++ b/src/helpers/Exception.ts @@ -34,7 +34,7 @@ export class Exception extends Error { help: null, stack: null, name: this.constructor.name, - code: changeCase.constantCase(this.constructor.name), + code: changeCase.constantCase(this.constructor.name) }) this.name = options.name @@ -87,7 +87,7 @@ export class Exception extends Error { hideErrorTitle: true, hideMessage: false, displayMainFrameOnly: false, - framesMaxLimit: 3, + framesMaxLimit: 3 }) const separator = Color.cyan('-----') @@ -98,7 +98,7 @@ export class Exception extends Error { if (this.help && this.help !== '') { this.help = `${helpKey}\n\n ${Color.green( - Color.apply(this.help), + Color.apply(this.help) )}\n\n ${separator}` } else { this.message = this.message.concat(`\n\n${separator}`) diff --git a/src/helpers/Exec.ts b/src/helpers/Exec.ts index f17a4f0..0a4da24 100644 --- a/src/helpers/Exec.ts +++ b/src/helpers/Exec.ts @@ -36,7 +36,7 @@ export class Exec { public static async concurrently( array: T[], - callback: (value: T, index: number, array: T[]) => Promise, + callback: (value: T, index: number, array: T[]) => Promise ): Promise { return Promise.all(array.map(callback)) } @@ -46,10 +46,10 @@ export class Exec { */ public static async command( command: string, - options?: { ignoreErrors?: boolean }, + options?: { ignoreErrors?: boolean } ): Promise { options = Options.create(options, { - ignoreErrors: false, + ignoreErrors: false }) const execOptions: ExecOptions = {} @@ -66,7 +66,7 @@ export class Exec { const result: CommandOutput = { stdout: '', stderr: '', - exitCode: 0, + exitCode: 0 } exec(command, execOptions, (error, stdout, stderr) => { @@ -129,12 +129,12 @@ export class Exec { public static pagination( data: any[], total: number, - pagination?: PaginationOptions, + pagination?: PaginationOptions ): PaginatedResponse { pagination = Options.create(pagination, { page: 0, limit: 10, - resourceUrl: '/', + resourceUrl: '/' }) const totalPages = Math.ceil(total / pagination.limit) @@ -144,7 +144,7 @@ export class Exec { totalItems: total, totalPages, currentPage: pagination.page, - itemsPerPage: pagination.limit, + itemsPerPage: pagination.limit } let nextPage = 1 @@ -159,7 +159,7 @@ export class Exec { first: `${pagination.resourceUrl}?limit=${meta.itemsPerPage}`, previous: `${pagination.resourceUrl}?page=${previousPage}&limit=${meta.itemsPerPage}`, next: `${pagination.resourceUrl}?page=${nextPage}&limit=${meta.itemsPerPage}`, - last: `${pagination.resourceUrl}?page=${totalPages}&limit=${meta.itemsPerPage}`, + last: `${pagination.resourceUrl}?page=${totalPages}&limit=${meta.itemsPerPage}` } return { meta, links, data } diff --git a/src/helpers/FakeApi.ts b/src/helpers/FakeApi.ts index bf077e9..eed1951 100644 --- a/src/helpers/FakeApi.ts +++ b/src/helpers/FakeApi.ts @@ -65,7 +65,7 @@ export class FakeApi { */ public static async start( port = 8989, - folderPath = Path.resources('fake-api'), + folderPath = Path.resources('fake-api') ): Promise { if (folderPath) { await this.registerFolder(folderPath) @@ -92,7 +92,7 @@ export class FakeApi { const files = new Folder(path).getFilesByPattern('**/*.json') const promises = files.map(file => - file.load().then(fileLoaded => this.registerFile(fileLoaded)), + file.load().then(fileLoaded => this.registerFile(fileLoaded)) ) await Promise.all(promises) @@ -241,7 +241,7 @@ export class FakeApiBuilder { return response.status(statusCode).headers(headers).send(body) }, - ...options, + ...options }) } } diff --git a/src/helpers/File.ts b/src/helpers/File.ts index 19622ea..6a99961 100644 --- a/src/helpers/File.ts +++ b/src/helpers/File.ts @@ -24,7 +24,7 @@ import { statSync, writeFileSync, ReadStream, - WriteStream, + WriteStream } from 'node:fs' import { lookup } from 'mime-types' @@ -145,7 +145,7 @@ export class File { filePath: string, content: string | Buffer = undefined, mockedValues = false, - isCopy = false, + isCopy = false ) { const { ext, dir, name, base, mime, path } = File.parsePath(filePath) @@ -224,7 +224,7 @@ export class File { */ public static async createFileOfSize( filePath: string, - size: number, + size: number ): Promise { const { dir, path } = File.parsePath(filePath) @@ -298,7 +298,7 @@ export class File { originalPath: this.originalPath, originalHref: this.originalHref, originalFileExists: this.originalFileExists, - content: this.content, + content: this.content }) } @@ -311,7 +311,7 @@ export class File { }): File { options = Options.create(options, { withContent: true, - isInternalLoad: false, + isInternalLoad: false }) if (!this.fileExists && this.content) { @@ -343,7 +343,7 @@ export class File { debug( `file %s with %s has been loaded in heap memory.`, this.base, - this.fileSize, + this.fileSize ) } @@ -361,7 +361,7 @@ export class File { }): Promise { options = Options.create(options, { withContent: true, - isInternalLoad: false, + isInternalLoad: false }) if (!this.fileExists && this.content) { @@ -414,7 +414,7 @@ export class File { debug( `file %s with %s has been loaded in heap memory.`, this.base, - this.fileSize, + this.fileSize ) } @@ -468,13 +468,13 @@ export class File { */ public copySync( path: string, - options?: { withContent?: boolean; mockedValues?: boolean }, + options?: { withContent?: boolean; mockedValues?: boolean } ): File { path = File.parsePath(path).path options = Options.create(options, { withContent: true, - mockedValues: false, + mockedValues: false }) this.loadSync({ isInternalLoad: true, withContent: options.withContent }) @@ -483,7 +483,7 @@ export class File { path, this.getContentSync(), options.mockedValues, - true, + true ).loadSync(options) } @@ -492,13 +492,13 @@ export class File { */ public async copy( path: string, - options?: { withContent?: boolean; mockedValues?: boolean }, + options?: { withContent?: boolean; mockedValues?: boolean } ): Promise { path = File.parsePath(path).path options = Options.create(options, { withContent: true, - mockedValues: false, + mockedValues: false }) await this.load({ isInternalLoad: true, withContent: options.withContent }) @@ -507,7 +507,7 @@ export class File { path, await this.getContent(), options.mockedValues, - true, + true ).load(options) } @@ -516,13 +516,13 @@ export class File { */ public moveSync( path: string, - options?: { withContent?: boolean; mockedValues?: boolean }, + options?: { withContent?: boolean; mockedValues?: boolean } ): File { path = File.parsePath(path).path options = Options.create(options, { withContent: true, - mockedValues: false, + mockedValues: false }) this.loadSync({ isInternalLoad: true, withContent: options.withContent }) @@ -531,7 +531,7 @@ export class File { path, this.getContentSync(), options.mockedValues, - false, + false ).loadSync(options) this.removeSync() @@ -544,13 +544,13 @@ export class File { */ public async move( path: string, - options?: { withContent?: boolean; mockedValues?: boolean }, + options?: { withContent?: boolean; mockedValues?: boolean } ): Promise { path = File.parsePath(path).path options = Options.create(options, { withContent: true, - mockedValues: false, + mockedValues: false }) await this.load({ isInternalLoad: true, withContent: options.withContent }) @@ -559,7 +559,7 @@ export class File { path, await this.getContent(), options.mockedValues, - false, + false ).load(options) await this.remove() @@ -626,10 +626,10 @@ export class File { */ public async setContent( content: string | Buffer, - options?: { withContent?: boolean }, + options?: { withContent?: boolean } ): Promise { options = Options.create(options, { - withContent: false, + withContent: false }) await this.load({ isInternalLoad: true, withContent: false }) @@ -654,10 +654,10 @@ export class File { */ public setContentSync( content: string | Buffer, - options?: { withContent?: boolean }, + options?: { withContent?: boolean } ): File { options = Options.create(options, { - withContent: false, + withContent: false }) this.loadSync({ isInternalLoad: true, withContent: false }) @@ -780,7 +780,7 @@ export class File { builder?: ObjectBuilderOptions }): Promise { return this.getContentAsJson(options).then(content => - new ObjectBuilder().set(content), + new ObjectBuilder().set(content) ) } @@ -798,7 +798,7 @@ export class File { * Create a readable stream of the file. */ public createReadStream( - options?: BufferEncoding | StreamOptions, + options?: BufferEncoding | StreamOptions ): ReadStream { return createReadStream(this.originalPath, options) } @@ -807,7 +807,7 @@ export class File { * Create a writable stream of the file. */ public createWriteStream( - options?: BufferEncoding | StreamOptions, + options?: BufferEncoding | StreamOptions ): WriteStream { if (!this.fileExists) { this.loadSync() diff --git a/src/helpers/Folder.ts b/src/helpers/Folder.ts index faed721..0f89e85 100644 --- a/src/helpers/Folder.ts +++ b/src/helpers/Folder.ts @@ -18,7 +18,7 @@ import { readdirSync, rmSync, statSync, - Dirent, + Dirent } from 'node:fs' import { Json } from '#src/helpers/Json' @@ -152,7 +152,7 @@ export class Folder { return (await Promise.all(stats)).reduce( (accumulator, { size }) => accumulator + size, - 0, + 0 ) } @@ -244,7 +244,7 @@ export class Folder { private static getSubFolders( folder: Folder, recursive: boolean, - pattern?: string, + pattern?: string ): Folder[] { const subFolders = [] @@ -307,7 +307,7 @@ export class Folder { originalPath: this.originalPath, folderExists: this.folderExists, isCopy: this.isCopy, - originalFolderExists: this.originalFolderExists, + originalFolderExists: this.originalFolderExists }) } @@ -322,7 +322,7 @@ export class Folder { options = Options.create(options, { withSub: true, withContent: false, - isInternalLoad: false, + isInternalLoad: false }) if (!this.folderExists) { @@ -349,7 +349,7 @@ export class Folder { this.loadSubSync( this.path, readdirSync(this.path, { withFileTypes: true }), - options.withContent, + options.withContent ) return this @@ -366,7 +366,7 @@ export class Folder { options = Options.create(options, { withSub: true, withContent: false, - isInternalLoad: false, + isInternalLoad: false }) if (!this.folderExists) { @@ -393,7 +393,7 @@ export class Folder { await this.loadSub( this.path, await promises.readdir(this.path, { withFileTypes: true }), - options.withContent, + options.withContent ) return this @@ -448,30 +448,30 @@ export class Folder { withSub?: boolean withContent?: boolean mockedValues?: boolean - }, + } ): Folder { path = Folder.parsePath(path).path options = Options.create(options, { withSub: true, withContent: false, - mockedValues: false, + mockedValues: false }) this.loadSync({ withSub: options.withSub, withContent: options.withContent, - isInternalLoad: true, + isInternalLoad: true }) const folder = new Folder(path, options.mockedValues, true).loadSync( - options, + options ) folder.files = this.files.map(f => { return f.copySync(`${folder.path}/${f.base}`, { mockedValues: options.mockedValues, - withContent: options.withContent, + withContent: options.withContent }) }) @@ -479,7 +479,7 @@ export class Folder { return f.copySync(`${folder.path}/${f.base}`, { withSub: options.withSub, withContent: options.withContent, - mockedValues: options.mockedValues, + mockedValues: options.mockedValues }) }) @@ -495,33 +495,33 @@ export class Folder { withSub?: boolean withContent?: boolean mockedValues?: boolean - }, + } ): Promise { path = Folder.parsePath(path).path options = Options.create(options, { withSub: true, withContent: false, - mockedValues: false, + mockedValues: false }) await this.load({ withSub: options.withSub, withContent: options.withContent, - isInternalLoad: true, + isInternalLoad: true }) const folder = await new Folder(path, options.mockedValues, true).load( - options, + options ) folder.files = await Promise.all( this.files.map(f => { return f.copy(`${folder.path}/${f.base}`, { mockedValues: options.mockedValues, - withContent: options.withContent, + withContent: options.withContent }) - }), + }) ) folder.folders = await Promise.all( @@ -529,9 +529,9 @@ export class Folder { return f.copy(`${folder.path}/${f.name}`, { withSub: options.withSub, mockedValues: options.mockedValues, - withContent: options.withContent, + withContent: options.withContent }) - }), + }) ) return folder @@ -546,30 +546,30 @@ export class Folder { withSub?: boolean withContent?: boolean mockedValues?: boolean - }, + } ): Folder { path = Folder.parsePath(path).path options = Options.create(options, { withSub: true, withContent: false, - mockedValues: false, + mockedValues: false }) this.loadSync({ withSub: options.withSub, withContent: options.withContent, - isInternalLoad: true, + isInternalLoad: true }) const folder = new Folder(path, options.mockedValues, true).loadSync( - options, + options ) folder.files = this.files.map(f => { return f.moveSync(`${folder.path}/${f.base}`, { mockedValues: options.mockedValues, - withContent: options.withContent, + withContent: options.withContent }) }) @@ -577,7 +577,7 @@ export class Folder { return f.moveSync(`${folder.path}/${f.name}`, { withSub: options.withSub, mockedValues: options.mockedValues, - withContent: options.withContent, + withContent: options.withContent }) }) @@ -595,33 +595,33 @@ export class Folder { withSub?: boolean withContent?: boolean mockedValues?: boolean - }, + } ): Promise { path = Folder.parsePath(path).path options = Options.create(options, { withSub: true, withContent: false, - mockedValues: false, + mockedValues: false }) await this.load({ withSub: options.withSub, withContent: options.withContent, - isInternalLoad: true, + isInternalLoad: true }) const folder = await new Folder(path, options.mockedValues, true).load( - options, + options ) folder.files = await Promise.all( this.files.map(f => { return f.move(`${folder.path}/${f.base}`, { mockedValues: options.mockedValues, - withContent: options.withContent, + withContent: options.withContent }) - }), + }) ) folder.folders = await Promise.all( @@ -629,9 +629,9 @@ export class Folder { return f.move(`${folder.path}/${f.name}`, { withSub: options.withSub, mockedValues: options.mockedValues, - withContent: options.withContent, + withContent: options.withContent }) - }), + }) ) await this.remove() @@ -719,7 +719,7 @@ export class Folder { private loadSubSync( path: string, dirents: Dirent[], - withContent: boolean, + withContent: boolean ): void { dirents.forEach(dirent => { const name = resolve(path, dirent.name) @@ -728,7 +728,7 @@ export class Folder { const folder = new Folder(name).loadSync({ withSub: true, withContent, - isInternalLoad: true, + isInternalLoad: true }) this.folders.push(folder) @@ -738,7 +738,7 @@ export class Folder { const file = new File(name).loadSync({ withContent, - isInternalLoad: true, + isInternalLoad: true }) this.files.push(file) @@ -751,7 +751,7 @@ export class Folder { private async loadSub( path: string, dirents: Dirent[], - withContent?: boolean, + withContent?: boolean ): Promise { const files = [] const folders = [] @@ -763,7 +763,7 @@ export class Folder { const folder = new Folder(name).load({ withSub: true, withContent, - isInternalLoad: true, + isInternalLoad: true }) folders.push(folder) @@ -773,7 +773,7 @@ export class Folder { const file = new File(name).load({ withContent, - isInternalLoad: true, + isInternalLoad: true }) files.push(file) diff --git a/src/helpers/HttpClient.ts b/src/helpers/HttpClient.ts index 2d85495..ceb9b3a 100644 --- a/src/helpers/HttpClient.ts +++ b/src/helpers/HttpClient.ts @@ -20,7 +20,7 @@ import type { Query, Request, Response, - RetryStrategyCallback, + RetryStrategyCallback } from '#src/types' import type { @@ -45,7 +45,7 @@ import type { DnsLookupIpVersion, BeforeRedirectHook, StringifyJsonFunction, - CreateConnectionFunction, + CreateConnectionFunction } from 'got' export class HttpClientBuilder { @@ -897,14 +897,14 @@ export class HttpClientBuilder { retryAfter, attemptCount, retryOptions, - computedValue, + computedValue }) => { return strategy(error, attemptCount, { error, retryAfter, attemptCount, retryOptions, - computedValue, + computedValue }) } @@ -1004,7 +1004,7 @@ export class HttpClientBuilder { * Set pagination options. */ public pagination( - options: PaginationOptions, + options: PaginationOptions ): HttpClientBuilder { this.options.pagination = options @@ -1103,7 +1103,7 @@ export class HttpClientBuilder { public patch( url?: string | URL, body?: Response, - options: Request = {}, + options: Request = {} ) { return this.method('PATCH') .url(url || options.url || this.options.url) @@ -1170,7 +1170,7 @@ export class HttpClient { public static post( url?: string | URL, body?: Body, - options?: Request, + options?: Request ) { return this._builder.post(url, body, options) } @@ -1181,7 +1181,7 @@ export class HttpClient { public static put( url?: string | URL, body?: Body, - options?: Request, + options?: Request ) { return this._builder.put(url, body, options) } @@ -1192,7 +1192,7 @@ export class HttpClient { public static patch( url?: string | URL, body?: Body, - options?: Request, + options?: Request ) { return this._builder.patch(url, body, options) } diff --git a/src/helpers/Is.ts b/src/helpers/Is.ts index ae77834..49d4e0f 100644 --- a/src/helpers/Is.ts +++ b/src/helpers/Is.ts @@ -10,7 +10,7 @@ import kindOf from 'kind-of' import { isIP } from 'node:net' -import { Uuid, Exception } from '#src' +import { File, Uuid, Exception } from '#src' import { isCep, isCnpj, isCpf } from 'validator-brazil' export class Is { @@ -33,30 +33,50 @@ export class Is { /** * Verify if the current platform is Linux. */ - public static Linux() { + public static Linux(): boolean { return process.platform === 'linux' } /** * Verify if the current platform is Mac. */ - public static Mac() { + public static Mac(): boolean { return process.platform === 'darwin' } /** * Verify if the current platform is Windows. */ - public static Windows() { + public static Windows(): boolean { return process.platform === 'win32' } + /** + * Verify if file path or File instance is a + * module or not. + */ + public static Module(value: any): boolean { + if (value instanceof File) { + return Is.Module(value.extension) + } + + if (!value || !Is.String(value)) { + return false + } + + if (value.includes('.js') || value.includes('.ts')) { + return true + } + + return false + } + /** * Verify if is valid Uuid. */ public static Uuid( value: string, - options?: { prefix?: string; ignorePrefix?: boolean }, + options?: { prefix?: string; ignorePrefix?: boolean } ): boolean { return Uuid.verify(value, options) } diff --git a/src/helpers/Json.ts b/src/helpers/Json.ts index 123e4a6..d3abd85 100644 --- a/src/helpers/Json.ts +++ b/src/helpers/Json.ts @@ -30,7 +30,7 @@ export class ObjectBuilder { ignoreNull: false, ignoreUndefined: true, defaultValue: null, - referencedValues: false, + referencedValues: false }) this.object = {} @@ -133,7 +133,7 @@ export class ObjectBuilder { * Execute some operation for each key of the object. */ public forEachKey( - closure: (key: string, index?: number, array?: string[]) => T, + closure: (key: string, index?: number, array?: string[]) => T ): T[] { return this.keys().map(closure) } @@ -142,7 +142,7 @@ export class ObjectBuilder { * Execute some operation for each value of the object. */ public forEachValue( - closure: (value: T, index?: number, array?: T[]) => K, + closure: (value: T, index?: number, array?: T[]) => K ): K[] { return this.values().map(closure) } @@ -151,7 +151,7 @@ export class ObjectBuilder { * Execute some operation for each entry of the object. */ public forEachEntry( - closure: (value: [string, T], index?: number, array?: [string, T][]) => K, + closure: (value: [string, T], index?: number, array?: [string, T][]) => K ): K[] { return this.entries().map(closure) } @@ -280,7 +280,7 @@ export class Json { */ public static parse( text: string, - reviver?: (this: any, key: string, value: any) => any, + reviver?: (this: any, key: string, value: any) => any ): any { try { return JSON.parse(text, reviver) @@ -300,7 +300,7 @@ export class Json { target[key] = value return true - }, + } }) } @@ -309,7 +309,7 @@ export class Json { */ public static fillable( data: Record, - keys: string[], + keys: string[] ): Record { return keys.reduce((previous, key) => { if (data[key]) { @@ -326,7 +326,7 @@ export class Json { public static get( object: T, key: string, - defaultValue: any = undefined, + defaultValue: any = undefined ): T | undefined { if (key === '' && object) { return object diff --git a/src/helpers/Module.ts b/src/helpers/Module.ts index 17df446..2d0dab9 100644 --- a/src/helpers/Module.ts +++ b/src/helpers/Module.ts @@ -30,7 +30,7 @@ export class Module { debug( 'not found a default module, picking the first one %s from %s', exported[0], - exported, + exported ) return module[exported[0]] @@ -50,7 +50,7 @@ export class Module { */ public static async getWithAlias( module: any | Promise, - subAlias: string, + subAlias: string ): Promise<{ alias: string; module: any }> { module = await Module.get(module) @@ -87,7 +87,7 @@ export class Module { */ public static async getAllWithAlias( modules: any[], - subAlias: string, + subAlias: string ): Promise<{ alias: string; module: any }[]> { const promises = modules.map(m => Module.getWithAlias(m, subAlias)) @@ -108,7 +108,7 @@ export class Module { */ public static async getFromWithAlias( path: string, - subAlias: string, + subAlias: string ): Promise<{ alias: string; module: any }> { const module = await Module.import(path) @@ -131,7 +131,7 @@ export class Module { */ public static async getAllFromWithAlias( path: string, - subAlias: string, + subAlias: string ): Promise<{ alias: string; module: any }[]> { const files = await Module.getAllJSFilesFrom(path) @@ -209,7 +209,7 @@ export class Module { 'trying to resolve path: %s, with parent URL: %s and query params: %s', path, meta, - queries, + queries ) return import.meta @@ -222,7 +222,7 @@ export class Module { */ public static createDirname( url = import.meta.url, - setInGlobal = false, + setInGlobal = false ): string { const __dirname = dirname(Module.createFilename(url, false)) @@ -238,7 +238,7 @@ export class Module { */ public static createFilename( url = import.meta.url, - setInGlobal = false, + setInGlobal = false ): string { const __filename = fileURLToPath(url) @@ -254,7 +254,7 @@ export class Module { */ public static createRequire( url = import.meta.url, - setInGlobal = false, + setInGlobal = false ): NodeRequire { const require = createRequire(url) diff --git a/src/helpers/Number.ts b/src/helpers/Number.ts index acc4db2..59c8ca7 100644 --- a/src/helpers/Number.ts +++ b/src/helpers/Number.ts @@ -23,7 +23,7 @@ export class Number { */ public static getKmRadius( centerCord: { latitude: number; longitude: number }, - pointCord: { latitude: number; longitude: number }, + pointCord: { latitude: number; longitude: number } ): number { const deg2rad = deg => deg * (Math.PI / 180) diff --git a/src/helpers/Options.ts b/src/helpers/Options.ts index 75c9597..d2493c9 100644 --- a/src/helpers/Options.ts +++ b/src/helpers/Options.ts @@ -35,7 +35,7 @@ export class Options { */ public static whenDefined( statement: T, - closure: (statement: T) => K, + closure: (statement: T) => K ): K { if (!Is.Defined(statement)) { return diff --git a/src/helpers/Parser.ts b/src/helpers/Parser.ts index 9b8041f..b9b74c6 100644 --- a/src/helpers/Parser.ts +++ b/src/helpers/Parser.ts @@ -35,7 +35,7 @@ export class Parser { separator?: string pairSeparator?: string lastSeparator?: string - }, + } ): string { if (values.length === 0) { return '' @@ -51,7 +51,7 @@ export class Parser { const normalized = Options.create(options, { separator: ', ', - lastSeparator: ' and ', + lastSeparator: ' and ' }) return ( @@ -121,7 +121,7 @@ export class Parser { */ public static sizeToByte( value: number, - options?: bytes.BytesOptions, + options?: bytes.BytesOptions ): string { return bytes.format(value, options) } @@ -190,7 +190,7 @@ export class Parser { host: null, port: null, database: matcher[8], - options: {}, + options: {} } if (matcher[5].includes(',')) { @@ -267,7 +267,7 @@ export class Parser { */ public static objectToBuilder( object: Record, - options: ObjectBuilderOptions = {}, + options: ObjectBuilderOptions = {} ): ObjectBuilder { const objectBuilder = new ObjectBuilder(options) @@ -283,7 +283,7 @@ export class Parser { */ public static arrayObjectToArrayBuilder( objects: Record[], - options: ObjectBuilderOptions = {}, + options: ObjectBuilderOptions = {} ): ObjectBuilder[] { return objects.map(object => Parser.objectToBuilder(object, options)) } diff --git a/src/helpers/Path.ts b/src/helpers/Path.ts index db62c08..1510b05 100644 --- a/src/helpers/Path.ts +++ b/src/helpers/Path.ts @@ -50,6 +50,7 @@ export class Path { logs: 'storage/logs', tests: 'tests', stubs: 'tests/stubs', + fixtures: 'tests/fixtures' } /** @@ -422,6 +423,22 @@ export class Path { return this } + /** + * Return the fixtures' path of your project. + */ + public static fixtures(subPath = sep): string { + return this.pwd(this.dirs.fixtures + sep + normalize(subPath)) + } + + /** + * Set the directory of fixtures folder. + */ + public static setFixtures(directory: string): typeof Path { + this.dirs.fixtures = directory + + return this + } + /** * Return the http path of your project. */ diff --git a/src/helpers/Route.ts b/src/helpers/Route.ts index 5f5e0b9..0ada067 100644 --- a/src/helpers/Route.ts +++ b/src/helpers/Route.ts @@ -58,7 +58,7 @@ export class Route { queryString .split('&') .forEach(queries => - queryNames.push(decodeURIComponent(queries.split('=')[0])), + queryNames.push(decodeURIComponent(queries.split('=')[0])) ) return queryNames @@ -69,7 +69,7 @@ export class Route { */ public static getParamsValue( routeWithParams: string, - routeWithValues: string, + routeWithValues: string ): any { routeWithParams = this.removeQueryParams(routeWithParams) routeWithValues = this.removeQueryParams(routeWithValues) @@ -87,7 +87,7 @@ export class Route { if (!param.startsWith(':')) return params[decodeURIComponent(param.replace(':', ''))] = decodeURIComponent( - routeWithValuesArray[i], + routeWithValuesArray[i] ) }) diff --git a/src/helpers/String.ts b/src/helpers/String.ts index 4a53160..7d358c6 100644 --- a/src/helpers/String.ts +++ b/src/helpers/String.ts @@ -52,7 +52,7 @@ export class String { public static toSnakeCase(value: string, capitalize?: boolean): string { if (capitalize) { return changeCase.snakeCase(value, { - transform: changeCase.capitalCaseTransform, + transform: changeCase.capitalCaseTransform }) } @@ -90,7 +90,7 @@ export class String { public static toDotCase(value: string, capitalize?: boolean): string { if (capitalize) { return changeCase.dotCase(value, { - transform: changeCase.capitalCaseTransform, + transform: changeCase.capitalCaseTransform }) } @@ -134,7 +134,7 @@ export class String { */ public static ordinalize(value: string | number): string { const transformedValue = Math.abs( - typeof value === 'string' ? parseInt(value) : value, + typeof value === 'string' ? parseInt(value) : value ) if (!Number.isFinite(transformedValue) || Number.isNaN(transformedValue)) { diff --git a/src/helpers/Uuid.ts b/src/helpers/Uuid.ts index bbd3319..9421636 100644 --- a/src/helpers/Uuid.ts +++ b/src/helpers/Uuid.ts @@ -17,7 +17,7 @@ export class Uuid { */ public static verify( token: string, - options: { prefix?: string; ignorePrefix?: boolean } = {}, + options: { prefix?: string; ignorePrefix?: boolean } = {} ): boolean { if (!token) { return false diff --git a/src/types/PathDirs.ts b/src/types/PathDirs.ts index eceaf1c..ad0a739 100644 --- a/src/types/PathDirs.ts +++ b/src/types/PathDirs.ts @@ -42,4 +42,5 @@ export interface PathDirs { logs?: string tests?: string stubs?: string + fixtures?: string } diff --git a/src/types/http-client/RetryStrategyCallback.ts b/src/types/http-client/RetryStrategyCallback.ts index 148ce38..7edf014 100644 --- a/src/types/http-client/RetryStrategyCallback.ts +++ b/src/types/http-client/RetryStrategyCallback.ts @@ -12,5 +12,5 @@ import type { RequestError, RetryObject } from 'got' export type RetryStrategyCallback = ( error: RequestError, execCount: number, - retryObject: RetryObject, + retryObject: RetryObject ) => number | Promise diff --git a/src/types/index.ts b/src/types/index.ts index aca1aa7..1145641 100644 --- a/src/types/index.ts +++ b/src/types/index.ts @@ -13,7 +13,7 @@ import type { RetryObject, CacheOptions, ToughCookieJar, - PromiseCookieJar, + PromiseCookieJar } from 'got' export type { @@ -22,7 +22,7 @@ export type { RetryObject, CacheOptions, ToughCookieJar, - PromiseCookieJar, + PromiseCookieJar } export * from '#src/types/Merge' diff --git a/tests/stubs/config/app.ts b/tests/stubs/config/app.ts index 86f6ae4..787c82f 100644 --- a/tests/stubs/config/app.ts +++ b/tests/stubs/config/app.ts @@ -8,5 +8,5 @@ */ export default { - name: 'Athenna', + name: 'Athenna' } diff --git a/tests/unit/CleanTest.ts b/tests/unit/CleanTest.ts index 6d5f567..622ed64 100644 --- a/tests/unit/CleanTest.ts +++ b/tests/unit/CleanTest.ts @@ -23,7 +23,7 @@ export default class CleanTest { nullValue: null, undefinedValue: undefined, subObject: { joao: 'joao', array: [null] }, - subArray: [null, 1, { joao: 'joao', lenon: null }, {}, [], ['hey', null]], + subArray: [null, 1, { joao: 'joao', lenon: null }, {}, [], ['hey', null]] } } @@ -43,7 +43,7 @@ export default class CleanTest { 2, 3, { joao: 'joao', lenon: null }, - ['hey', null], + ['hey', null] ]) } @@ -56,7 +56,7 @@ export default class CleanTest { 2, 3, { joao: 'joao' }, - ['hey'], + ['hey'] ]) } @@ -69,7 +69,7 @@ export default class CleanTest { emptyArray: [], emptyObject: {}, subObject: { joao: 'joao', array: [null] }, - subArray: [null, 1, { joao: 'joao', lenon: null }, {}, [], ['hey', null]], + subArray: [null, 1, { joao: 'joao', lenon: null }, {}, [], ['hey', null]] }) } @@ -80,7 +80,7 @@ export default class CleanTest { assert.deepEqual(Clean.cleanObject(object, { removeEmpty: true }), { key: 'value', subObject: { joao: 'joao', array: [null] }, - subArray: [null, 1, { joao: 'joao', lenon: null }, {}, [], ['hey', null]], + subArray: [null, 1, { joao: 'joao', lenon: null }, {}, [], ['hey', null]] }) } @@ -91,7 +91,7 @@ export default class CleanTest { assert.deepEqual(Clean.cleanObject(object, { removeEmpty: true, recursive: true }), { key: 'value', subObject: { joao: 'joao' }, - subArray: [1, { joao: 'joao' }, ['hey']], + subArray: [1, { joao: 'joao' }, ['hey']] }) } } diff --git a/tests/unit/CollectionTest.ts b/tests/unit/CollectionTest.ts index 50f0d6b..2cc8790 100644 --- a/tests/unit/CollectionTest.ts +++ b/tests/unit/CollectionTest.ts @@ -29,9 +29,9 @@ export default class CollectionTest { public async shouldBeAbleToExecuteTheToResourceMethodInsideObjectsOfCollections({ assert }: Context) { const models = [ { - toResource: () => ({ id: 1 }), + toResource: () => ({ id: 1 }) }, - { toResource: criterias => criterias }, + { toResource: criterias => criterias } ] assert.deepEqual(models.toResource({ id: 2 }), [{ id: 1 }, { id: 2 }]) diff --git a/tests/unit/ExceptionTest.ts b/tests/unit/ExceptionTest.ts index 0cc2124..cba8516 100644 --- a/tests/unit/ExceptionTest.ts +++ b/tests/unit/ExceptionTest.ts @@ -28,7 +28,7 @@ export default class ExceptionTest { const exception = new Error('My custom instance error').toAthennaException({ status: 0, code: 'EXCEPTION', - name: 'Exception', + name: 'Exception' }) const errorJson = exception.toJSON() @@ -66,7 +66,7 @@ export default class ExceptionTest { status, message: content, code: 'E_RUNTIME_EXCEPTION', - help: 'Restart your computer, works always. 👍', + help: 'Restart your computer, works always. 👍' }) } } diff --git a/tests/unit/ExecTest.ts b/tests/unit/ExecTest.ts index eff0ed8..32477a1 100644 --- a/tests/unit/ExecTest.ts +++ b/tests/unit/ExecTest.ts @@ -67,7 +67,7 @@ export default class ExecTest { while (i < 10) { collection.push({ joao: 'lenon', - hello: 'world', + hello: 'world' }) i++ @@ -76,7 +76,7 @@ export default class ExecTest { const paginatedData = Exec.pagination(collection, collection.length + 1, { page: 0, limit: 10, - resourceUrl: 'https://my-api.com/products', + resourceUrl: 'https://my-api.com/products' }) assert.deepEqual(paginatedData.data, collection) @@ -85,13 +85,13 @@ export default class ExecTest { totalItems: 11, totalPages: 2, currentPage: 0, - itemsPerPage: 10, + itemsPerPage: 10 }) assert.deepEqual(paginatedData.links, { first: 'https://my-api.com/products?limit=10', previous: 'https://my-api.com/products?page=0&limit=10', next: 'https://my-api.com/products?page=1&limit=10', - last: 'https://my-api.com/products?page=2&limit=10', + last: 'https://my-api.com/products?page=2&limit=10' }) } diff --git a/tests/unit/FakeApiTest.ts b/tests/unit/FakeApiTest.ts index de4b20a..6d691ef 100644 --- a/tests/unit/FakeApiTest.ts +++ b/tests/unit/FakeApiTest.ts @@ -84,7 +84,7 @@ export default class FakeApiTest { assert.equal(responseOne.statusCode, 200) assert.deepEqual(responseOne.body, [ { id: 1, name: 'Robson Trasel' }, - { id: 2, name: 'Victor Tesoura' }, + { id: 2, name: 'Victor Tesoura' } ]) const responseTwo = await HttpClient.get('http://localhost:8989/example', options) diff --git a/tests/unit/FileTest.ts b/tests/unit/FileTest.ts index f21f03c..07c7965 100644 --- a/tests/unit/FileTest.ts +++ b/tests/unit/FileTest.ts @@ -190,7 +190,7 @@ export default class FileTest { @Test() public async shouldBeAbleToMakeACopyOfTheFile({ assert }: Context) { const copyOfBigFile = await this.bigFile.copy(Path.storage('files/testing/copy-big-file.txt'), { - withContent: false, + withContent: false }) assert.isDefined(await File.exists(this.bigFile.path)) @@ -209,7 +209,7 @@ export default class FileTest { @Test() public async shouldBeAbleToMoveTheFile({ assert }: Context) { const moveOfBigFile = await this.bigFile.move(Path.storage('testing/move-big-file.txt'), { - withContent: false, + withContent: false }) assert.isFalse(await File.exists(this.bigFile.path)) diff --git a/tests/unit/FolderTest.ts b/tests/unit/FolderTest.ts index 1035f9f..f10144e 100644 --- a/tests/unit/FolderTest.ts +++ b/tests/unit/FolderTest.ts @@ -150,7 +150,7 @@ export default class FolderTest { public async shouldBeAbleToMakeACopyOfFolder({ assert }: Context) { const copyOfBigFolder = await this.bigFolder.copy(Path.storage('folders/testing/copy-big-folder'), { withSub: true, - withContent: false, + withContent: false }) this.bigFolder.removeSync() @@ -167,7 +167,7 @@ export default class FolderTest { assert.isDefined(copyOfBigFolder.folders[0].files[0].name) const copyOfNoExistFolder = await this.nonexistentFolder.copy( - Path.storage('folders/testing/copy-non-existent-folder'), + Path.storage('folders/testing/copy-non-existent-folder') ) assert.isTrue(await Folder.exists(copyOfNoExistFolder.path)) @@ -177,7 +177,7 @@ export default class FolderTest { public async shouldBeAbleToMakeACopyInSyncModeOfTheFolder({ assert }: Context) { const copyOfBigFolder = this.bigFolder.copySync(Path.storage('folders/testing/copy-big-folder'), { withSub: true, - withContent: false, + withContent: false }) this.bigFolder.removeSync() @@ -194,7 +194,7 @@ export default class FolderTest { assert.isDefined(copyOfBigFolder.folders[0].files[0].name) const copyOfNoExistFolder = this.nonexistentFolder.copySync( - Path.storage('folders/testing/copy-non-existent-folder'), + Path.storage('folders/testing/copy-non-existent-folder') ) assert.isTrue(await Folder.exists(copyOfNoExistFolder.path)) @@ -204,7 +204,7 @@ export default class FolderTest { public async shouldBeAbleToMoveTheFolder({ assert }: Context) { const moveOfBigFolder = await this.bigFolder.move(Path.storage('folders/testing/move-big-folder'), { withSub: true, - withContent: false, + withContent: false }) assert.isFalse(await Folder.exists(this.bigFolder.path)) @@ -220,7 +220,7 @@ export default class FolderTest { assert.isDefined(moveOfBigFolder.folders[0].files[0].name) const moveOfNoExistFolder = await this.nonexistentFolder.move( - Path.storage('folders/testing/move-non-existent-folder'), + Path.storage('folders/testing/move-non-existent-folder') ) assert.isFalse(await Folder.exists(this.nonexistentFolder.path)) @@ -231,7 +231,7 @@ export default class FolderTest { public async shouldBeAbleToMoveTheFolderInSyncMode({ assert }: Context) { const moveOfBigFolder = await this.bigFolder.moveSync(Path.storage('folders/testing/move-big-folder'), { withSub: true, - withContent: false, + withContent: false }) assert.isFalse(await Folder.exists(this.bigFolder.path)) @@ -247,7 +247,7 @@ export default class FolderTest { assert.isDefined(moveOfBigFolder.folders[0].files[0].name) const moveOfNoExistFolder = this.nonexistentFolder.moveSync( - Path.storage('folders/testing/move-non-existent-folder'), + Path.storage('folders/testing/move-non-existent-folder') ) assert.isFalse(await Folder.exists(this.nonexistentFolder.path)) diff --git a/tests/unit/HttpClientTest.ts b/tests/unit/HttpClientTest.ts index f15ba3d..351e5dc 100644 --- a/tests/unit/HttpClientTest.ts +++ b/tests/unit/HttpClientTest.ts @@ -62,7 +62,7 @@ export default class HttpClientTest { @Test() public async shouldBeOnlyBeAbleToSetOptionsInBuilderAndReuseInNextRequestsUsingTheSetBuildMethod({ - assert, + assert }: Context) { await HttpClient.builder().responseType('json').url('/users').get().json() @@ -294,7 +294,7 @@ export default class HttpClientTest { @Test() public async shouldBeAbleToSetupBeforeRetryHooksForRequests({ assert }: Context) { const builder = HttpClient.builder().setBeforeRetryHook((error, _retryCount) => - assert.deepEqual(error.name, 'ERR_NON_2XX_3XX_RESPONSE'), + assert.deepEqual(error.name, 'ERR_NON_2XX_3XX_RESPONSE') ) try { diff --git a/tests/unit/IsTest.ts b/tests/unit/IsTest.ts index fba561d..a81dc78 100644 --- a/tests/unit/IsTest.ts +++ b/tests/unit/IsTest.ts @@ -7,10 +7,21 @@ * file that was distributed with this source code. */ -import { Is, Exception } from '#src' +import { Is, File, Exception } from '#src' import { Test, type Context } from '@athenna/test' export default class IsTest { + @Test() + public async shouldVerifyIfIsAValidModule({ assert }: Context) { + assert.isFalse(Is.Module('')) + assert.isFalse(Is.Module('Hello')) + assert.isTrue(Is.Module('.js')) + assert.isTrue(Is.Module('.ts')) + assert.isTrue(Is.Module(Path.src('helpers/Clean.js'))) + assert.isTrue(Is.Module(Path.src('helpers/Clean.ts'))) + assert.isTrue(Is.Module(new File(Path.src('helpers/Clean.ts')))) + } + @Test() public async shouldVerifyIfIsAValidJsonString({ assert }: Context) { assert.isFalse(Is.Json('')) @@ -194,7 +205,7 @@ export default class IsTest { assert.isTrue( Is.Function(function test() { return '' - }), + }) ) } @@ -206,7 +217,7 @@ export default class IsTest { assert.isFalse( Is.Async(function test() { return '' - }), + }) ) assert.isTrue(Is.Async(async () => '')) assert.isTrue(Is.Async(() => new Promise(resolve => resolve))) @@ -235,11 +246,11 @@ export default class IsTest { public async shouldVerifyIsIsAValidArrayOfObjects({ assert }: Context) { const data = [ { - hello: 'hello', + hello: 'hello' }, { - hello: 'hello', - }, + hello: 'hello' + } ] assert.isFalse(Is.ArrayOfObjects([])) diff --git a/tests/unit/JsonTest.ts b/tests/unit/JsonTest.ts index 4fb52dd..74dcf78 100644 --- a/tests/unit/JsonTest.ts +++ b/tests/unit/JsonTest.ts @@ -15,7 +15,7 @@ export default class JsonTest { public async shouldReturnADeepCopyFromObject({ assert }: Context) { const object = { test: 'hello', - hello: () => 'hy', + hello: () => 'hy' } const objectCopy = Json.copy(object) @@ -54,7 +54,7 @@ export default class JsonTest { public async shouldCleanDataObjectRemovingAllKeysThatAreNotInKeyArray({ assert }: Context) { const data = { hello: 'hello', - world: 'world', + world: 'world' } assert.deepEqual(Json.fillable(data, ['world']), { world: 'world' }) @@ -65,7 +65,7 @@ export default class JsonTest { public async shouldBeAbleToObserveChangesOfAnObject({ assert }: Context) { const object = { joao: 'lenon', - hello: 'world', + hello: 'world' } const objectProxy = Json.observeChanges( @@ -78,7 +78,7 @@ export default class JsonTest { }, 1, 2, - 3, + 3 ) objectProxy.joao = 'oi' @@ -92,10 +92,10 @@ export default class JsonTest { hello: { world: { value: { - hello: 'Hello World!', - }, - }, - }, + hello: 'Hello World!' + } + } + } } const value = Json.get(object, 'hello.world.value.hello') @@ -138,16 +138,16 @@ export default class JsonTest { details: { car: { color: 'white', - name: 'BMW E46 M3', + name: 'BMW E46 M3' }, job: 'Software Engineer', - favoriteColor: 'black', + favoriteColor: 'black' }, createdAt: '2000-12-09T00:00:00.000Z', updatedAt: '2022-12-09T00:00:00.000Z', deletedAt: null, willSetDefaultOne: 'Hello', - willSetDefaultTwo: 'Hello', + willSetDefaultTwo: 'Hello' }) const ignores = Json.builder({ ignoreNull: true, ignoreUndefined: true, defaultValue: 'Global' }) @@ -161,7 +161,7 @@ export default class JsonTest { name: 'Global', email: 'Global', age: 0, - createdAt: '2000-12-09T00:00:00.000Z', + createdAt: '2000-12-09T00:00:00.000Z' }) } @@ -186,7 +186,7 @@ export default class JsonTest { assert.equal(builder.get('deletedAt', new Date('2022-12-09').toISOString()), null) assert.equal( builder.get('deletedAt.notFound', new Date('2022-12-09').toISOString()), - new Date('2022-12-09').toISOString(), + new Date('2022-12-09').toISOString() ) } @@ -248,7 +248,7 @@ export default class JsonTest { assert.deepEqual(me, { name: 'João Lenon', email: 'lenon@athenna.io', - age: 22, + age: 22 }) } @@ -293,7 +293,7 @@ export default class JsonTest { assert.deepEqual(entries, [ ['name', 'João Lenon'], ['email', 'lenon@athenna.io'], - ['age', 22], + ['age', 22] ]) } @@ -307,7 +307,7 @@ export default class JsonTest { assert.deepEqual(builder.entries(), [ ['name', 'João Lenon'], ['email', 'lenon@athenna.io'], - ['age', 22], + ['age', 22] ]) } @@ -345,7 +345,7 @@ export default class JsonTest { assert.deepEqual(entries, [ ['NAME', 'João Lenon'], ['EMAIL', 'lenon@athenna.io'], - ['AGE', 22], + ['AGE', 22] ]) } } diff --git a/tests/unit/NumberTest.ts b/tests/unit/NumberTest.ts index 2af18dc..b52d6ff 100644 --- a/tests/unit/NumberTest.ts +++ b/tests/unit/NumberTest.ts @@ -23,11 +23,11 @@ export default class NumberTest { public async shouldGetKmRadiusBetweenTwoCoordinates({ assert }: Context) { const first = Number.getKmRadius( { latitude: -25503207, longitude: -545390592 }, - { latitude: -25503207, longitude: -545390592 }, + { latitude: -25503207, longitude: -545390592 } ) const second = Number.getKmRadius( { latitude: -25503207, longitude: -545390592 }, - { latitude: -254957901, longitude: -545671577 }, + { latitude: -254957901, longitude: -545671577 } ) assert.equal(first, 0) diff --git a/tests/unit/OptionsTest.ts b/tests/unit/OptionsTest.ts index 78ba212..b2af2e3 100644 --- a/tests/unit/OptionsTest.ts +++ b/tests/unit/OptionsTest.ts @@ -16,7 +16,7 @@ export default class OptionsTest { const api = (options: { name?: string; age?: number } = {}) => { options = Options.create(options, { name: 'lenon', - age: 22, + age: 22 }) return options @@ -35,7 +35,7 @@ export default class OptionsTest { age: 22, getAge() { return this.age - }, + } } const closure = Options.bind(object, 'getAge') diff --git a/tests/unit/ParserTest.ts b/tests/unit/ParserTest.ts index cc3668c..8e19413 100644 --- a/tests/unit/ParserTest.ts +++ b/tests/unit/ParserTest.ts @@ -38,16 +38,16 @@ export default class ParserTest { assert.equal( Parser.arrayToString(['1', '2', '3', '4', '5', '6'], { separator: '|', - lastSeparator: '|', + lastSeparator: '|' }), - '1|2|3|4|5|6', + '1|2|3|4|5|6' ) assert.equal( Parser.arrayToString(['1', '2'], { - pairSeparator: '-', + pairSeparator: '-' }), - '1-2', + '1-2' ) } @@ -55,7 +55,7 @@ export default class ParserTest { public async shouldParseJsonToFormData({ assert }: Context) { const json = { name: 'lenon', - email: 'lenonSec7@gmail.com', + email: 'lenonSec7@gmail.com' } const formData = Parser.jsonToFormData(json) @@ -71,7 +71,7 @@ export default class ParserTest { assert.deepEqual(json, { name: 'lenon', - email: 'lenonSec7@gmail.com', + email: 'lenonSec7@gmail.com' }) } @@ -150,7 +150,7 @@ export default class ParserTest { assert.deepEqual(connectionObject.options, { paramOne: '1', paramTwo: '2', - paramThree: '3', + paramThree: '3' }) // connection object to database url @@ -195,7 +195,7 @@ export default class ParserTest { assert.equal(connectionObject.database, 'postgres') assert.deepEqual(connectionObject.options, { options: '10', - test: '10', + test: '10' }) // connection object to database url diff --git a/tests/unit/PathTest.ts b/tests/unit/PathTest.ts index ddc17ec..9608f37 100644 --- a/tests/unit/PathTest.ts +++ b/tests/unit/PathTest.ts @@ -185,6 +185,7 @@ export default class PathTest { .setLogs('build/storage/logs') .setTests('build/tests') .setStubs('build/tests/stubs') + .setFixtures('build/tests/fixtures') assert.isTrue(Path.bin().endsWith(`build${sep}bin`)) assert.isTrue(Path.src().endsWith(`build${sep}src`)) @@ -219,12 +220,13 @@ export default class PathTest { assert.isTrue(Path.logs().endsWith(`build${sep}storage${sep}logs`)) assert.isTrue(Path.tests().endsWith(`build${sep}tests`)) assert.isTrue(Path.stubs().endsWith(`build${sep}tests${sep}stubs`)) + assert.isTrue(Path.fixtures().endsWith(`build${sep}tests${sep}fixtures`)) } @Test() public shouldBeAbleToMergeCustomDirectoriesWithDefaults({ assert }: Context) { Path.mergeDirs({ - app: 'build/app', + app: 'build/app' }) assert.isTrue(Path.bin().endsWith('bin')) diff --git a/tests/unit/RouteTest.ts b/tests/unit/RouteTest.ts index 5f40c26..aa33cc7 100644 --- a/tests/unit/RouteTest.ts +++ b/tests/unit/RouteTest.ts @@ -34,7 +34,7 @@ export default class RouteTest { assert.deepEqual(Route.getQueryParamsValue(path), { page: '1', limit: '10', - created_at: '1995-12-17T03:24:00', + created_at: '1995-12-17T03:24:00' }) } @@ -60,7 +60,7 @@ export default class RouteTest { assert.deepEqual(Route.getParamsValue(pathWithParams, pathWithValues), { id: '1', - post_id: '2', + post_id: '2' }) }