Skip to content

Commit ee4730f

Browse files
committed
fix: Removed xhr library in favour of ky, and switched request for got for a smaller package size and retry functionality
1 parent 18effa2 commit ee4730f

File tree

7 files changed

+163
-364
lines changed

7 files changed

+163
-364
lines changed

README.md

Lines changed: 13 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -147,43 +147,26 @@ Instantiate the library using a basic token created in your [Gitlab Profile](htt
147147

148148
```javascript
149149
// ES6 (>=node 8.9.0)
150-
import { Gitlab } from 'gitlab';
150+
import { Gitlab } from 'gitlab'; // All Resources
151+
import { Projects } from 'gitlab'; // Just the Project Resource
152+
//...etc
151153

152154
// ES5, assuming native or polyfilled Promise is available
153155
const { Gitlab } = require('gitlab');
154-
155-
// Instantiating
156-
const api = new Gitlab({
157-
host: 'http://example.com', // Defaults to https://gitlab.com
158-
token: 'abcdefghij123456', // Can be created in your profile.
159-
});
160-
161-
// Or, use a OAuth token instead!
162-
163-
const api = new Gitlab({
164-
host: 'http://example.com', // Defaults to https://gitlab.com
165-
oauthToken: 'abcdefghij123456',
166-
});
167-
168-
// You can also use a CI job token:
169-
170-
const api = new Gitlab({
171-
url: 'http://example.com', // Defaults to https://gitlab.com
172-
jobToken: process.env.CI_JOB_TOKEN,
173-
});
174156
```
175157

176-
#### Specific Imports
177-
178-
Sometimes you don't want to import and instantiate the whole Gitlab API, perhaps you only want access to the Projects API. To do this, one only needs to import and instantiate this specific API:
179-
158+
Instatiating options:
180159
```javascript
181-
import { Projects } from 'gitlab';
182-
183-
const service = new Projects({
184-
host: 'http://example.com', // Defaults to https://gitlab.com
185-
token: 'abcdefghij123456', // Can be created in your profile.
160+
const api = new Gitlab({
161+
host: 'http://gl.com', //Optional, Default: https://gitlab.com
162+
token: 'personaltoken', //Personal Token. Required (one of the three tokens are required)
163+
oauthToken: 'oauthtoken', //OAuth Token. Required (one of the three tokens are required)
164+
jobToken: 'myJobToken', //CI job token. Required (one of the three tokens are required)
165+
rejectUnauthorized: false //Http Certificate setting. Optional, Default: false
166+
sudo: false //Sudo query parameter. Optional, Default: false
167+
version = 'v4', //API Version ID. Optional, Default: v4
186168
camelize = false, //Response Key Camelize. Camelizes all response body keys. Optional, Default: false
169+
requester = KyRequester, //Request Library Wrapper. Optional, Default: Currently wraps Ky.
187170
});
188171
```
189172

src/index.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
import { shim } from 'universal-url';
2+
3+
// Add URL shim
4+
shim();
15

26
import { bundler } from './infrastructure';
37
import * as APIServices from './services';

src/infrastructure/BaseService.ts

Lines changed: 8 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,53 +1,36 @@
1-
import URLJoin from 'url-join';
2-
import Request from 'request-promise';
3-
import XMLHttpRequester, { XhrStaticPromisified } from './XMLHttpRequester';
1+
import { KyRequester } from './KyRequester';
42

5-
interface BaseModelOptions {
3+
export class BaseService {
64
public readonly url: string;
7-
token?: string;
8-
oauthToken?: string;
5+
public readonly requester: Requester;
6+
public readonly headers: { [header: string]: string };
97
public readonly camelize: boolean;
10-
version?: string;
11-
sudo?: string | number;
12-
rejectUnauthorized?: boolean;
13-
}
14-
15-
export type BaseModelContructorOptions =
16-
| BaseModelOptions & Required<Pick<BaseModelOptions, 'token'>>
17-
| BaseModelOptions & Required<Pick<BaseModelOptions, 'oauthToken'>>;
18-
class BaseModel {
19-
public url: string;
20-
public readonly headers: { [header: string]: string | number};
218
public readonly rejectUnauthorized: boolean;
22-
public readonly requester: XhrStaticPromisified;
23-
public readonly useXMLHttpRequest: boolean;
249

2510
constructor({
2611
token,
12+
jobToken,
2713
oauthToken,
2814
sudo,
2915
host = 'https://gitlab.com',
3016
url = '',
3117
version = 'v4',
3218
camelize = false,
3319
rejectUnauthorized = true,
34-
}: BaseModelContructorOptions) {
20+
requester = KyRequester,
3521
}: BaseServiceOptions) {
3622
this.url = [host, 'api', version, url].join('/');
3723
this.headers = {};
38-
this.requester = useXMLHttpRequest
39-
? XMLHttpRequester : (Request as temporaryAny as XhrStaticPromisified);
40-
this.useXMLHttpRequest = useXMLHttpRequest;
4124
this.rejectUnauthorized = rejectUnauthorized;
4225
this.camelize = camelize;
26+
this.requester = requester;
4327

4428
// Handle auth tokens
4529
if (oauthToken) this.headers.authorization = `Bearer ${oauthToken}`;
30+
else if (jobToken) this.headers['job-token'] = jobToken;
4631
else if (token) this.headers['private-token'] = token;
4732

4833
// Set sudo
4934
if (sudo) this.headers['Sudo'] = `${sudo}`;
5035
}
5136
}
52-
53-
export default BaseModel;

src/infrastructure/KyRequester.ts

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
import Ky from 'ky-universal';
2+
import { decamelizeKeys } from 'humps';
3+
import { stringify } from 'query-string';
4+
import { skipAllCaps } from './Utils';
5+
6+
const methods = ['get', 'post', 'put', 'delete'];
7+
const KyRequester = {} as Requester;
8+
9+
function responseHeadersAsObject(response) {
10+
const headers = {}
11+
const keyVals = [...response.headers.entries()]
12+
13+
keyVals.forEach(([key, val]) => {
14+
headers[key] = val
15+
})
16+
17+
return headers
18+
}
19+
20+
function defaultRequest(
21+
service: any,
22+
endpoint: string,
23+
{ body, query, sudo }: DefaultRequestOptions,
24+
) {
25+
const headers = new Headers(service.headers);
26+
27+
if (sudo) headers.append('sudo', `${sudo}`);
28+
29+
return [
30+
endpoint,
31+
{
32+
timeout: 30000,
33+
headers,
34+
searchParams: stringify(decamelizeKeys(query || {}), { arrayFormat: 'bracket' }),
35+
prefixUrl: service.url,
36+
json: typeof body === 'object' ? decamelizeKeys(body, skipAllCaps) : body,
37+
rejectUnauthorized: service.rejectUnauthorized,
38+
},
39+
];
40+
}
41+
42+
methods.forEach(m => {
43+
KyRequester[m] = async function(service, endpoint, options) {
44+
try {
45+
const response = await Ky[m](...defaultRequest(service, endpoint, options));
46+
const { status } = response;
47+
const headers = responseHeadersAsObject(response);
48+
let body = await response.json();
49+
50+
if (typeof body === 'object') body = body || {};
51+
52+
return { body, headers, status };
53+
} catch(e) {
54+
console.error(e)
55+
console.error(...defaultRequest(service, endpoint, options))
56+
throw(e)
57+
}
58+
};
59+
});
60+
61+
export { KyRequester };

0 commit comments

Comments
 (0)