@stembord/router
v0.2.5
Published
router
Downloads
21
Readme
ts-router
router
import { Router } from "@stembord/router";
const router = new Router();
router.use(
"/",
(context: IContext) =>
new Promise((resolve: (context: IContext) => void) => {
setTimeout(() => {
console.log("middleware");
resolve(context);
}, 0);
})
);
router.route("/", () => {
console.log("Home");
});
router.route("/parent/:parent_id", (context: IContext) => {
console.log("Parent", context.params);
});
router.route("/parent/:parent_id/child/:child_id", (context: IContext) => {
console.log("Child", context.params);
});
router.route(
"/parent/:parent_id/child/:child_id/grand_child/:grand_child_id",
(context: IContext) => {
console.log("Grandchild", context.params);
}
);
router.route("/redirect", (context: IContext) => {
context.redirectUrl = url.parse("/");
});
router.route("/error", () => {
throw new Error("rejected");
});
router.use("/", (context: IContext) => {
if (!context.resolved()) {
context.redirectUrl = url.parse("/not_found");
}
context.end();
});
use with @stembord/location
import { Location, getUrlPathname } from "@stembord/location";
const handler = (url: url.UrlWithParsedQuery) => {
const context = createContext(url);
return router.handle(context).then(
() => {
if (context.redirectUrl) {
return Promise.reject(context.redirectUrl);
} else {
return Promise.resolve(context.url);
}
},
error => {
if (error && context.redirectUrl) {
location.set(getUrlPathname(context.redirectUrl));
return Promise.reject(error);
} else if (error) {
return Promise.reject(error);
} else {
return Promise.reject(null);
}
}
);
};
const location = new Location(window, { html5Mode: true, handler });
// on load
location.init();