Skip to content

Commit

Permalink
feat(helpers): improve options and types
Browse files Browse the repository at this point in the history
  • Loading branch information
jlenon7 committed Aug 29, 2023
1 parent a49e3ad commit 0bdfcee
Show file tree
Hide file tree
Showing 14 changed files with 102 additions and 61 deletions.
4 changes: 2 additions & 2 deletions src/exceptions/InvalidUuidException.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ export class InvalidUuidException extends Exception {
public constructor(value: string) {
super({
code: 'E_INVALID_UUID',
help: 'Use a valid uuid instead.',
message: `The value ${value} is not a valid uuid.`,
help: 'Use a valid UUID instead.',
message: `The value ${value} is not a valid UUID.`,
})
}
}
8 changes: 2 additions & 6 deletions src/helpers/Exec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,19 +84,15 @@ export class Exec {
/**
* Download an archive to a determined path.
*/
public static async download(
name: string,
path: string,
url: string,
): Promise<File> {
public static async download(path: string, url: string): Promise<File> {
return new Promise((resolve, reject) => {
const callback = response => {
const data = new Transform()

response.on('data', chunk => data.push(chunk))

response.on('end', function () {
resolve(new File(`${path}/${name}`, data.read()).loadSync())
resolve(new File(path, data.read()).loadSync())
})

response.on('error', error => reject(error))
Expand Down
63 changes: 33 additions & 30 deletions src/helpers/HttpClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,17 +12,24 @@ import CacheableLookup from 'cacheable-lookup'

import { Is } from '#src/helpers/Is'
import { Json } from '#src/helpers/Json'

import type { Store } from 'keyv'
import type { ClientHttp2Session } from 'http2'
import type { Body, Query, ReqOptions, RetryStrategyCallback } from '#src/types'
import type {
Body,
Query,
Request,
Response,
RetryStrategyCallback,
} from '#src/types'

import type {
Hooks,
Delays,
Agents,
Method,
Request,
InitHook,
Request as GotRequest,
RetryOptions,
ResponseType,
HttpsOptions,
Expand All @@ -45,16 +52,16 @@ export class HttpClientBuilder {
/**
* Got options used to make the request.
*/
private options: ReqOptions
private options: Request

public constructor(options: ReqOptions = {}) {
public constructor(options: Request = {}) {
this.options = options
}

/**
* Return the options of the client builder.
*/
public getOptions(): ReqOptions {
public getOptions(): Request {
return Json.copy(this.options)
}

Expand Down Expand Up @@ -330,7 +337,7 @@ export class HttpClientBuilder {
* const { HttpsAgent } = HttpAgent
*
* await HttpClient.builder()
* .agent({ http: new HttpAgent(), https: new HttpsAgent() }
* .agent({ http: new HttpAgent(), https: new HttpsAgent() })
* .get('https://sindresorhus.com')
* ```
*/
Expand Down Expand Up @@ -1034,7 +1041,7 @@ export class HttpClientBuilder {
/**
* Set the merge options.
*/
public mergeOptions(options: ReqOptions): HttpClientBuilder {
public mergeOptions(options: Request): HttpClientBuilder {
this.options = { ...this.options, ...options }

return this
Expand All @@ -1043,28 +1050,28 @@ export class HttpClientBuilder {
/**
* Execute the request and return as stream.
*/
public stream(options: ReqOptions = {}): Request {
public stream(options: Request = {}): GotRequest {
return got.stream({ ...this.options, ...options } as any)
}

/**
* Execute the request and return paginated data.
*/
public paginate<T = any>(options: ReqOptions = {}): AsyncIterableIterator<T> {
public paginate<T = any>(options: Request = {}): AsyncIterableIterator<T> {
return got.paginate({ ...this.options, ...options } as any)
}

/**
* Execute the request using all the options defined.
*/
public request<T = any>(options: ReqOptions = {}) {
public request<T = any>(options: Request = {}): Response<T> {
return got<T>({ ...this.options, ...options } as any)
}

/**
* Make a GET request.
*/
public get<T = any>(url?: string | URL, options: ReqOptions = {}) {
public get<T = any>(url?: string | URL, options: Request = {}) {
return this.method('GET')
.url(url || options.url || this.options.url)
.request<T>(options)
Expand All @@ -1073,11 +1080,7 @@ export class HttpClientBuilder {
/**
* Make a POST request.
*/
public post<T = any>(
url?: string | URL,
body?: Body,
options: ReqOptions = {},
) {
public post<T = any>(url?: string | URL, body?: Body, options: Request = {}) {
return this.method('POST')
.url(url || options.url || this.options.url)
.body(body || options.body || this.options.body || {})
Expand All @@ -1087,11 +1090,7 @@ export class HttpClientBuilder {
/**
* Make a PUT request.
*/
public put<T = any>(
url?: string | URL,
body?: Body,
options: ReqOptions = {},
) {
public put<T = any>(url?: string | URL, body?: Body, options: Request = {}) {
return this.method('PUT')
.url(url || options.url || this.options.url)
.body(body || options.body || this.options.body || {})
Expand All @@ -1104,7 +1103,7 @@ export class HttpClientBuilder {
public patch<T = any>(
url?: string | URL,
body?: Response,
options: ReqOptions = {},
options: Request = {},
) {
return this.method('PATCH')
.url(url || options.url || this.options.url)
Expand All @@ -1115,7 +1114,7 @@ export class HttpClientBuilder {
/**
* Make a DELETE request.
*/
public delete<T = any>(url?: string | URL, options: ReqOptions = {}) {
public delete<T = any>(url?: string | URL, options: Request = {}) {
return this.method('DELETE')
.url(url || options.url || this.options.url)
.request<T>(options)
Expand All @@ -1124,7 +1123,7 @@ export class HttpClientBuilder {
/**
* Make a HEAD request.
*/
public head<T = any>(url?: string | URL, options: ReqOptions = {}) {
public head<T = any>(url?: string | URL, options: Request = {}) {
return this.method('HEAD')
.url(url || options.url || this.options.url)
.request<T>(options)
Expand Down Expand Up @@ -1161,7 +1160,7 @@ export class HttpClient {
/**
* Make a GET request.
*/
public static get<T = any>(url?: string | URL, options?: ReqOptions) {
public static get<T = any>(url?: string | URL, options?: Request) {
return this._builder.get<T>(url, options)
}

Expand All @@ -1171,7 +1170,7 @@ export class HttpClient {
public static post<T = any>(
url?: string | URL,
body?: Body,
options?: ReqOptions,
options?: Request,
) {
return this._builder.post<T>(url, body, options)
}
Expand All @@ -1182,29 +1181,33 @@ export class HttpClient {
public static put<T = any>(
url?: string | URL,
body?: Body,
options?: ReqOptions,
options?: Request,
) {
return this._builder.put<T>(url, body, options)
}

/**
* Make a PATCH request.
*/
static patch<T = any>(url?: string | URL, body?: Body, options?: ReqOptions) {
public static patch<T = any>(
url?: string | URL,
body?: Body,
options?: Request,
) {
return this._builder.patch<T>(url, body, options)
}

/**
* Make a DELETE request.
*/
public static delete<T = any>(url?: string | URL, options?: ReqOptions) {
public static delete<T = any>(url?: string | URL, options?: Request) {
return this._builder.delete<T>(url, options)
}

/**
* Make a HEAD request.
*/
public static head<T = any>(url?: string | URL, options?: ReqOptions) {
public static head<T = any>(url?: string | URL, options?: Request) {
return this._builder.head<T>(url, options)
}
}
10 changes: 6 additions & 4 deletions src/helpers/Is.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,7 @@
import kindOf from 'kind-of'

import { isIP } from 'node:net'
import { validate } from 'uuid'
import { Exception } from '#src/helpers/Exception'
import { Uuid, Exception } from '#src'
import { isCep, isCnpj, isCpf } from 'validator-brazil'

export class Is {
Expand All @@ -34,8 +33,11 @@ export class Is {
/**
* Verify if is valid Uuid.
*/
public static Uuid(value: string): boolean {
return validate(value)
public static Uuid(
value: string,
options?: { prefix?: string; ignorePrefix?: boolean },
): boolean {
return Uuid.verify(value, options)
}

/**
Expand Down
2 changes: 1 addition & 1 deletion src/helpers/Json.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ export class ObjectBuilder {
}

/**
* Delete the configuration key.
* Delete a value from the object by the key.
*/
public delete(key: string): this {
if (this.notExists(key)) {
Expand Down
3 changes: 0 additions & 3 deletions src/helpers/Parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,9 +80,6 @@ export class Parser {

/**
* Parse an object to form data.
*
* @param {any} object
* @return {string}
*/
public static jsonToFormData(object: any): string {
return Object.keys(object)
Expand Down
3 changes: 0 additions & 3 deletions src/helpers/Route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,6 @@ export class Route {

/**
* Get array with ?&queryParams name from route.
*
* @param {string} route
* @return {string[]}
*/
public static getQueryParamsName(route: string): string[] {
const queryNames = []
Expand Down
29 changes: 22 additions & 7 deletions src/helpers/Uuid.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,20 +7,35 @@
* file that was distributed with this source code.
*/

import { v4 } from 'uuid'
import { Is } from '#src/helpers/Is'
import { v4, validate } from 'uuid'
import { Options } from '#src/helpers/Options'
import { InvalidUuidException } from '#src/exceptions/InvalidUuidException'

export class Uuid {
/**
* Verify if string is a valid uuid.
*/
public static verify(token: string, isPrefixed = false): boolean {
if (isPrefixed) {
return Is.Uuid(this.getToken(token))
public static verify(
token: string,
options: { prefix?: string; ignorePrefix?: boolean } = {},
): boolean {
options = Options.create(options, { ignorePrefix: true })

if (options.prefix) {
const prefix = this.getPrefix(token)

if (prefix !== options.prefix) {
return false
}

return validate(this.getToken(token))
}

if (options.ignorePrefix) {
return validate(this.getToken(token))
}

return Is.Uuid(token)
return validate(token)
}

/**
Expand Down Expand Up @@ -76,7 +91,7 @@ export class Uuid {
}

/**
* Change the prefix of and uuid token
* Change the prefix of an uuid token
*/
public static changePrefix(newPrefix: string, token: string): string {
const uuid = this.getToken(token)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
import type { Except } from '#src/types'
import type { OptionsInit, ResponseType } from 'got'

export type ReqOptions = Except<OptionsInit, 'responseType'> &
export type Request = Except<OptionsInit, 'responseType'> &
Partial<{
get responseType(): ResponseType | string
set responseType(value: ResponseType | string)
Expand Down
12 changes: 12 additions & 0 deletions src/types/http-client/Response.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/**
* @athenna/common
*
* (c) João Lenon <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

import type { Response as GotResponse, CancelableRequest } from 'got'

export type Response<T = any> = CancelableRequest<GotResponse<T>>
21 changes: 20 additions & 1 deletion src/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,24 @@
* file that was distributed with this source code.
*/

import type {
Hooks,
RequestError,
RetryObject,
CacheOptions,
ToughCookieJar,
PromiseCookieJar,
} from 'got'

export type {
Hooks,
RequestError,
RetryObject,
CacheOptions,
ToughCookieJar,
PromiseCookieJar,
}

export * from '#src/types/Merge'
export * from '#src/types/Except'
export * from '#src/types/PathDirs'
Expand All @@ -21,5 +39,6 @@ export * from '#src/types/pagination/PaginatedResponse'

export * from '#src/types/http-client/Body'
export * from '#src/types/http-client/Query'
export * from '#src/types/http-client/ReqOptions'
export * from '#src/types/http-client/Request'
export * from '#src/types/http-client/Response'
export * from '#src/types/http-client/RetryStrategyCallback'
Loading

0 comments on commit 0bdfcee

Please sign in to comment.