Skip to content

Commit

Permalink
chore: add support for fully qualified url
Browse files Browse the repository at this point in the history
  • Loading branch information
lucacicada committed Oct 16, 2023
1 parent 8f04c86 commit 62ddd85
Showing 1 changed file with 59 additions and 7 deletions.
66 changes: 59 additions & 7 deletions src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -276,17 +276,44 @@ export interface AweberAddSubscriberRequest {
}

export interface AweberClientOptions {
accountId: string
/**
* The aweber account ID.
*/
accountId: string | number

/**
* The OAuth2 client ID.
*/
clientId: string

/**
* The OAuth2 client secret.
*/
clientSecret: string

/**
* The OAuth2 refresh token.
*/
refreshToken: string

/**
* An optional OAuth2 access token.
*/
accessToken?: string

/**
* The OAuth2 scope.
*
* @default ['account.read', 'list.read', 'list.write', 'subscriber.read', 'subscriber.write']
*/
scopes?: string[]
}

export class AweberClient extends OAuth2ApiClient {
private _accountId: string
/**
* The aweber account ID.
*/
readonly accountId: string

constructor(options: AweberClientOptions) {
if (!options?.accountId) {
Expand Down Expand Up @@ -316,7 +343,7 @@ export class AweberClient extends OAuth2ApiClient {
scopes: options.scopes || ['account.read', 'list.read', 'list.write', 'subscriber.read', 'subscriber.write'],
})

this._accountId = options.accountId
this.accountId = String(options.accountId)
}

/**
Expand Down Expand Up @@ -392,11 +419,36 @@ export class AweberClient extends OAuth2ApiClient {
})
}

_fetch = async <T>(request: string | string[], { accountId, ...options }: AweberFetchOptions = {}) => {
const _accountId = accountId || this._accountId
const parts = Array.isArray(request) ? request : [request]
/**
* Create a url for the Aweber API.
*
* @param request The request path, an url.
* @param accountId
*/
_getURL = (request: URL | string | string[], accountId?: string) => {
const parts = (Array.isArray(request) ? request : [request]).filter(Boolean).map(String)

if (parts.length === 0) {
return resolveURL('https://api.aweber.com/1.0/accounts', accountId || this.accountId)
}

const url = resolveURL('https://api.aweber.com/1.0/accounts', _accountId, ...parts)
// take the first element of the request, guaranteed to exists after filtering
const root = parts.shift()!

if (root.startsWith('http')) {
return resolveURL(root, ...parts)
}

return resolveURL('https://api.aweber.com/1.0/accounts', accountId || this.accountId, ...parts)
}

/**
* Fetch a resource from the Aweber API.
*
* Use a fully qualified or append a path after `'https://api.aweber.com/1.0/accounts/' + accountId + ...`
*/
_fetch = async <T>(request: string | string[], { accountId, ...options }: AweberFetchOptions = {}) => {
const url = this._getURL(request, accountId)

return this.sendRequest<T>(url, {
...options,
Expand Down

0 comments on commit 62ddd85

Please sign in to comment.