|
| 1 | +import { asyncErrorHandler } from './middleware/errors' |
| 2 | +import { createBodyValidator, createQueryValidator } from './validation' |
| 3 | +import { |
| 4 | + AllowedMethod, |
| 5 | + AllowedMethods, |
| 6 | + Endpoint, |
| 7 | + ExpressMethod, |
| 8 | + ExpressMethods, |
| 9 | +} from './types' |
| 10 | +import { RequestHandler, Router } from 'express' |
| 11 | +import globCb from 'glob' |
| 12 | +import { promisify } from 'util' |
| 13 | + |
| 14 | +const router = Router() |
| 15 | +const glob = promisify(globCb) |
| 16 | + |
| 17 | +interface EndpointModule extends Partial<Record<AllowedMethod, Endpoint>> { |
| 18 | + validation?: Partial<Record<AllowedMethod, Record<'body' | 'query', any>>> |
| 19 | + guestAccess?: boolean |
| 20 | + ensureAdmin?: boolean |
| 21 | +} |
| 22 | + |
| 23 | +interface IInitFsRoutingParams { |
| 24 | + ensureAdmin: RequestHandler |
| 25 | + ensureAuthenticated: RequestHandler |
| 26 | + routesPath: string |
| 27 | +} |
| 28 | + |
| 29 | +export const initFsRouting = async ({ |
| 30 | + ensureAdmin, |
| 31 | + ensureAuthenticated, |
| 32 | + routesPath, |
| 33 | +}: IInitFsRoutingParams) => { |
| 34 | + // Apply middleware first |
| 35 | + console.log('Mounting routes') |
| 36 | + let numberOfRoutes = 0 |
| 37 | + let numberOfFiles = 0 |
| 38 | + let numberOfRoutesWithoutValidation = 0 |
| 39 | + // Get all of the files under the routes directory |
| 40 | + const files = await getFiles(routesPath) |
| 41 | + numberOfFiles = files.length + 1 |
| 42 | + // Sort by reverse alphabetical order, so items with colons are below items without colons. This makes it so we can override param routes. |
| 43 | + const promises = files |
| 44 | + .sort() |
| 45 | + .reverse() |
| 46 | + .map(async path => { |
| 47 | + // get the endpoint path for express by removing the base filesystem path |
| 48 | + let routePath = path.replace(routesPath, '') |
| 49 | + // remove the js portion |
| 50 | + routePath = routePath.replace(/.js$/, '') |
| 51 | + // replace index at beggining with / |
| 52 | + routePath = routePath.replace(/^\/index/, '/') |
| 53 | + // remove index at end |
| 54 | + routePath = routePath.replace(/\/index$/, '') |
| 55 | + // do not handle routes that begin with _ |
| 56 | + const lastSlash = routePath.lastIndexOf('/') |
| 57 | + const endpointName = routePath.substr(lastSlash) |
| 58 | + |
| 59 | + if (endpointName.startsWith('/_')) { |
| 60 | + console.log('Skipping mounting:', routePath) |
| 61 | + return |
| 62 | + } |
| 63 | + |
| 64 | + // import route |
| 65 | + const module: EndpointModule = await import(path) |
| 66 | + // here we have the chance to alias routes to different locations, by storing multiple paths in routePaths |
| 67 | + const routePaths = [routePath] |
| 68 | + |
| 69 | + // we treat authentication differently on u routes and API routes, can get rid of this when client is separted from API server |
| 70 | + |
| 71 | + console.log(`Mounting route:`, routePaths[0]) |
| 72 | + const [routesMounted, routesWithoutValidation] = mountEndpoints({ |
| 73 | + paths: routePaths, |
| 74 | + endpoints: module, |
| 75 | + ensureAdmin, |
| 76 | + ensureAuthenticated, |
| 77 | + }) |
| 78 | + numberOfRoutes += routesMounted |
| 79 | + numberOfRoutesWithoutValidation += routesWithoutValidation |
| 80 | + if (routesMounted === 0) console.log('\t | No exported HTTP methods') |
| 81 | + }) |
| 82 | + await Promise.all(promises).then(() => |
| 83 | + console.log( |
| 84 | + `${numberOfFiles} route files processed, ${numberOfRoutes} routes mounted, ${numberOfRoutesWithoutValidation} routes do not have validation.` |
| 85 | + ) |
| 86 | + ) |
| 87 | + return router |
| 88 | +} |
| 89 | + |
| 90 | +// Returns the number of routes mounted, and the number of routes that had validation |
| 91 | +interface IMountEndpointsParams { |
| 92 | + paths: string[] |
| 93 | + endpoints: EndpointModule |
| 94 | + ensureAdmin: RequestHandler |
| 95 | + ensureAuthenticated: RequestHandler |
| 96 | +} |
| 97 | + |
| 98 | +const mountEndpoints = ({ |
| 99 | + paths, |
| 100 | + endpoints, |
| 101 | + ensureAdmin, |
| 102 | + ensureAuthenticated, |
| 103 | +}: IMountEndpointsParams): [number, number] => { |
| 104 | + let mounted = 0 |
| 105 | + let numberWithValidation = 0 |
| 106 | + |
| 107 | + const validation = endpoints.validation |
| 108 | + const guestAccess = endpoints.guestAccess |
| 109 | + const adminOnly = endpoints.ensureAdmin |
| 110 | + |
| 111 | + Object.entries(endpoints).map(([method, endpoint]) => { |
| 112 | + // skip exports that are not allowed Express methods |
| 113 | + const expressMethodName = method.toLowerCase() |
| 114 | + if (!isExpressMethod(expressMethodName)) { |
| 115 | + return |
| 116 | + } |
| 117 | + let handlers: RequestHandler[] = [] |
| 118 | + if (!guestAccess) { |
| 119 | + handlers.push(ensureAuthenticated) |
| 120 | + |
| 121 | + if (adminOnly) { |
| 122 | + handlers.push(ensureAdmin) |
| 123 | + } |
| 124 | + } |
| 125 | + let validationMsg = '' |
| 126 | + // check if it should have validation |
| 127 | + if (validation?.hasOwnProperty(method)) { |
| 128 | + if (isHttpMethod(method)) { |
| 129 | + const hasBody = validation[method]?.body |
| 130 | + const hasQuery = validation[method]?.query |
| 131 | + console.log(`\t | Mounting ${method} with validation`) |
| 132 | + // verify that the validation object has the correct keys (query and body) |
| 133 | + if (hasQuery) { |
| 134 | + validationMsg = `\t | ${method} has query validation\n` |
| 135 | + // add optional key property to all validators |
| 136 | + const query = { |
| 137 | + ...validation[method]?.query, |
| 138 | + properties: { |
| 139 | + ...validation[method]?.query?.properties, |
| 140 | + key: { type: 'string', description: 'API Key' }, |
| 141 | + }, |
| 142 | + } |
| 143 | + // Add query validation handler |
| 144 | + handlers.push( |
| 145 | + createQueryValidator({ |
| 146 | + query: query, |
| 147 | + // body: validation[method]?.body, |
| 148 | + }) |
| 149 | + ) |
| 150 | + } |
| 151 | + if (hasBody) { |
| 152 | + // Add body validation handler |
| 153 | + validationMsg += `\t | ${method} has body validation` |
| 154 | + handlers.push( |
| 155 | + createBodyValidator({ |
| 156 | + body: validation[method]?.body, |
| 157 | + }) |
| 158 | + ) |
| 159 | + } |
| 160 | + } |
| 161 | + } else { |
| 162 | + // this endpoint doesn't have validation yet |
| 163 | + validationMsg += '- no validation' |
| 164 | + numberWithValidation++ |
| 165 | + } |
| 166 | + |
| 167 | + const hasMiddleware = Array.isArray(endpoint) |
| 168 | + handlers = hasMiddleware |
| 169 | + ? [...handlers, ...endpoint] |
| 170 | + : [...handlers, endpoint] |
| 171 | + // add async handling to all handlers |
| 172 | + handlers = handlers.map(handler => asyncErrorHandler(handler)) |
| 173 | + // mount the route |
| 174 | + router[expressMethodName](paths, handlers) |
| 175 | + console.log(`\t | ${method} ${validationMsg}`) |
| 176 | + mounted++ |
| 177 | + }) |
| 178 | + return [mounted, numberWithValidation] |
| 179 | +} |
| 180 | + |
| 181 | +const isExpressMethod = (method: string): method is ExpressMethod => { |
| 182 | + return ExpressMethods.includes(method as ExpressMethod) |
| 183 | +} |
| 184 | + |
| 185 | +const isHttpMethod = (exportKey: string): exportKey is AllowedMethod => { |
| 186 | + return AllowedMethods.includes(exportKey as AllowedMethod) |
| 187 | +} |
| 188 | + |
| 189 | +const getFiles = async (src: string) => { |
| 190 | + return glob(src + '/**/*.js', { nodir: true }) |
| 191 | +} |
| 192 | + |
| 193 | +export default router |
0 commit comments