2022-06-28 16:22:49 +00:00
|
|
|
import { path } from "./interface";
|
|
|
|
import handler from "./handler";
|
|
|
|
import { pathToRegexp } from "path-to-regexp";
|
|
|
|
|
|
|
|
interface matchedStatus {
|
|
|
|
matched: boolean;
|
|
|
|
attributes: {
|
|
|
|
name: string;
|
|
|
|
value: string | undefined;
|
|
|
|
}[];
|
|
|
|
}
|
|
|
|
|
2022-07-03 19:15:42 +00:00
|
|
|
interface regExpKey {
|
|
|
|
name: string;
|
|
|
|
prefix: string;
|
|
|
|
suffix: string;
|
|
|
|
pattern: string;
|
|
|
|
modifier: string;
|
|
|
|
};
|
|
|
|
|
2022-06-28 16:22:49 +00:00
|
|
|
export class route {
|
2022-07-03 19:15:42 +00:00
|
|
|
private paths: path[];
|
2022-06-29 15:00:01 +00:00
|
|
|
public handlers: handler<any, any>[];
|
2022-07-03 19:15:42 +00:00
|
|
|
private regExps: { regExp: RegExp, keys: regExpKey[] }[] = [];
|
2022-06-28 16:22:49 +00:00
|
|
|
|
2022-06-29 15:00:01 +00:00
|
|
|
constructor(paths: path[], handlers: handler<any, any>[]) {
|
2022-06-28 16:22:49 +00:00
|
|
|
this.paths = paths;
|
2022-06-29 15:00:01 +00:00
|
|
|
this.handlers = handlers;
|
2022-07-03 19:15:42 +00:00
|
|
|
|
|
|
|
this.paths.forEach(path => {
|
|
|
|
const keys: regExpKey[] = [];
|
|
|
|
this.regExps.push({ regExp: pathToRegexp(path, keys), keys });
|
|
|
|
})
|
2022-06-28 16:22:49 +00:00
|
|
|
}
|
|
|
|
async exec(path: string): Promise<matchedStatus> {
|
|
|
|
let Answer = await Promise.all<Promise<matchedStatus>>(
|
2022-07-03 19:15:42 +00:00
|
|
|
this.regExps.map(async (it) => {
|
|
|
|
|
|
|
|
const answer = it.regExp.exec(path);
|
2022-06-28 16:22:49 +00:00
|
|
|
if (answer === null)
|
|
|
|
return {
|
|
|
|
matched: false,
|
|
|
|
attributes: [],
|
|
|
|
};
|
|
|
|
|
|
|
|
let attributes: matchedStatus["attributes"] = [];
|
|
|
|
|
2022-07-03 19:15:42 +00:00
|
|
|
it.keys.forEach((key, index) => {
|
2022-06-28 16:22:49 +00:00
|
|
|
attributes.push({
|
|
|
|
name: key.name,
|
|
|
|
value: answer[index + 1],
|
|
|
|
});
|
|
|
|
});
|
|
|
|
|
|
|
|
return {
|
|
|
|
matched: true,
|
|
|
|
attributes: attributes,
|
|
|
|
};
|
|
|
|
})
|
|
|
|
);
|
|
|
|
Answer = Answer.filter((it) => it.matched);
|
|
|
|
if (Answer.length === 0)
|
|
|
|
return {
|
|
|
|
matched: false,
|
|
|
|
attributes: [],
|
|
|
|
};
|
|
|
|
else return Answer[0];
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export default route;
|