Skip to content

Commit 060cc5d

Browse files
committed
update get-emails-directory code on preview-server
1 parent c2680bb commit 060cc5d

File tree

1 file changed

+24
-13
lines changed

1 file changed

+24
-13
lines changed

apps/preview-server/src/utils/get-emails-directory-metadata.ts

Lines changed: 24 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -2,25 +2,33 @@
22
import fs from 'node:fs';
33
import path from 'node:path';
44

5-
const isFileAnEmail = (fullPath: string): boolean => {
6-
const stat = fs.statSync(fullPath);
5+
const isFileAnEmail = async (fullPath: string): Promise<boolean> => {
6+
let fileHandle: fs.promises.FileHandle;
7+
try {
8+
fileHandle = await fs.promises.open(fullPath, 'r');
9+
} catch (exception) {
10+
console.warn(exception);
11+
return false;
12+
}
13+
const stat = await fileHandle.stat();
714

8-
if (stat.isDirectory()) return false;
15+
if (stat.isDirectory()) {
16+
await fileHandle.close();
17+
return false;
18+
}
919

1020
const { ext } = path.parse(fullPath);
1121

12-
if (!['.js', '.tsx', '.jsx'].includes(ext)) return false;
13-
14-
// This is to avoid a possible race condition where the file doesn't exist anymore
15-
// once we are checking if it is an actual email, this could cause issues that
16-
// would be very hard to debug and find out the why of it happening.
17-
if (!fs.existsSync(fullPath)) {
22+
if (!['.js', '.tsx', '.jsx'].includes(ext)) {
23+
await fileHandle.close();
1824
return false;
1925
}
2026

2127
// check with a heuristic to see if the file has at least
2228
// a default export (ES6) or module.exports (CommonJS) or named exports (MDX)
23-
const fileContents = fs.readFileSync(fullPath, 'utf8');
29+
const fileContents = await fileHandle.readFile('utf8');
30+
31+
await fileHandle.close();
2432

2533
// Check for ES6 export default syntax
2634
const hasES6DefaultExport = /\bexport\s+default\b/gm.test(fileContents);
@@ -80,10 +88,13 @@ export const getEmailsDirectoryMetadata = async (
8088
withFileTypes: true,
8189
});
8290

83-
const emailFilenames = dirents
84-
.filter((dirent) =>
91+
const isEmailPredicates = await Promise.all(
92+
dirents.map((dirent) =>
8593
isFileAnEmail(path.join(absolutePathToEmailsDirectory, dirent.name)),
86-
)
94+
),
95+
);
96+
const emailFilenames = dirents
97+
.filter((_, i) => isEmailPredicates[i])
8798
.map((dirent) =>
8899
keepFileExtensions
89100
? dirent.name

0 commit comments

Comments
 (0)