/
lets-make-a-plugin.md
341 lines (265 loc) 路 8.02 KB
/
lets-make-a-plugin.md
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
[> Back to homepage](../readme.md#documentation)
## Let's make a plugin!
> Another example on how to use Got like a boss :electric_plug:
Okay, so you already have learned some basics. That's great!
When it comes to advanced usage, custom instances are really helpful.
For example, take a look at [`gh-got`](https://github.com/sindresorhus/gh-got).
It looks pretty complicated, but... it's simple and extremely useful.
Before we start, we need to find the [GitHub API docs](https://developer.github.com/v3/).
Let's write down the most important information:
1. The root endpoint is `https://api.github.com/`.
2. We will use version 3 of the API.\
The `Accept` header needs to be set to `application/vnd.github.v3+json`.
3. The body is in a JSON format.
4. We will use OAuth2 for authorization.
5. We may receive `400 Bad Request` or `422 Unprocessable Entity`.\
The body contains detailed information about the error.
6. *Pagination?* Yeah! Supported natively by Got.
7. Rate limiting. These headers are interesting:
- `X-RateLimit-Limit`
- `X-RateLimit-Remaining`
- `X-RateLimit-Reset`
Also `X-GitHub-Request-Id` may be useful for debugging.
8. The `User-Agent` header is required.
When we have all the necessary info, we can start mixing :cake:
### The root endpoint
Not much to do here. Just extend an instance and provide the `prefixUrl` option:
```js
import got from 'got';
const instance = got.extend({
prefixUrl: 'https://api.github.com'
});
export default instance;
```
### v3 API
GitHub needs to know which API version we are using. We'll use the `Accept` header for that:
```js
import got from 'got';
const instance = got.extend({
prefixUrl: 'https://api.github.com',
headers: {
accept: 'application/vnd.github.v3+json'
}
});
export default instance;
```
### JSON body
We'll use [`options.responseType`](2-options.md#responsetype):
```js
import got from 'got';
const instance = got.extend({
prefixUrl: 'https://api.github.com',
headers: {
accept: 'application/vnd.github.v3+json'
},
responseType: 'json'
});
export default instance;
```
### Authorization
It's common to set some environment variables, for example, `GITHUB_TOKEN`. You can modify the tokens in all your apps easily, right? Cool. What about... we want to provide a unique token for each app. Then we will need to create a new option - it will default to the environment variable, but you can easily override it.
Got performs option validation and doesn't know that `token` is a wanted option so it will throw. We can handle it inside an `init` hook and save it in `options.context`.
```js
import got from 'got';
const instance = got.extend({
prefixUrl: 'https://api.github.com',
headers: {
accept: 'application/vnd.github.v3+json'
},
responseType: 'json',
context: {
token: process.env.GITHUB_TOKEN,
},
hooks: {
init: [
(raw, options) => {
if ('token' in raw) {
options.context.token = raw.token;
delete raw.token;
}
}
]
}
});
export default instance;
```
For the rest we will use a handler. We could use hooks, but this way it will be more readable. Having `beforeRequest`, `beforeError` and `afterResponse` hooks for just a few lines of code would complicate things unnecessarily.
**Tip:**
> - It's a good practice to use hooks when your plugin gets complicated.
> - Try not to overload the handler function, but don't abuse hooks either.
```js
import got from 'got';
const instance = got.extend({
prefixUrl: 'https://api.github.com',
headers: {
accept: 'application/vnd.github.v3+json'
},
responseType: 'json',
context: {
token: process.env.GITHUB_TOKEN,
},
hooks: {
init: [
(raw, options) => {
if ('token' in raw) {
options.context.token = raw.token;
delete raw.token;
}
}
]
},
handlers: [
(options, next) => {
// Authorization
const {token} = options.context;
if (token && !options.headers.authorization) {
options.headers.authorization = `token ${token}`;
}
return next(options);
}
]
});
export default instance;
```
### Errors
We should name our errors, just to know if the error is from the API response. Superb errors, here we come!
```js
...
handlers: [
(options, next) => {
// Authorization
const {token} = options.context;
if (token && !options.headers.authorization) {
options.headers.authorization = `token ${token}`;
}
// Don't touch streams
if (options.isStream) {
return next(options);
}
// Magic begins
return (async () => {
try {
const response = await next(options);
return response;
} catch (error) {
const {response} = error;
// Nicer errors
if (response && response.body) {
error.name = 'GitHubError';
error.message = `${response.body.message} (${response.statusCode} status code)`;
}
throw error;
}
})();
}
]
...
```
Note that by providing our own errors in handlers, we don't alter the ones in `beforeError` hooks.\
The conversion is the last thing here.
### Rate limiting
Umm... `response.headers['x-ratelimit-remaining']` doesn't look good. What about `response.rateLimit.limit` instead?\
Yeah, definitely. Since `response.headers` is an object, we can easily parse these:
```js
const getRateLimit = (headers) => ({
limit: Number.parseInt(headers['x-ratelimit-limit'], 10),
remaining: Number.parseInt(headers['x-ratelimit-remaining'], 10),
reset: new Date(Number.parseInt(headers['x-ratelimit-reset'], 10) * 1000)
});
getRateLimit({
'x-ratelimit-limit': '60',
'x-ratelimit-remaining': '55',
'x-ratelimit-reset': '1562852139'
});
// => {
// limit: 60,
// remaining: 55,
// reset: 2019-07-11T13:35:39.000Z
// }
```
Let's integrate it:
```js
const getRateLimit = (headers) => ({
limit: Number.parseInt(headers['x-ratelimit-limit'], 10),
remaining: Number.parseInt(headers['x-ratelimit-remaining'], 10),
reset: new Date(Number.parseInt(headers['x-ratelimit-reset'], 10) * 1000)
});
...
handlers: [
(options, next) => {
// Authorization
const {token} = options.context;
if (token && !options.headers.authorization) {
options.headers.authorization = `token ${token}`;
}
// Don't touch streams
if (options.isStream) {
return next(options);
}
// Magic begins
return (async () => {
try {
const response = await next(options);
// Rate limit for the Response object
response.rateLimit = getRateLimit(response.headers);
return response;
} catch (error) {
const {response} = error;
// Nicer errors
if (response && response.body) {
error.name = 'GitHubError';
error.message = `${response.body.message} (${response.statusCode} status code)`;
}
// Rate limit for errors
if (response) {
error.rateLimit = getRateLimit(response.headers);
}
throw error;
}
})();
}
]
...
```
### The frosting on the cake: `User-Agent` header.
```js
const packageJson = {
name: 'gh-got',
version: '12.0.0'
};
const instance = got.extend({
...
headers: {
accept: 'application/vnd.github.v3+json',
'user-agent': `${packageJson.name}/${packageJson.version}`
},
...
});
```
## Woah. Is that it?
Yup. View the full source code [here](examples/gh-got.js). Here's an example of how to use it:
```js
import ghGot from 'gh-got';
const response = await ghGot('users/sindresorhus');
const creationDate = new Date(response.created_at);
console.log(`Sindre's GitHub profile was created on ${creationDate.toGMTString()}`);
// => Sindre's GitHub profile was created on Sun, 20 Dec 2009 22:57:02 GMT
```
### Pagination
```js
import ghGot from 'gh-got';
const countLimit = 50;
const pagination = ghGot.paginate(
'repos/sindresorhus/got/commits',
{
pagination: {countLimit}
}
);
console.log(`Printing latest ${countLimit} Got commits (newest to oldest):`);
for await (const commitData of pagination) {
console.log(commitData.commit.message);
}
```
That's... astonishing! We don't have to implement pagination on our own. Got handles it all.
### At the end
Did you know you can mix many instances into a bigger, more powerful one? Check out the [Advanced Creation](examples/advanced-creation.js) guide.