UNPKG

2.02 kBJavaScriptView Raw
1// Copyright © 2017, 2018 IBM Corp. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14'use strict';
15
16const pkg = require('../package.json');
17const http = require('http');
18const https = require('https');
19const cloudant = require('@cloudant/cloudant');
20
21const userAgent = 'couchbackup-cloudant/' + pkg.version + ' (Node.js ' +
22 process.version + ')';
23
24module.exports = {
25 client: function(url, opts) {
26 var protocol = (url.match(/^https/)) ? https : http;
27 const keepAliveAgent = new protocol.Agent({
28 keepAlive: true,
29 keepAliveMsecs: 30000,
30 maxSockets: opts.parallelism
31 });
32 // Split the URL for use with nodejs-cloudant
33 var actUrl = url.substr(0, url.lastIndexOf('/'));
34 var dbName = url.substr(url.lastIndexOf('/') + 1);
35 // Default set of plugins includes retry
36 var pluginsToUse = ['retry'];
37 // Default to cookieauth unless an IAM key is provided
38 if (opts.iamApiKey) {
39 const iamPluginConfig = { iamApiKey: opts.iamApiKey };
40 if (opts.iamTokenUrl) {
41 iamPluginConfig.iamTokenUrl = opts.iamTokenUrl;
42 }
43 pluginsToUse.push({ iamauth: iamPluginConfig });
44 } else {
45 pluginsToUse.push({ cookieauth: { errorOnNoCreds: false } });
46 }
47 return cloudant({
48 url: actUrl,
49 plugins: pluginsToUse,
50 requestDefaults: {
51 agent: keepAliveAgent,
52 headers: { 'User-Agent': userAgent },
53 gzip: true,
54 timeout: opts.requestTimeout
55 }
56 }).use(dbName);
57 }
58};