re-nav/source/redirect/base.ts

56 lines
1.5 KiB
TypeScript
Raw Normal View History

2022-10-19 19:10:41 +00:00
import {customAlphabet} from 'nanoid';
export const matcherTypes = ['hostname'] as const;
export const redirectTypes = ['hostname', 'simple'] as const;
2022-10-05 17:08:17 +00:00
export type MatcherType = typeof matcherTypes[number];
export type RedirectType = typeof redirectTypes[number];
2022-10-19 11:31:53 +00:00
export function narrowMatcherType(value: string): value is MatcherType {
return matcherTypes.includes(value as MatcherType);
}
export function narrowRedirectType(value: string): value is RedirectType {
return redirectTypes.includes(value as RedirectType);
}
2022-10-05 17:08:17 +00:00
2022-10-12 22:04:51 +00:00
export type Matcher = {
matcherType: MatcherType;
2022-10-12 22:04:51 +00:00
toMatch: string;
};
export type RedirectParameters = {
redirectType: RedirectType;
};
2022-10-05 17:08:17 +00:00
export abstract class Redirect<P extends RedirectParameters> {
2022-10-19 19:10:41 +00:00
public static generateId(): string {
const alphabet = 'abcdefghijklmnopqrstuvwxyz';
const nanoid = customAlphabet(`${alphabet}${alphabet.toUpperCase()}`, 20);
return nanoid();
}
public id: string;
constructor(public parameters: P & Matcher, id?: string) {
this.id = id ?? Redirect.generateId();
}
2022-10-12 22:04:51 +00:00
public isMatch(url: URL): boolean {
if (this.parameters.matcherType === 'hostname') {
const hostname = url.hostname.startsWith('www.')
? url.hostname.slice(4)
: url.hostname;
return hostname === this.parameters.toMatch;
2022-10-12 22:04:51 +00:00
}
return false;
}
2022-10-05 17:08:17 +00:00
public abstract redirect(url: URL | string): URL;
public abstract get redirectValue(): string;
public abstract set redirectValue(value: string);
2022-10-05 17:08:17 +00:00
}