forked from adamlaska/core.js
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
93 lines (79 loc) · 2.7 KB
/
index.ts
File metadata and controls
93 lines (79 loc) · 2.7 KB
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
import { getUserAgent } from "universal-user-agent";
import { Collection, HookCollection } from "before-after-hook";
import { request } from "@octokit/request";
import { graphql, withCustomRequest } from "@octokit/graphql";
import { OctokitOptions, Parameters, Plugin } from "./types";
import { VERSION } from "./version";
import { withAuthorizationPrefix } from "./auth";
export class Octokit {
static defaults(defaults: OctokitOptions) {
return class OctokitWithDefaults extends this {
static defaults(newDefaults: OctokitOptions): typeof Octokit {
return Octokit.defaults(Object.assign({}, defaults, newDefaults));
}
constructor(options: OctokitOptions = {}) {
super(Object.assign({}, defaults, options));
}
};
}
static plugins: Plugin[] = [];
static plugin(plugins: Plugin | Plugin[]) {
const currentPlugins = this.plugins;
const newPlugins = Array.isArray(plugins) ? plugins : [plugins];
return class NewOctokit extends this {
static plugins = currentPlugins.concat(
newPlugins.filter(plugin => !currentPlugins.includes(plugin))
);
};
}
constructor(options: OctokitOptions = {}) {
const hook = new Collection();
const requestDefaults: Required<Parameters> = {
baseUrl: request.endpoint.DEFAULTS.baseUrl,
headers: {},
request: Object.assign({}, options.request, {
hook: hook.bind(null, "request")
}),
mediaType: {
previews: [],
format: ""
}
};
// prepend default user agent with `options.userAgent` if set
requestDefaults.headers["user-agent"] = [
options.userAgent,
`octokit-core.js/${VERSION} ${getUserAgent()}`
]
.filter(Boolean)
.join(" ");
if (options.baseUrl) {
requestDefaults.baseUrl = options.baseUrl;
}
if (options.previews) {
requestDefaults.mediaType.previews = options.previews;
}
if (options.auth) {
if (typeof options.auth === "string") {
requestDefaults.headers.authorization = withAuthorizationPrefix(
options.auth
);
} else {
// @ts-ignore
hook.wrap("request", options.auth.hook);
}
}
this.request = request.defaults(requestDefaults);
this.graphql = withCustomRequest(this.request).defaults(requestDefaults);
this.hook = hook;
// apply plugins
// https://stackoverflow.com/a/16345172
const classConstructor = this.constructor as typeof Octokit;
classConstructor.plugins.forEach(plugin => plugin(this, options));
}
// assigned during constructor
request: typeof request;
graphql: typeof graphql;
hook: HookCollection;
// allow for plugins to extend the Octokit instance
[key: string]: any;
}