@brickninjaapi/fetch 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +26 -0
- package/package.json +32 -0
- package/src/index.ts +126 -0
- package/tsconfig.json +11 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 @brickninja
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
# `@brickninjaapi/fetch`
|
|
2
|
+
|
|
3
|
+
This package provides a tiny wrapper around native fetch to call the Brick Ninja API that returns typesafe responses.
|
|
4
|
+
|
|
5
|
+
## Usage
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
import { fetchBrickNinjaApi } from '@brickninjaapi/fetch';
|
|
9
|
+
|
|
10
|
+
const item = await fetchBrickNinjaApi('/v1/items/1234');
|
|
11
|
+
// -> { id: number, name: string, ... }
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
## Installation
|
|
15
|
+
|
|
16
|
+
```sh
|
|
17
|
+
npm i @brickninjaapi/fetch
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
## Contributing
|
|
21
|
+
|
|
22
|
+
See [parent readme](../../README.md#contributing).
|
|
23
|
+
|
|
24
|
+
## License
|
|
25
|
+
|
|
26
|
+
Licensed under the [MIT License](./LICENSE).
|
package/package.json
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@brickninjaapi/fetch",
|
|
3
|
+
"version": "0.0.1",
|
|
4
|
+
"description": "Tiny wrapper around fetch that returns type-safe responses",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"main": "dist/index.js",
|
|
7
|
+
"types": "dist/index.d.ts",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "git+https://github.com/brickninja-org/brickninjaapi-ts.git",
|
|
11
|
+
"directory": "packages/fetch"
|
|
12
|
+
},
|
|
13
|
+
"keywords": [
|
|
14
|
+
"brickninjaapi",
|
|
15
|
+
"fetch",
|
|
16
|
+
"brickninja",
|
|
17
|
+
"api"
|
|
18
|
+
],
|
|
19
|
+
"scripts": {
|
|
20
|
+
"test": "tsc --noEmit",
|
|
21
|
+
"build": "tsc"
|
|
22
|
+
},
|
|
23
|
+
"devDependencies": {
|
|
24
|
+
"typescript": "5.8.3"
|
|
25
|
+
},
|
|
26
|
+
"peerDependencies": {
|
|
27
|
+
"@brickninjaapi/types": "~0.0.1"
|
|
28
|
+
},
|
|
29
|
+
"publishConfig": {
|
|
30
|
+
"access": "public"
|
|
31
|
+
}
|
|
32
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import type { AuthenticatedOptions, EndpointType, KnownEndpoint, LocalizedOptions, OptionsByEndpoint } from '@brickninjaapi/types/endpoints';
|
|
2
|
+
import type { SchemaVersion } from '@brickninjaapi/types/schema';
|
|
3
|
+
|
|
4
|
+
type RequiredKeys<T> = { [K in keyof T]-?: {} extends Pick<T, K> ? never : K }[keyof T];
|
|
5
|
+
|
|
6
|
+
// if OptionsByEndpoint<Url> has no required keys, make the options parameter optional
|
|
7
|
+
type Args<Url extends string, Schema extends SchemaVersion> = RequiredKeys<OptionsByEndpoint<Url>> extends never
|
|
8
|
+
? [endpoint: Url, options?: FetchBrickNinjaApiOptions<Schema> & OptionsByEndpoint<Url> & FetchOptions]
|
|
9
|
+
: [endpoint: Url, options: FetchBrickNinjaApiOptions<Schema> & OptionsByEndpoint<Url> & FetchOptions]
|
|
10
|
+
|
|
11
|
+
export async function fetchBrickNinjaApi<
|
|
12
|
+
Url extends KnownEndpoint | (string & {}),
|
|
13
|
+
Schema extends SchemaVersion = 'latest',
|
|
14
|
+
>(
|
|
15
|
+
...[endpoint, options]: Args<Url, Schema>
|
|
16
|
+
): Promise<EndpointType<Url, Schema>> {
|
|
17
|
+
const url = new URL('https://brick-ninja-api.vercel.app/');
|
|
18
|
+
|
|
19
|
+
if (options.schema) {
|
|
20
|
+
url.searchParams.set('v', options.schema);
|
|
21
|
+
}
|
|
22
|
+
if (hasLanguage(options)) {
|
|
23
|
+
url.searchParams.set('lang', options.language);
|
|
24
|
+
}
|
|
25
|
+
if (hasAccessToken(options)) {
|
|
26
|
+
url.searchParams.set('access_token', options.accessToken);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// build request
|
|
30
|
+
let request = new Request(url, {
|
|
31
|
+
// The Brick Ninja API never uses redirects, so we want to error if we encounter one.
|
|
32
|
+
// We use `manual` instead of `error` here so we can throw our own `BrickNinjaApiError` with the response attached
|
|
33
|
+
redirect: 'manual',
|
|
34
|
+
|
|
35
|
+
// set signal and cache from options
|
|
36
|
+
signal: options.signal,
|
|
37
|
+
cache: options.cache
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
// if there is a onRequest handler registered, let it modify the request
|
|
41
|
+
if(options.onRequest) {
|
|
42
|
+
request = await options.onRequest(request);
|
|
43
|
+
|
|
44
|
+
if(!(request instanceof Request)) {
|
|
45
|
+
throw new Error(`onRequest has to return a Request`);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// call the API
|
|
50
|
+
const response = await fetch(request);
|
|
51
|
+
|
|
52
|
+
// call the onResponse handler if it exists
|
|
53
|
+
await options.onResponse?.(response);
|
|
54
|
+
|
|
55
|
+
// check if the response is json (`application/json; charset=utf-8`)
|
|
56
|
+
const isJson = response.headers.get('content-type').startsWith('application/json');
|
|
57
|
+
|
|
58
|
+
// censor access token in the url to not leak it in error messages
|
|
59
|
+
const erroredUrl = hasAccessToken(options)
|
|
60
|
+
? url.toString().replace(options.accessToken, '***')
|
|
61
|
+
: url.toString();
|
|
62
|
+
|
|
63
|
+
// check if the response is an error
|
|
64
|
+
if (!response.ok) {
|
|
65
|
+
// if the response is JSON, it might have more details in the `text` prop
|
|
66
|
+
if (isJson) {
|
|
67
|
+
const error: unknown = await response.json();
|
|
68
|
+
|
|
69
|
+
if (typeof error === 'object' && 'text' in error && typeof error.text === 'string') {
|
|
70
|
+
throw new BrickNinjaApiError(`The Brick Ninja API call to '${erroredUrl}' returned ${response.status} ${response.statusText}: ${error.text}.`, response);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// otherwise just throw error with the status code
|
|
75
|
+
throw new BrickNinjaApiError(`The Brick Ninja API call to '${erroredUrl}' returned ${response.status} ${response.statusText}.`, response);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// if the response is not JSON, throw an error
|
|
79
|
+
if (!isJson) {
|
|
80
|
+
throw new BrickNinjaApiError(`The Brick Ninja API call to '${erroredUrl}'did not respond with a JSON response.`, response);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// parse the response as JSON
|
|
84
|
+
const json = await response.json();
|
|
85
|
+
|
|
86
|
+
// TODO: catch more errors
|
|
87
|
+
|
|
88
|
+
return json;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export type FetchBrickNinjaApiOptions<Schema extends SchemaVersion> = {
|
|
92
|
+
/** The schema to use when making the API request */
|
|
93
|
+
schema?: Schema;
|
|
94
|
+
|
|
95
|
+
/** onRequest handler allows to modify the request made to the Brick Ninja API. */
|
|
96
|
+
onRequest?: (request: Request) => Request | Promise<Request>;
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* onResponse handler. Called for all responses, successful or not.
|
|
100
|
+
* Make sure to clone the response in case of consuming the body.
|
|
101
|
+
*/
|
|
102
|
+
onResponse?: (response: Response) => void | Promise<void>;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export type FetchOptions = {
|
|
106
|
+
/** @see https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal */
|
|
107
|
+
signal?: AbortSignal,
|
|
108
|
+
|
|
109
|
+
/** @see https://developer.mozilla.org/en-US/docs/Web/API/Request/cache */
|
|
110
|
+
cache?: RequestCache,
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export class BrickNinjaApiError extends Error {
|
|
114
|
+
constructor(message: string, public response: Response) {
|
|
115
|
+
super(message);
|
|
116
|
+
this.name = 'BrickNinjaApiError';
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function hasLanguage(options: OptionsByEndpoint<any>): options is LocalizedOptions {
|
|
121
|
+
return 'language' in options;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function hasAccessToken(options: OptionsByEndpoint<any>): options is AuthenticatedOptions {
|
|
125
|
+
return 'accessToken' in options;
|
|
126
|
+
}
|