Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: switch the http client to ky #42

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3,733 changes: 2,225 additions & 1,508 deletions package-lock.json

Large diffs are not rendered by default.

13 changes: 7 additions & 6 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
"build": "tsc -p tsconfig.dist.json",
"build:docs": "npx typedoc",
"build:index": "node --import tsx/esm scripts/build-index.ts",
"build:types": "npx therefore -f src",
"check:coverage": "vitest run --coverage=true",
"check:project": "node-standards lint",
"check:types": "tsc -p tsconfig.json",
Expand All @@ -35,17 +36,17 @@
"split2": "^4.2.0"
},
"devDependencies": {
"@skyleague/axioms": "^4.3.4",
"@skyleague/node-standards": "^7.1.0",
"@skyleague/therefore": "^5.8.8",
"@skyleague/axioms": "^4.5.2",
"@skyleague/node-standards": "^8.2.4",
"@skyleague/therefore": "^5.18.0",
"@types/split2": "^4.2.3",
"camelcase": "^8.0.0",
"got": "^14.3.0",
"nock": "^13.5.4",
"ky": "^1.7.2",
"nock": "^14.0.0-beta.15",
"typescript": "^5.4.5"
},
"peerDependencies": {
"got": "^14.3.0"
"ky": "^1.7.2"
},
"engines": {
"node": ">=20"
Expand Down
58 changes: 31 additions & 27 deletions src/accounting-interest-accrual/rest.client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,16 @@
import type { IncomingHttpHeaders } from 'node:http'

import type { DefinedError } from 'ajv'
import { got } from 'got'
import type { CancelableRequest, Got, Options, OptionsInit, Response } from 'got'
import ky from 'ky'
import type { KyInstance, Options, ResponsePromise } from 'ky'

import { ErrorResponse, InterestAccrualSearchCriteria, SearchResponse } from './rest.type.js'

/**
* accounting/interestaccrual
*/
export class MambuAccountingInterestAccrual {
public client: Got
public client: KyInstance

public auth: {
basic?: [username: string, password: string] | (() => Promise<[username: string, password: string]>)
Expand All @@ -31,22 +31,26 @@ export class MambuAccountingInterestAccrual {
options,
auth = {},
defaultAuth,
client = ky,
}: {
prefixUrl: string | 'http://localhost:8889/api' | 'https://localhost:8889/api'
options?: Options | OptionsInit
options?: Options
auth: {
basic?: [username: string, password: string] | (() => Promise<[username: string, password: string]>)
apiKey?: string | (() => Promise<string>)
}
defaultAuth?: string[][] | string[]
client?: KyInstance
}) {
this.client = got.extend(...[{ prefixUrl, throwHttpErrors: false }, options].filter((o): o is Options => o !== undefined))
this.client = client.extend({ prefixUrl, throwHttpErrors: false, ...options })
this.auth = auth
this.availableAuth = new Set(Object.keys(auth))
this.defaultAuth = defaultAuth
}

/**
* POST /accounting/interestaccrual:search
*
* Allows search of interest accrual breakdown entries by various criteria.
*/
public search({
Expand All @@ -66,7 +70,7 @@ export class MambuAccountingInterestAccrual {
| FailureResponse<StatusCode<2>, string, 'response:body', IncomingHttpHeaders>
| FailureResponse<
Exclude<StatusCode<1 | 3 | 4 | 5>, '400' | '401' | '403'>,
string,
unknown,
'response:statuscode',
IncomingHttpHeaders
>
Expand All @@ -78,17 +82,17 @@ export class MambuAccountingInterestAccrual {

return this.awaitResponse(
this.buildClient(auth).post('accounting/interestaccrual:search', {
json: body,
json: _body.right as InterestAccrualSearchCriteria,
searchParams: query ?? {},
headers: { Accept: 'application/vnd.mambu.v2+json' },
responseType: 'json',
}),
{
200: SearchResponse,
400: ErrorResponse,
401: ErrorResponse,
403: ErrorResponse,
},
'json',
) as ReturnType<this['search']>
}

Expand All @@ -113,75 +117,75 @@ export class MambuAccountingInterestAccrual {
public async awaitResponse<
I,
S extends Record<PropertyKey, { parse: (o: I) => { left: DefinedError[] } | { right: unknown } } | undefined>,
>(response: CancelableRequest<Response<I>>, schemas: S) {
>(response: ResponsePromise<I>, schemas: S, responseType?: 'json' | 'text') {
const result = await response
const _body = (await (responseType !== undefined ? result[responseType]() : result.text())) as I
const status =
result.statusCode < 200
result.status < 200
? 'informational'
: result.statusCode < 300
: result.status < 300
? 'success'
: result.statusCode < 400
: result.status < 400
? 'redirection'
: result.statusCode < 500
: result.status < 500
? 'client-error'
: 'server-error'
const validator = schemas[result.statusCode] ?? schemas.default
const body = validator?.parse?.(result.body)
if (result.statusCode < 200 || result.statusCode >= 300) {
const validator = schemas[result.status] ?? schemas.default
const body = validator?.parse?.(_body)
if (result.status < 200 || result.status >= 300) {
return {
statusCode: result.statusCode.toString(),
statusCode: result.status.toString(),
status,
headers: result.headers,
left: body !== undefined && 'right' in body ? body.right : result.body,
left: body !== undefined && 'right' in body ? body.right : _body,
validationErrors: body !== undefined && 'left' in body ? body.left : undefined,
where: 'response:statuscode',
}
}
if (body === undefined || 'left' in body) {
return {
statusCode: result.statusCode.toString(),
statusCode: result.status.toString(),
status,
headers: result.headers,
left: result.body,
left: _body,
validationErrors: body?.left,
where: 'response:body',
}
}
return { statusCode: result.statusCode.toString(), status, headers: result.headers, right: result.body }
return { statusCode: result.status.toString(), status, headers: result.headers, right: _body }
}

protected buildBasicClient(client: Got) {
protected buildBasicClient(client: KyInstance) {
return client.extend({
hooks: {
beforeRequest: [
async (options) => {
const basic = this.auth.basic
if (basic !== undefined) {
const [username, password] = typeof basic === 'function' ? await basic() : basic
options.username = username
options.password = password
options.headers.set('Authorization', `Basic ${btoa(`${username}:${password}`)}`)
}
},
],
},
})
}

protected buildApiKeyClient(client: Got) {
protected buildApiKeyClient(client: KyInstance) {
return client.extend({
hooks: {
beforeRequest: [
async (options) => {
const apiKey = this.auth.apiKey
const key = typeof apiKey === 'function' ? await apiKey() : apiKey
options.headers.apiKey = key
options.headers.set('apiKey', `${key}`)
},
],
},
})
}

protected buildClient(auths: string[][] | string[] | undefined = this.defaultAuth, client?: Got): Got {
protected buildClient(auths: string[][] | string[] | undefined = this.defaultAuth, client?: KyInstance): KyInstance {
const auth = (auths ?? [...this.availableAuth])
.map((auth) => (Array.isArray(auth) ? auth : [auth]))
.filter((auth) => auth.every((a) => this.availableAuth.has(a)))
Expand Down
Loading