-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.js
More file actions
175 lines (138 loc) · 4.12 KB
/
utils.js
File metadata and controls
175 lines (138 loc) · 4.12 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
import { dirname } from "path";
import { fileURLToPath } from "url";
import { promises as fs } from "fs";
import multer from "multer";
export const __dirname = dirname(fileURLToPath(import.meta.url));
const ROOT_PATH = `${__dirname}/projects`;
const notExist = (e) => e.code === "ENOENT";
const truncPath = (p) => p.split("/").slice(0, -1).join("/");
export async function createFile(fileData, filePath, fileExt = "json") {
const fileName = `${ROOT_PATH}/${filePath}.${fileExt}`;
try {
if (fileExt === "json") {
await fs.writeFile(fileName, JSON.stringify(fileData, null, 2));
} else {
await fs.writeFile(fileName, fileData);
}
} catch (err) {
if (notExist(err)) {
await fs.mkdir(truncPath(`${ROOT_PATH}/${filePath}`), {
recursive: true,
});
return createFile(fileData, filePath, fileExt);
}
throw err;
}
}
export async function readFile(filePath, fileExt = "json") {
const fileName = `${ROOT_PATH}/${filePath}.${fileExt}`;
let fileHandler = null;
try {
fileHandler = await fs.open(fileName);
const fileContent = await fileHandler.readFile("utf-8");
return fileExt === "json" ? JSON.parse(fileContent) : fileContent;
} catch (err) {
if (notExist(err)) {
throw { status: 404, message: "Not found" };
}
throw err;
} finally {
fileHandler?.close();
}
}
export async function removeFile(filePath, fileExt = "json") {
const fileName = `${ROOT_PATH}/${filePath}.${fileExt}`;
try {
await fs.unlink(fileName);
await removeDir(truncPath(`${ROOT_PATH}/${filePath}`));
} catch (err) {
if (notExist(err)) {
throw { status: 404, message: "Not found" };
}
throw err;
}
}
async function removeDir(dirPath, rootPath = ROOT_PATH) {
if (dirPath === rootPath) return;
const isEmpty = (await fs.readdir(dirPath)).length < 1;
if (isEmpty) {
await fs.rmdir(dirPath);
removeDir(truncPath(dirPath));
}
}
export async function getFileNames(path = ROOT_PATH) {
let fileNames = [];
try {
const files = await fs.readdir(path);
if (files.length < 1) return fileNames;
for (let file of files) {
file = `${path}/${file}`;
const isDir = (await fs.stat(file)).isDirectory();
if (isDir) {
fileNames = fileNames.concat(await getFileNames(file));
} else {
fileNames.push(file);
}
}
return fileNames;
} catch (err) {
if (notExist(err)) {
throw { status: 404, message: "Not found" };
}
throw err;
}
}
export const uploadFile = multer({
storage: multer.diskStorage({
destination: (req, file, cb) => {
const dirPath = `${ROOT_PATH}/${req.body.project_name.replace(
file.originalname.replace(".json", ""),
""
)}`;
fs.mkdir(dirPath, { recursive: true }).then(() => {
cb(null, dirPath);
});
},
filename: (_, file, cb) => {
cb(null, file.originalname);
},
}),
});
const strCollator = new Intl.Collator();
const numCollator = new Intl.Collator([], { numeric: true });
export const queryMap = {
offset: (items, count) => items.slice(count),
limit: (items, count) => items.slice(0, count),
sort(items, field = "id", order = "asc") {
const isString =
typeof items[0][field] === "string" && Number.isNaN(items[0][field]);
const collator = isString ? strCollator : numCollator;
return items.sort((a, b) =>
order.toLowerCase() === "asc"
? collator.compare(a[field], b[field])
: collator.compare(b[field], a[field])
);
},
};
export function areEqual(a, b) {
if (a === b) return true;
if (a instanceof Date && b instanceof Date)
return a.getTime() === b.getTime();
if (!a || !b || (typeof a !== "object" && typeof b !== "object"))
return a === b;
if (a.prototype !== b.prototype) return false;
const keys = Object.keys(a);
if (keys.length !== Object.keys(b).length) return false;
return keys.every((k) => areEqual(a[k], b[k]));
}
export function isJson(item) {
try {
item = JSON.parse(item);
} catch (e) {
return false;
}
if (typeof item === "object" && item !== null) {
return true;
}
return false;
}