Skip to content

Commit

Permalink
Improve options
Browse files Browse the repository at this point in the history
  • Loading branch information
darthmaim committed Jul 24, 2024
1 parent 2bd4055 commit 34e7164
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 4 deletions.
5 changes: 5 additions & 0 deletions .changeset/rotten-bats-smell.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@gw2api/fetch": minor
---

Make `options` parameter optional if it does not contain required properties
6 changes: 6 additions & 0 deletions .changeset/two-needles-sip.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"@gw2api/fetch": patch
"@gw2api/types": patch
---

Allow passing partial options for unknown endpoints
10 changes: 7 additions & 3 deletions packages/fetch/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
import type { AuthenticatedOptions, EndpointType, KnownEndpoint, LocalizedOptions, OptionsByEndpoint } from '@gw2api/types/endpoints';
import { SchemaVersion } from '@gw2api/types/schema';

// TODO: make `options` optional if `OptionsByEndpoint<Url>` only contains optional props
type RequiredKeys<T> = { [K in keyof T]-?: {} extends Pick<T, K> ? never : K }[keyof T];

// if OptionsByEndpoint<Url> has no required keys, make the options parameter optional
type Args<Url extends string, Schema extends SchemaVersion> = RequiredKeys<OptionsByEndpoint<Url>> extends never
? [endpoint: Url, options?: FetchGw2ApiOptions<Schema> & OptionsByEndpoint<Url> & FetchOptions]
: [endpoint: Url, options: FetchGw2ApiOptions<Schema> & OptionsByEndpoint<Url> & FetchOptions]

export function fetchGw2Api<
Url extends KnownEndpoint | (string & {}),
Schema extends SchemaVersion = undefined
>(
endpoint: Url,
options: FetchGw2ApiOptions<Schema> & OptionsByEndpoint<Url> & FetchOptions
...[endpoint, options]: Args<Url, Schema>
): Promise<EndpointType<Url, Schema>> {
const url = new URL(endpoint, 'https://api.guildwars2.com/');

Expand Down
3 changes: 2 additions & 1 deletion packages/types/endpoints.ts
Original file line number Diff line number Diff line change
Expand Up @@ -362,7 +362,8 @@ export type OptionsByEndpoint<Endpoint extends string> =
Endpoint extends KnownAuthenticatedEndpoint ? Options & AuthenticatedOptions :
Endpoint extends KnownLocalizedEndpoint ? Options & LocalizedOptions :
Endpoint extends CreateSubtokenUrl<'/v2/createsubtoken'> ? Options & AuthenticatedOptions :
Options
Endpoint extends KnownEndpoint | BulkExpandedEndpointUrl<KnownBulkExpandedEndpoint, string | number> ? Options :
Partial<AuthenticatedOptions & LocalizedOptions>

// result type for endpoint
export type EndpointType<Url extends KnownEndpoint | (string & {}), Schema extends SchemaVersion = undefined> =
Expand Down

0 comments on commit 34e7164

Please sign in to comment.