UNPKG

1.78 kBJavaScriptView Raw
1/*
2 * Copyright 2018 Adobe. All rights reserved.
3 * This file is licensed to you under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License. You may obtain a copy
5 * of the License at http://www.apache.org/licenses/LICENSE-2.0
6 *
7 * Unless required by applicable law or agreed to in writing, software distributed under
8 * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
9 * OF ANY KIND, either express or implied. See the License for the specific language
10 * governing permissions and limitations under the License.
11 */
12
13'use strict';
14
15const _ = require('lodash');
16
17/**
18 * Export the subdomain handler (express middleware) through a parameterizable function
19 *
20 * @param {object} options configuration hash
21 * @returns {function(*, *, *)} handler function
22 */
23function createMiddleware(options) {
24 const conf = (options && options.subdomainMapping) || {};
25 const enabled = conf.enable && conf.baseDomains && conf.baseDomains.length;
26 return (req, res, next) => {
27 if (!enabled) {
28 return next();
29 }
30
31 let { host } = req.headers;
32 const origUrl = host + req.url;
33
34 // trim :<port>
35 [host] = host.split(':');
36
37 // match & remove base domain
38 const i = _.findIndex(conf.baseDomains, (dom) => _.endsWith(host, dom));
39 if (i === -1) {
40 return next();
41 }
42 host = _.trimEnd(host.slice(0, -conf.baseDomains[i].length), '.');
43 if (!host.length) {
44 // no subdomains
45 return next();
46 }
47
48 req.url = `/${host.split('.').join('/')}${req.url}`;
49 req.mappedSubDomain = true;
50
51 options.logger.debug(`${origUrl} => ${req.url}`);
52
53 // pass on to next middleware
54 return next();
55 };
56}
57module.exports = createMiddleware;