Creating a list of "page" objects from a file system. which looks like
pages/
- Home.jsx
- Blog.jsx
- Post.Blog.jsx
- Posts.Blog.jsx
- private/
-- Admin.jsx
-- Dashboard.jsx
-- admin/
--- Main.Admin.jsx
-- author/
--- Post.Admin.jsx
-- editor/
--- Editor.Admin.jsx
- For Filenames with single name before the extension, I want to return objects that look like:
{name:"Home", isPrivate:false, permission:"guest"}
- for Dot separated names outside of the private directory, I want to look like:
{name:"Blog", isPrivate:false permission:"guest", subpages:[{name:"Post", isPrivate:false, permission:"guest"},{name:"Posts", isPrivate:false, permission:"guest"},...]}
- For Files inside of the Private will have the "isPrivate" key/val pair set to true, the "permission" key/val set to the subdirectory it lives in. for example:
{name:Admin, isPrivate:true permission:"private", subpages:[{name:"Post",isPrivate:true, permission:"author"},{name:"Main", isPrivate:true, permission:"admin"},...]}
I've tried for loops inside of the conditional to add subpages to the current page object being created but that caused issues when I tried to use recursion at that level to access the files in the private directory or its subfolders, so i broke it back down to this and am trying to build up from here.
const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)
const directoryPath = join(__dirname,'../../../../ui/src/pages')
const files = []
const createList = (dir)=>{
const fileMatrix = fs.readdirSync(dir)
fileMatrix.map(file=>{
const filePath = join(dir,file)
const stats = fs.statSync(filePath)
const isDir = stats.isDirectory()
const isPrivate = filePath.includes('private')
const permission = isPrivate ? path.dirname(filePath).split('/').pop():"guest"
const fileParts = path.basename(filePath,'.jsx').split('.')
const fileName = fileParts[0]
const parent = fileParts[1]
if (!isDir){
file = {
name:fileName,
isPrivate,
permission
}
console.log(file)
}
else if(isDir){
createList(filePath)
}
})
}
createList(directoryPath);