Extract a method and add some typings

This commit is contained in:
Stefan Forstenlechner 2022-04-29 21:29:34 +02:00
parent 53e0e9bd1f
commit 30a21e820d
1 changed files with 41 additions and 27 deletions

View File

@ -14,10 +14,10 @@ const notEmpty = <TValue>(
return value !== null && value !== undefined;
};
const getRequestedPath = (req: express.Request) =>
const getRequestedPath = (req: express.Request): string =>
req.params[1] === undefined || req.params[1] === "/" ? "" : req.params[1];
const readThumbnails = (requestedPath: string) => {
const readThumbnails = (requestedPath: string): string[] => {
const requestedThumbnailPath = path.posix.join(
thumbnailPublicPath,
requestedPath
@ -27,7 +27,11 @@ const readThumbnails = (requestedPath: string) => {
: [];
};
const getSrc = (thumbnailExists: boolean, requestedPath: string, f: Dirent) =>
const getSrc = (
thumbnailExists: boolean,
requestedPath: string,
f: Dirent
): string =>
thumbnailExists
? path.posix.join("/staticImages", thumbnailPath, requestedPath, f.name)
: path.posix.join("/staticImages", requestedPath, f.name);
@ -37,7 +41,7 @@ const toImage = (
thumbnailExists: boolean,
requestedPath: string,
f: Dirent
) => {
): Image => {
const widthAndHeightSwap = metadata.orientation > 4; // see https://exiftool.org/TagNames/EXIF.html
return a<Image>({
src: getSrc(thumbnailExists, requestedPath, f),
@ -46,22 +50,12 @@ const toImage = (
});
};
export const getImages = async (
req: express.Request,
res: express.Response
) => {
const requestedPath = getRequestedPath(req);
try {
securityValidation(requestedPath);
const dirents = fs.readdirSync(path.posix.join(publicPath, requestedPath), {
withFileTypes: true,
});
const thumbnails = readThumbnails(requestedPath);
const imagesToBeLoaded = dirents
const getImagesToBeLoaded = (
dirents: Dirent[],
thumbnails: string[],
requestedPath: string
): Promise<Image | void>[] =>
dirents
.filter((f) => f.isFile())
.map((f) => {
const thumbnailExists: boolean = thumbnails.includes(f.name);
@ -83,6 +77,26 @@ export const getImages = async (
);
});
});
export const getImages = async (
req: express.Request,
res: express.Response
) => {
const requestedPath = getRequestedPath(req);
try {
securityValidation(requestedPath);
const dirents = fs.readdirSync(path.posix.join(publicPath, requestedPath), {
withFileTypes: true,
});
const thumbnails = readThumbnails(requestedPath);
const imagesToBeLoaded = getImagesToBeLoaded(
dirents,
thumbnails,
requestedPath
);
const images = (await Promise.all(imagesToBeLoaded)).filter(notEmpty);
res.json(a<Folder>({ images }));
} catch (e) {