2018-01-25 05:13:30 -05:00
|
|
|
import * as XRegExp from 'xregexp';
|
2021-04-27 15:50:11 -04:00
|
|
|
import { FirebaseRedirectConfig } from './FirebaseRedirector';
|
|
|
|
import { FirebaseRedirectSource } from './FirebaseRedirectSource';
|
2018-01-25 05:13:30 -05:00
|
|
|
|
|
|
|
export class FirebaseRedirect {
|
2021-04-27 15:50:11 -04:00
|
|
|
source: FirebaseRedirectSource;
|
|
|
|
destination: string;
|
|
|
|
|
2021-04-27 15:50:12 -04:00
|
|
|
constructor({source, regex, destination}: FirebaseRedirectConfig) {
|
|
|
|
this.source = (typeof source === 'string') ?
|
|
|
|
FirebaseRedirectSource.fromGlobPattern(source) :
|
|
|
|
FirebaseRedirectSource.fromRegexPattern(regex!);
|
2021-04-27 15:50:11 -04:00
|
|
|
this.destination = destination;
|
|
|
|
}
|
2018-01-25 05:13:30 -05:00
|
|
|
|
2019-10-03 05:46:38 -04:00
|
|
|
replace(url: string): string | undefined {
|
2021-04-27 15:50:11 -04:00
|
|
|
const match = this.source.match(url);
|
2019-10-03 05:46:38 -04:00
|
|
|
|
|
|
|
if (!match) {
|
|
|
|
return undefined;
|
2018-01-25 05:13:30 -05:00
|
|
|
}
|
2019-10-03 05:46:38 -04:00
|
|
|
|
2021-04-27 15:50:11 -04:00
|
|
|
const namedReplacers = this.source.namedGroups.map<[RegExp, string]>(name => [ XRegExp(`:${name}`, 'g'), match[name] ]);
|
|
|
|
const restReplacers = this.source.restNamedGroups.map<[RegExp, string]>(name => [ XRegExp(`:${name}\\*`, 'g'), match[name] ]);
|
|
|
|
return XRegExp.replaceEach(this.destination, [...namedReplacers, ...restReplacers]);
|
2018-01-25 05:13:30 -05:00
|
|
|
}
|
|
|
|
}
|