API: directory-list: handle empty input case and improve error responses

This commit is contained in:
Jesse Chan
2021-02-15 23:09:12 +08:00
parent 945c593393
commit ad535e2cde
3 changed files with 57 additions and 51 deletions
+2 -38
View File
@@ -50,42 +50,6 @@ export const sanitizePath = (input?: string): string => {
// eslint-disable-next-line no-control-regex
const controlRe = /[\x00-\x1f\x80-\x9f]/g;
return path.resolve(input).replace(controlRe, '');
};
export const getDirectoryList = async (inputPath: string) => {
if (typeof inputPath !== 'string') {
throw fileNotFoundError();
}
const sourcePath = inputPath.replace(/^~/, homedir());
const resolvedPath = sanitizePath(sourcePath);
if (!isAllowedPath(resolvedPath)) {
throw accessDeniedError();
}
const directories: Array<string> = [];
const files: Array<string> = [];
fs.readdirSync(resolvedPath).forEach((item) => {
const joinedPath = path.join(resolvedPath, item);
if (fs.existsSync(joinedPath)) {
if (fs.statSync(joinedPath).isDirectory()) {
directories.push(item);
} else {
files.push(item);
}
}
});
const hasParent = /^.{0,}:?(\/|\\){1,1}\S{1,}/.test(resolvedPath);
return {
directories,
files,
hasParent,
path: resolvedPath,
separator: path.sep,
};
return path.resolve(input.replace(/^~/, homedir()).replace(controlRe, ''));
};