-
Notifications
You must be signed in to change notification settings - Fork 18
/
index.js
82 lines (74 loc) · 2.06 KB
/
index.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
'use strict';
var fetch = require('node-fetch');
var url = require('url');
var Promise = require('lie');
var requests = [
{
path: '/_config/httpd/enable_cors',
value: '"true"'
},
{
path: '/_config/cors/origins',
value: '"*"'
},
{
path: '/_config/cors/credentials',
value: '"true"'
},
{
path: '/_config/cors/methods',
value: '"GET, PUT, POST, HEAD, DELETE"'
},
{
path: '/_config/cors/headers',
value: '"accept, authorization, content-type, origin, referer, x-csrf-token"'
}
];
function formatUrl(baseUrl, auth, path) {
var urlObject = url.parse(baseUrl + path);
if (auth) {
urlObject.auth = auth;
}
return url.format(urlObject);
}
function updateConfig(urlString, value) {
return fetch(urlString, {method: 'PUT', body: value}).then(function (resp) {
if (resp.status === 200) {
return;
}
return resp.text().then(function (text) {
throw new Error('status ' + resp.status + ' ' + text);
});
});
}
function doCouch1(baseUrl, auth) {
return Promise.all(requests.map(function (req) {
var urlString = formatUrl(baseUrl, auth, req.path);
return updateConfig(urlString, req.value);
}));
}
function doCouch2(baseUrl, auth, membershipResp) {
// do the Couch1 logic for all cluster_nodes
// see https://github.com/klaemo/docker-couchdb/issues/42#issuecomment-169610897
return membershipResp.json().then(function (members) {
return Promise.all(members.cluster_nodes.map(function (node) {
return Promise.all(requests.map(function (req) {
var path = '/_node/' + node + '/' + req.path;
var urlString = formatUrl(baseUrl, auth, path);
return updateConfig(urlString, req.value);
}));
}));
});
}
function addCors(baseUrl, auth) {
// check if we're dealing with couch 1 or couch 2
var urlString = formatUrl(baseUrl, auth, '/_membership');
return fetch(urlString).then(function (resp) {
if (resp.status !== 200) {
return doCouch1(baseUrl, auth);
} else {
return doCouch2(baseUrl, auth, resp);
}
});
}
module.exports = addCors;