UNPKG

@chubbyts/chubbyts-framework

Version:

A minimal, highly performant middleware PSR-15 inspired function based micro framework built with as little complexity as possible, aimed primarily at those developers who want to understand all the vendors they use.

80 lines (79 loc) 2.6 kB
import { createRoute } from './route.js'; /** * ```ts * import type { Group } from '@chubbyts/chubbyts-framework/dist/router/group'; * import type { Route } from '@chubbyts/chubbyts-framework/dist/router/route'; * * const group: Group = { ..., _group: 'Group' }; * const route: Route = { ..., _route: 'Route' }; * * isGroup(group) // true * isGroup(route) // false * ``` */ export const isGroup = (group) => { return typeof group === 'object' && null !== group && '_group' in group; }; /** * ```ts * import type { Group } from '@chubbyts/chubbyts-framework/dist/router/group'; * import { createGroup } from '@chubbyts/chubbyts-framework/dist/router/group'; * import type { Route } from '@chubbyts/chubbyts-framework/dist/router/route'; * * const listRoute: Route = ...; * const createRoute: Route = ...; * const readRoute: Route = ...; * const updateRoute: Route = ...; * const deleteRoute: Route = ...; * * const group: Group = createGroup({ * path: '/api/users', * children: [listRoute, createRoute, readRoute, updateRoute, deleteRoute], * }); * ``` */ export const createGroup = ({ path, children, middlewares, pathOptions }) => { return { path, children, middlewares: middlewares ?? [], pathOptions: pathOptions ?? {}, _group: 'Group', }; }; /** * ```ts * import type { Group } from '@chubbyts/chubbyts-framework/dist/router/group'; * import { createGroup, getRoutes } from '@chubbyts/chubbyts-framework/dist/router/group'; * import type { Route } from '@chubbyts/chubbyts-framework/dist/router/route'; * * const group: Group = createGroup({ ... }); * * const routes: Array<Route> = getRoutes(group); * ``` */ export const getRoutes = (group) => { return group.children.flatMap((child) => { const childPath = group.path + child.path; const childMiddlewares = [...group.middlewares, ...child.middlewares]; const childPathOptions = { ...group.pathOptions, ...child.pathOptions }; if (isGroup(child)) { return getRoutes(createGroup({ path: childPath, children: child.children, middlewares: childMiddlewares, pathOptions: childPathOptions, })); } return [ createRoute({ method: child.method, path: childPath, name: child.name, handler: child.handler, middlewares: childMiddlewares, pathOptions: childPathOptions, }), ]; }); };