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 | ;
|
14 |
|
15 | const _ = require('lodash');
|
16 | const { debug } = require('@adobe/helix-log');
|
17 |
|
18 | /**
|
19 | * Export the subdomain handler (express middleware) through a parameterizable function
|
20 | *
|
21 | * @param {object} options configuration hash
|
22 | * @returns {function(*, *, *)} handler function
|
23 | */
|
24 | function createMiddleware(options) {
|
25 | const conf = (options && options.subdomainMapping) || {};
|
26 | const enabled = conf.enable && conf.baseDomains && conf.baseDomains.length;
|
27 | return (req, res, next) => {
|
28 | if (!enabled) {
|
29 | return next();
|
30 | }
|
31 |
|
32 | let { host } = req.headers;
|
33 | const origUrl = host + req.url;
|
34 |
|
35 | // trim :<port>
|
36 | [host] = host.split(':');
|
37 |
|
38 | // match & remove base domain
|
39 | const i = _.findIndex(conf.baseDomains, (dom) => _.endsWith(host, dom));
|
40 | if (i === -1) {
|
41 | return next();
|
42 | }
|
43 | host = _.trimEnd(host.slice(0, -conf.baseDomains[i].length), '.');
|
44 | if (!host.length) {
|
45 | // no subdomains
|
46 | return next();
|
47 | }
|
48 |
|
49 | req.url = `/${host.split('.').join('/')}${req.url}`;
|
50 | req.mappedSubDomain = true;
|
51 |
|
52 | debug(`${origUrl} => ${req.url}`);
|
53 |
|
54 | // pass on to next middleware
|
55 | return next();
|
56 | };
|
57 | }
|
58 | module.exports = createMiddleware;
|