forked from cujojs/rest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpathPrefix.js
49 lines (41 loc) · 1.01 KB
/
pathPrefix.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
/*
* Copyright 2012-2016 the original author or authors
* @license MIT, see LICENSE.txt for details
*
* @author Scott Andrews
*/
'use strict';
var interceptor, UrlBuilder;
interceptor = require('../interceptor');
UrlBuilder = require('../UrlBuilder');
function startsWith(str, prefix) {
return str.indexOf(prefix) === 0;
}
function endsWith(str, suffix) {
return str.lastIndexOf(suffix) + suffix.length === str.length;
}
/**
* Prefixes the request path with a common value.
*
* @param {Client} [client] client to wrap
* @param {number} [config.prefix] path prefix
*
* @returns {Client}
*/
module.exports = interceptor({
request: function (request, config) {
var path;
if (config.prefix && !(new UrlBuilder(request.path).isFullyQualified())) {
path = config.prefix;
if (request.path) {
if (!endsWith(path, '/') && !startsWith(request.path, '/')) {
// add missing '/' between path sections
path += '/';
}
path += request.path;
}
request.path = path;
}
return request;
}
});