All Projects → kruschid → Typesafe Routes

kruschid / Typesafe Routes

Licence: mit
Spices up your favorite routing library by adding type safety to plain string-based route definitions.

Programming Languages

typescript
32286 projects

Projects that are alternatives of or similar to Typesafe Routes

React Cool Starter
😎 🐣 A starter boilerplate for a universal web app with the best development experience and a focus on performance and best practices.
Stars: ✭ 1,083 (+4065.38%)
Mutual labels:  express, react-router
Universal React Tutorial
📓 How to build universal web apps with React.
Stars: ✭ 136 (+423.08%)
Mutual labels:  express, react-router
Simple Universal React Redux
The simplest possible Async Universal React & Redux Boilerplate app, that works on both Mac and Windows
Stars: ✭ 58 (+123.08%)
Mutual labels:  express, react-router
Diagonistician Reactjs Express Mongoose
Question - Answers demo SPA
Stars: ✭ 13 (-50%)
Mutual labels:  express, react-router
React
Extremely simple boilerplate, easiest you can find, for React application including all the necessary tools: Flow | React 16 | redux | babel 6 | webpack 3 | css-modules | jest | enzyme | express + optional: sass/scss
Stars: ✭ 244 (+838.46%)
Mutual labels:  express, react-router
Chat Buy React
Client for beginners to learn, built with React / Redux / Node
Stars: ✭ 1,026 (+3846.15%)
Mutual labels:  express, react-router
Reeakt
A modern React boilerplate to awesome web applications
Stars: ✭ 116 (+346.15%)
Mutual labels:  express, react-router
Express React Boilerplate
🚀🚀🚀 This is a tool that helps programmers create Express & React projects easily base on react-cool-starter.
Stars: ✭ 32 (+23.08%)
Mutual labels:  express, react-router
Ecommerce Site Template
A beautiful e-commerce template powered by React, Redux and other modern web tech.
Stars: ✭ 167 (+542.31%)
Mutual labels:  express, react-router
Express Webpack React Redux Typescript Boilerplate
🎉 A full-stack boilerplate that using express with webpack, react and typescirpt!
Stars: ✭ 156 (+500%)
Mutual labels:  express, react-router
React Redux Saucepan
A minimal and universal react redux starter project. With hot reloading, linting and server-side rendering
Stars: ✭ 86 (+230.77%)
Mutual labels:  express, react-router
Judo Heroes
A React application to showcase rendering with Universal JavaScript
Stars: ✭ 373 (+1334.62%)
Mutual labels:  express, react-router
Js Stack Boilerplate
Final boilerplate code of the JavaScript Stack from Scratch tutorial –
Stars: ✭ 145 (+457.69%)
Mutual labels:  express, react-router
Pro Mern Stack
Code Listing for the book Pro MERN Stack
Stars: ✭ 290 (+1015.38%)
Mutual labels:  express, react-router
React Ssr Setup
React Starter Project with Webpack 4, Babel 7, TypeScript, CSS Modules, Server Side Rendering, i18n and some more niceties
Stars: ✭ 678 (+2507.69%)
Mutual labels:  express, react-router
Geek Navigation
❤️ 极客猿梦导航-独立开发者的导航站!
Stars: ✭ 832 (+3100%)
Mutual labels:  express
Mevn Stack
Stars: ✭ 19 (-26.92%)
Mutual labels:  express
Ajcss
Stars: ✭ 6 (-76.92%)
Mutual labels:  express
Call Forwarding Node
A sample implementation of advanced call forwarding using Twilio, Node.js and Express.js.
Stars: ✭ 6 (-76.92%)
Mutual labels:  express
Vk To Telegram
Utility to forward posts from VK through callback API to telegram channel or chat
Stars: ✭ 24 (-7.69%)
Mutual labels:  express

Typesafe Routes

Spices up your favorite routing library by adding type-safety to plain string-based route definitions. Let typescript handle the detection of broken links in compilation time while you create maintainable software products.

You can use this utility with your favorite framework that follows path-to-regex syntax (although we only support a subset of it). You can find some demo applications with react-router or express in src/demo.

Typesafe Routes utilizes Template Literal Types and Recursive Conditional Types. These features are only available in typescript version 4.1 and above.

Installation (npm/yarn examples)

npm i typesafe-routes

# or

yarn add typesafe-routes

Usage

route(path: string, parserMap: Record<string, Parser>, children: Record<string, ChildRoute>)

  • path must be the path string according to the path-to-regex syntax.
  • parserMap contains parameter-specific Parser identified by parameter name
  • children assign children routes here in case you want to utilize serialization of nested routes

Examples

Basic Example
import { route, stringParser } from "typesafe-routes";

const accountRoute = route("/account/:accountId", {
  accountId: stringParser, // parser implicitly defines the static type (string) of 'accountId'
}, {});

// serialisation:
accountRoute({ accountId: "5c9f1e79e96c" }).$
// => "/account/5c9f1e79e96c"

// parsing:
accountRoute.parseParams({ accountId: "123"}).$
// => { accountId: "123" }

While stringParser is probably the most common parser/serializer there are also intParser, floatParser, dateParser, and booleanParser shipped with the module. But you are not limited to these. If you wish to implement your custom parserserializer just imlement the interface Parser<T>. You can find more details on that topic further down the page.

Nested Routes
import { route } from "typesafe-routes";

const detailsRoute = route("/details", {}, {})
const settingsRoute = route("/settings", {}, { detailsRoute });
const accountRoute = route("/account", {}, { settingsRoute });

accountRoute({}).settingsRoute({}).detailsRoute({}).$
// => "/account/settings/details"
Optional Parameters

Parameters can be suffixed with a question mark (?) to make a parameter optional.

import { route, intParser } from "typesafe-routes";

const userRoute = route("/user/:userId/:groupId?", {
  userId: intParser,
  groupId: intParser // parser is required also required for optional parameters
}, {});

userRoute({ userId: 342 }).$ // groupId is optional
// => "/user/342"
userRoute({ userId: 5453, groupId: 5464 }).$
// => "/user/5453/5464"
userRoute({ groupId: 464 }).$
// => error because userId is missing

// parsing:
userRoute.parseParams({ userId: "65", groupId: "212" });
// returns { userId: 6, groupId: 12 }
Query Parameters

Parameters can be prefixed with & to make the parameter a query parameter.

import { route, intParser } from "typesafe-routes";

const usersRoute = route("/users&:start&:limit", {
  start: intParser,
  limit: intParser,
}, {});

usersRoute({ start: 10, limit: 20 }).$
// returns "/users?start=10&limit=20"

When serialising nested routes query params are always being appended to the end of the locator string:

import { route, intParser } from "typesafe-routes";

const settingsRoute = route("/settings&:expertMode", {
  expertMode: booleanParser,
}, {});

const usersRoute = route("/users&:start&:limit", {
  start: intParser,
  limit: intParser,
}, {
  settingsRoute
});

usersRoute({ start: 10, limit: 20 }).settingsRoute({ expertMode: true })$
// returns "/users/settings?expertMode=true&start=10&limit=20"

userRoute.parseParams({ start: "10", limit: "20", expertMode: "false" });
// returns { start: 10, limit: 20, expertMode: false }
Parsers & Serializers

If you need to parse/serialize other datatypes than primitive types or dates or the build-in parsers don't meet your requirements for some reason you can create your own parsers with a few lines of code. The Parser<T> interface that helps yo to achieve that is defined as followed:

interface Parser<T> {
  parse: (s: string) => T;
  serialize: (x: T) => string;
}

The next example shows the implementation and usage of a typesafe Vector2D parser/serializer.

import { Parser, route } from "typesafe-routes";

interface Vector2D {
  x: number;
  y: number;
};

const vectorParser: Parser<Vector2D> = {
  serialize: (v) => btoa(JSON.stringify(v)),
  parse: (s) => JSON.parse(atob(s)),
};

const mapRoute = route("/map&:pos", { pos: vectorParser }, {});

mapRoute({ pos: { x: 1, y: 0 }}).$;
// returns "/map?pos=eyJ4IjoxLCJ5IjowfQ%3D%3D"

vectorParser.parseParams({pos: "eyJ4IjoxLCJ5IjowfQ=="})
// returns { pos: { x: 1, y: 0 }}
React Router Utilities

While library is not limited to react (e.g. express demo code in src/demo proves this statement) I've decided to add a few juicy react-router-specific utilities to this library.

useRouteParams(route: RouteNode)

Internally useRouteParams depends on useParams that will be imported from the optional dependency react-router-dom. However unlike useParams the useRouteParams function is able to parse query strings by utilising qs.

import { route } from "typesafe-routes";
import { useRouteParams } from "typesafe-routes/react-router";

const topicRoute = route("/:topicId&:limit?", {
  topicId: stringParser,
  limit: floatParser,
}, {});

const Component = () => {
  const { topicId, limit } = useRouteParams(topicRoute);

  return <>{...}</>;
}

<Link> and <NavLink>

Same as the original <Link> and <NavLink> from react-router-dom but require the to property to be a route:

import { route } from "typesafe-routes";
import { Link, NavLink } from "typesafe-routes/react-router";

const topicRoute = route("/topic", {}, {});

<Link to={topicRoute({})}>Topic</Link>
<NavLink to={topicRoute({})}>Topic</NavLink>

<Link to="/topic">Topic</Link> // error "to" prop can't be string 
<NavLink to="/topic">Topic</NavLink> // error "to" prop can't be string 

template

typesafe-routes implements a subset of template syntax of react-router and thus is compatible with it. But since specifying additional query params would break the compatibility (react-router doesn't understand the & prefix) the .template property doesn't contain any of such parameters and can be used to define router in your react-router app:

import { route } from "typesafe-routes";

const topicRoute = route("/:topicId&:limit?", {
  topicId: stringParser,
  limit: floatParser,
}, {});

<Route path={topicRoute.template}> // template only contains the "/:topicId" path
  <Topic />
</Route>

Developer Fuel

You can have some impact and improve the quality of this project not only by writing code and opening PRs but also by buying me a cup of fresh coffee as a small reward for my effort I put into the development of this library. ¡Gracias!

Buy Me A Coffee

Roadmap

So far I consider this library feature-complete that's why I will be mainly concerned about fixing bugs and improving the API. However, if some high demand for additional functionality or PRs shows up I might be considering expanding the scope.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].