-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfindPathInDb.ts
32 lines (31 loc) · 962 Bytes
/
findPathInDb.ts
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
import { JsonDB } from './server.ts';
export const findPathInDb = (
db: JsonDB,
routePaths: string[],
rewriteRules?: Record<string, string[]>
) => {
const matchedRewriteKey =
rewriteRules &&
Object.keys(rewriteRules).find(
(rewriteKey) => rewriteKey === routePaths.join('/')
);
const appliedRoutePaths = matchedRewriteKey
? rewriteRules![matchedRewriteKey]
: routePaths;
return appliedRoutePaths.reduce((subDB, routePart) => {
if (routePart == null || routePart === '') {
return subDB;
}
const id = Number(routePart);
if (Array.isArray(subDB) && !Number.isNaN(id)) {
return (subDB as { id: number }[]).find(
(item) => item.id === id
) as Record<string, unknown>;
}
if (routePart && routePart in subDB) {
return subDB[routePart] as Record<string, unknown>;
}
console.error(`${routePart} not found in ${JSON.stringify(subDB)}!`);
return subDB;
}, db);
};