forked from paperos-labs/x-hub.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fetch.js
62 lines (49 loc) · 1.27 KB
/
fetch.js
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
"use strict";
/**
* @typedef XHubFetchPackage
* @prop {XHubFetchCreate} create
*/
/**
* @callback XHubFetchCreate
* @param {XHub.XHubOptions} options
* @returns {XHubFetch}
*/
/**
* @typedef XHubFetch
* @prop {fetch} fetch
*/
/** @type {XHubFetchPackage} */
let XHubFetch = module.exports;
let XHub = require("../x-hub-signature.js");
// "application/json"
// "application/json; charset=utf-8"
// "application/vnd.github.v3+json"
// XHubFetch._isJSON = /[\/\+]json($|;\s)/;
XHubFetch.create = function (options) {
let xhub = XHub.create(options);
let request = {};
/** @type {fetch} */
request.fetch = async function (url, opts) {
if (!opts?.body) {
throw new Error("no 'body' to sign");
}
//@ts-ignore
let header = await xhub.sign(opts.body, "sha256");
let fetchOpts = Object.assign({}, opts);
if (!fetchOpts.headers) {
/** @type {Object.<String, String>} */
let headers = {};
let isSha256 = header.startsWith("sha256=");
if (isSha256) {
headers["X-Hub-Signature-256"] = header;
} else {
headers["X-Hub-Signature"] = header;
}
//@ts-ignore
Object.assign(fetchOpts.headers, headers);
}
let resp = await fetch(url, fetchOpts);
return resp;
};
return request;
};