angular-component / router

Angular Component Router - A declarative router for Angular applications
MIT License
253 stars 16 forks source link

Consider replacing `pathToRegexp` with built-in function #58

Closed meeroslav closed 3 years ago

meeroslav commented 4 years ago

pathToRegexp provides nice functionality for parsing routes, but also includes a lot of functionality we do not use or need.

Simple built-in function could reduce footprint further. Take a look at following:

const wrap = (regexBody: string): string => {
  return `/^${regexBody}/i`
}

const div = '\/';
const end = '$';
const nEnd = '[]|$'; // null or end
const pathEnd = `[\/#\?]`;
const param = `([^\/#\?]+?)`;

const books = wrap(`${div}books(?:${pathEnd}(?=${nEnd}))?(?=${pathEnd}|${nEnd})`); // '/books' + exact false
const login = wrap(`${div}login${pathEnd}?${end}`); // '/login'
const id = wrap(`(?:${div}${param})${pathEnd}?${end}`); // '/:id'
const home = wrap(`${pathEnd}?${end}`); // '/'
const wildcard = wrap(`(?:${pathEnd}(?=${nEnd}))?`); // '/' + exact false

const booksFind = wrap(`${div}books${div}find${pathEnd}?${end}`); // '/books/find'
const booksId = wrap(`${div}books(?:${div}${param})${pathEnd}?${end}`); // '/books/:id'
const booksRoot = wrap(`${div}books${pathEnd}?${end}`); // '/books'
const booksWildcard = wrap(`${div}books(?:${pathEnd}(?=${nEnd}))?(?=${pathEnd}|${nEnd})`); // '/books' + exact false

With these few common patterns we can describe every route matcher Regexp

meeroslav commented 3 years ago

Type checked URL router: https://ja.nsommer.dk/articles/type-checked-url-router.html

brandonroberts commented 3 years ago

I think this is worth exploring. We also would need to get the path and params info with the internal matcher

meeroslav commented 3 years ago

The path type checking, unfortunately, requires Template Literal Types which landed in TypeScript v4.1. We can park this for later. But internal matcher is still possible.