-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathgenerateFileExtension.ts
More file actions
61 lines (55 loc) · 1.44 KB
/
generateFileExtension.ts
File metadata and controls
61 lines (55 loc) · 1.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import fs from "fs-extra";
import path from "path";
import {
layoutTemplate,
pageTemplate,
loadingTemplate,
errorTemplate,
globalErrorsTemplate,
notFoundTemplate,
templateFile,
middlewareTemplate,
routeTemplate,
defaultFileTemplate,
} from "./templates";
type TemplateFunction = (name: string) => string;
const defaultTemplates: Record<string, TemplateFunction> = {
page: pageTemplate,
loading: loadingTemplate,
layout: layoutTemplate,
error: errorTemplate,
template: templateFile,
"global-error": globalErrorsTemplate,
"not-found": notFoundTemplate,
middleware: middlewareTemplate,
route: routeTemplate,
default: defaultFileTemplate,
};
export async function generateFile(
type: string,
filePath: string,
fileTemplate: string,
fileExtension = ".tsx",
name: string = "",
customType: string = ""
): Promise<boolean> {
const fileName = `${type}${fileExtension}`;
const pathToCreateFile = path.join(filePath, fileName);
const templateContent =
fileTemplate || defaultTemplates[type || customType](name);
try {
await fs.ensureDir(filePath);
const fileExists = await fs.pathExists(pathToCreateFile);
if (fileExists) {
return false;
}
await fs.writeFile(pathToCreateFile, templateContent, { encoding: "utf8" });
return true;
} catch (error) {
throw new Error(
`Error creating file: ${
error instanceof Error ? error.message : String(error)
}`
);
}
}