/
interceptorHelper.js
82 lines (71 loc) · 2.04 KB
/
interceptorHelper.js
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
// @flow
import { keys, includes } from "lodash";
import pathMatch from "path-match";
import parseUrl from "parse-url";
import queryString from "query-string";
import { Request } from "../Request";
import { Response } from "../Response";
import { Database } from "../Database";
export type RouteHandler = (
request: Request,
db: Database<any>
) => Response | any;
export type InterceptorConfig = {
+host: string,
+routes: { [method: string]: { [path: string]: RouteHandler } },
+db: any,
+requestDelay: number
};
export type UrlDetails = {
+handlers: any,
+pathname: string,
+fullpath: string
};
// @TODO (oskar): This NEEDS refactor.
const getRoute = (
{ host }: InterceptorConfig,
{ handlers, pathname, fullpath }: UrlDetails
) => {
const matchesPathname = path => pathMatch()(path)(pathname);
const route = keys(handlers).find(matchesPathname);
const hasHost = includes(fullpath, host);
return route && hasHost ? route : null;
};
const extractUrl = (
{ routes }: InterceptorConfig,
url: string,
method: string
) => ({
handlers: routes[method],
pathname: parseUrl(url).pathname,
fullpath: parseUrl(url).href
});
export interface Interceptor {
getDB(): any;
getDelay(): number;
getHandler(url: string, method: string): RouteHandler | null;
getParams(url: string, method: string): any;
getQuery(url: string): any;
}
export const interceptorHelper = (config: InterceptorConfig): Interceptor => ({
getDB() {
return config.db;
},
getDelay() {
return config.requestDelay;
},
getHandler(url, method) {
const extractedUrl = extractUrl(config, url, method);
const route = getRoute(config, extractedUrl);
return route ? extractedUrl.handlers[route] : null;
},
getParams(url, method) {
const extractedUrl = extractUrl(config, url, method);
const matchesPathname = path => pathMatch()(path)(extractedUrl.pathname);
const route = getRoute(config, extractedUrl);
return route ? matchesPathname(route) : null;
},
getQuery(url) {
return queryString.parse(parseUrl(url).search);
}
});