Skip to content

Commit 72ce020

Browse files
authored
Merge pull request #11 from codeclown/type-definitions
Type definitions
2 parents 792fda5 + 0d148b5 commit 72ce020

File tree

4 files changed

+242
-9
lines changed

4 files changed

+242
-9
lines changed

CHANGELOG.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
11
# Changelog
22

3+
## Upcoming
4+
5+
Features:
6+
- TypeScript type definitions (4beec22)
7+
38
## 1.3.0
49

510
Features:

CONTRIBUTING.md

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
# Contributing
2+
3+
## Code conventions, code style
4+
5+
Yea is written as pure JavaScript with no precompilation (other than minification for the distributed version).
6+
7+
## Documentation
8+
9+
Documentation of all methods should be kept up-to-date in two places:
10+
11+
- `README.md` – Extensive documentation for each method, with examples
12+
- `index.d.ts` – 1-to-2 sentence documentation for each method, with minimal examples
13+
14+
## Changelog
15+
16+
Each change should be complemented with a bulletpoint in CHANGELOG.md under "Upcoming".

README.md

Lines changed: 33 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ Requests are configured via method calls and each method always returns a fresh
1212
- Immutable API, Promise-based, throws meaningful errors
1313
- No external dependencies, quite small (<2.4KB minified and gzipped)
1414
- Understands Content-Type (decodes JSON responses by default)
15+
- [TypeScript support](#usage-with-typescript)
1516
- [Works on modern browsers and some older ones](#browser-support)
1617
- [Fully tested](/test/specs) (see e.g. [requests.spec.js](/test/specs/requests.spec.js))
1718

@@ -22,6 +23,7 @@ Why not use fetch, axios, jQuery, etc..? See [COMPARISON.md](COMPARISON.md).
2223

2324
- [Installation](#installation)
2425
- [Usage](#usage)
26+
- [Usage with TypeScript](#usage-with-typescript)
2527
- [API](#api)
2628
- [Inspect request config](#inspect-request-config)
2729
- [Extending (instances)](#extending-instances)
@@ -141,6 +143,21 @@ const account = await request.get('https://example.com/accounts.json').prop('dat
141143
```
142144

143145

146+
## Usage with TypeScript
147+
148+
Yea comes with built-in type declarations.
149+
150+
```ts
151+
import yea, { YeaRequestError } from 'yea';
152+
request.get('https://example.com').then(response => {
153+
// Response is implicitly an instance of YeaResponse
154+
console.log(response.body);
155+
}).catch((error: YeaRequestError) => {
156+
console.error(error.response.status);
157+
});
158+
```
159+
160+
144161
## API
145162

146163
The following methods are available.
@@ -243,14 +260,21 @@ request.baseUrl('https://example.com/nested/foo').url('accounts') // => https:/
243260

244261
### query
245262

246-
Sets query parameters from an object. Overwrites existing query.
263+
Sets query parameters from an object or a string. Overwrites existing query.
247264

248265
```js
249266
.query(object | string)
250267
```
251268

252269
Where `object` is key-value object of query parameters to set, or a valid query string.
253270

271+
Example:
272+
273+
```js
274+
request.query({ first: 'foo', second: 'bar' })
275+
request.query('first=foo&second=bar')
276+
```
277+
254278
### headers
255279

256280
Sets request headers from an object. Overwrites existing headers.
@@ -324,7 +348,7 @@ console.log(req.toObject().headers) // => { 'x-token': 'secret123' }
324348

325349
### body
326350

327-
Set the body of the request.
351+
Set the raw body of the request.
328352

329353
```js
330354
.body(data)
@@ -348,13 +372,13 @@ Shorthand for `request.header('Content-Type', 'application/json').body(JSON.stri
348372

349373
### urlencoded
350374

351-
Sets a JSON-encoded body and sets the `Content-Type` header to `'application/urlencoded'`.
375+
Sets a URL-encoded body and sets the `Content-Type` header to `'application/urlencoded'`.
352376

353377
```js
354-
.urlencoded(value)
378+
.urlencoded(data)
355379
```
356380

357-
Where `value` is mixed.
381+
Where `value` is an object.
358382

359383
Shorthand for `request.header('content-type', 'application/x-www-form-urlencoded').body(_valueUrlEncoded_)`.
360384

@@ -391,8 +415,8 @@ Where `path` is a string or an array.
391415
Example:
392416

393417
```js
394-
cosnt account = await request.get('...').prop('data.accounts[0]');
395-
cosnt contentType = await request.get('...').prop(['headers', 'content-type']);
418+
const account = await request.get('...').prop('data.accounts[0]');
419+
const contentType = await request.get('...').prop(['headers', 'content-type']);
396420
```
397421

398422
### send
@@ -439,15 +463,15 @@ Note that calling `.send()` is not always necessary. You can usually directly ca
439463

440464
### sendUrlencoded
441465

442-
Short-hand for `.urlencoded(data).send()`.
466+
Shorthand for `.urlencoded(data).send()`.
443467

444468
```js
445469
.sendUrlencoded(data)
446470
```
447471

448472
### sendJson
449473

450-
Short-hand for `.json(data).send()`.
474+
Shorthand for `.json(data).send()`.
451475

452476
```js
453477
.sendJson(data)

index.d.ts

Lines changed: 188 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,188 @@
1+
export as namespace yea;
2+
3+
export interface YeaResponse {
4+
headers: {
5+
[key: string]: string;
6+
};
7+
body: string;
8+
status: number;
9+
}
10+
11+
/**
12+
* Error thrown when sending a request fails.
13+
*/
14+
export interface YeaRequestError extends Error {
15+
response: YeaResponse;
16+
}
17+
18+
export type ResponseTransformer = (response: YeaResponse) => YeaResponse;
19+
20+
declare class YeaAjaxRequest implements PromiseLike<YeaResponse> {
21+
jsonResponseTransformer: ResponseTransformer;
22+
23+
then<TResult1 = YeaResponse, TResult2 = never>(
24+
onfulfilled?:
25+
| ((value: YeaResponse) => TResult1 | PromiseLike<TResult1>)
26+
| undefined
27+
| null,
28+
onrejected?:
29+
| ((reason: any) => TResult2 | PromiseLike<TResult2>)
30+
| undefined
31+
| null
32+
): Promise<TResult1 | TResult2>;
33+
34+
/**
35+
* Sets the HTTP method.
36+
* @see get
37+
* @see post
38+
* @see put
39+
* @see delete
40+
*/
41+
method(
42+
method:
43+
| "GET"
44+
| "POST"
45+
| "PUT"
46+
| "DELETE"
47+
| "get"
48+
| "post"
49+
| "put"
50+
| "delete"
51+
): this;
52+
53+
/**
54+
* Initializes a GET request
55+
* @example `yea.get('http://example.com/data.json')`
56+
*/
57+
get(url: string): this;
58+
59+
/**
60+
* Initializes a POST request
61+
* @example `yea.post('http://example.com/data')`
62+
*/
63+
post(url: string): this;
64+
65+
/**
66+
* Initializes a PUT request
67+
*/
68+
put(url: string): this;
69+
70+
/**
71+
* Initializes a DELETE request
72+
*/
73+
delete(url: string): this;
74+
75+
/**
76+
* Sets the full URL of the request. If a query-string is present, it will override any previously set query parameters.
77+
*/
78+
url(url: string): this;
79+
80+
/**
81+
* Sets the base URL to which all subsequent request URLs will be appended.
82+
*/
83+
baseUrl(baseUrl: string): this;
84+
85+
/**
86+
* Sets query parameters from an object. Overwrites existing query.
87+
*/
88+
query(query: object | string): this;
89+
90+
/**
91+
* Sets request headers from an object. Overwrites existing headers.
92+
*/
93+
headers(headers: object): this;
94+
95+
/**
96+
* Sets request headers from an object. Only overwrites headers present in the given object.
97+
*/
98+
amendHeaders(headers: object): this;
99+
100+
/**
101+
* Adds or updates a header value.
102+
*/
103+
header(name: string, value: string): this;
104+
105+
/**
106+
* Removes a header from the request.
107+
*/
108+
unsetHeader(name: string): this;
109+
110+
/**
111+
* Set the raw body of the request. See also `json` and `urlencoded`.
112+
*/
113+
body(data: string | number): this;
114+
115+
/**
116+
* Sets a URL-encoded body and sets the `Content-Type` header to `'application/urlencoded'`.
117+
*/
118+
urlencoded(data: object): this;
119+
120+
/**
121+
* Sets a JSON-encoded body and sets the `Content-Type` header to `'application/json'`.
122+
*/
123+
json(data: any): this;
124+
125+
/**
126+
* Sets a timeout after which the request will be aborted and the Promise rejected.
127+
*/
128+
timeout(milliseconds): this;
129+
130+
/**
131+
* Removes the timeout-value previously set with `timeout`.
132+
*/
133+
unsetTimeout(): this;
134+
135+
/**
136+
* Sets a path (similar to `lodash.get`) which will be resolved once the response is returned.
137+
* @example
138+
```js
139+
const account = await request.get('...').prop('data.accounts[0]');
140+
const contentType = await request.get('...').prop(['headers', 'content-type']);
141+
```
142+
*/
143+
prop(path: string): this;
144+
145+
/**
146+
* Sets a list of response transformers which are called when a response is received. See the documentation for more information.
147+
*/
148+
setResponseTransformers(transformers: ResponseTransformer[]): this;
149+
150+
/**
151+
* By default any 2XX status code resolves the Promise and other status codes will reject it. This can be customized using `setAllowedStatusCode`.
152+
*/
153+
setAllowedStatusCode(
154+
allowedStatusCode: number | RegExp | ((statusCode: number) => boolean)
155+
): this;
156+
157+
/**
158+
* Override global dependencies which are used internally (like Promise). See the documentation for more information.
159+
*/
160+
polyfills(polyfills: { Promise: typeof Promise }): this;
161+
162+
/**
163+
* Returns the request configuration as an object.
164+
*/
165+
toObject(): object;
166+
config(): object;
167+
debug(): object;
168+
169+
/**
170+
* Shorthand for `.urlencoded(data).send()`.
171+
*/
172+
sendUrlencoded(data: object): Promise<YeaResponse>;
173+
174+
/**
175+
* Shorthand for `.json(data).send()`.
176+
*/
177+
sendJson(data: any): Promise<YeaResponse>;
178+
179+
/**
180+
* Dispatches the request and returns a Promise. See also `sendJson` and `sendUrlencoded`.
181+
*/
182+
send(body?: string): Promise<YeaResponse>;
183+
}
184+
185+
// An instance of a class is exported
186+
// i.e. `module.exports = new YeaAjaxRequest()`
187+
declare const _YeaAjaxRequest: YeaAjaxRequest;
188+
export default _YeaAjaxRequest;

0 commit comments

Comments
 (0)