Last active
April 6, 2020 19:04
-
-
Save josefaidt/6dec379927a2594f28d4ca022e3a253f to your computer and use it in GitHub Desktop.
basic express filesystem router
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import fs from 'fs'; | |
import path from 'path'; | |
import express from 'express'; | |
const getFileRoutes = async ({ directory, ignore = /_/, include = /\.js$/ }) => { | |
const result = new Map(); | |
const nestedGetFiles = async nestedDirectory => { | |
const files = fs.readdirSync(nestedDirectory, { withFileTypes: true }); | |
for (let i = 0; i < files.length; i++) { | |
const f = files[i]; | |
const fPath = path.join(nestedDirectory, f.name); | |
if (!ignore.test(f.name)) { | |
if (f.isDirectory()) { | |
nestedGetFiles(fPath); | |
} else if (include.test(f.name)) { | |
// eslint-disable-next-line no-await-in-loop | |
const mod = await import(fPath); | |
result.set( | |
`${nestedDirectory}/${f.name}` | |
.replace(directory, '') | |
.slice(1) | |
.replace(/\.js$/, ''), | |
mod?.default || mod | |
); | |
} | |
} | |
} | |
}; | |
await nestedGetFiles(directory); | |
return result; | |
}; | |
const defaultHandler = (req, res) => | |
res.json({ | |
message: | |
'This route is not yet set up, to complete the setup export a default function accepting `request` and `response` as arguments.', | |
}); | |
const fsRouter = directory => { | |
const router = express.Router(); | |
const project = path.resolve(process.cwd(), directory); | |
getFileRoutes({ directory: project }).then(files => { | |
for (const [path, handler] of files.entries()) { | |
if (typeof handler === 'function') { | |
router.all(`/${path}`, handler); | |
} else { | |
console.warn(`[FS-ROUTER] Warning! Route "${path}" does not export a function, applying default handler`); | |
router.all(`/${path}`, defaultHandler); | |
} | |
} | |
}); | |
return router; | |
}; | |
export default fsRouter; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage