-
-
Notifications
You must be signed in to change notification settings - Fork 530
Expand file tree
/
Copy pathconfig.ts
More file actions
70 lines (60 loc) · 2.18 KB
/
Copy pathconfig.ts
File metadata and controls
70 lines (60 loc) · 2.18 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
import { NextApiRequest, NextApiResponse } from "next";
import {
Utils, CoreConfig,
//types:
ZipConfig,
Config
} from "@react-awesome-query-builder/core";
import { withSessionRoute, getSessionData, saveSessionData } from "../../lib/withSession";
import serverConfig from "../../lib/config";
// API to get/save `zipConfig` to session
// Initial config is created in `lib/config` and compressed with `Utils.ConfigUtils.compressConfig()`
export type GetConfigQuery = {
initial?: string;
};
export interface PostConfigBody {
zipConfig: ZipConfig;
}
// eslint-disable-next-line @typescript-eslint/no-empty-object-type
export interface PostConfigResult {
}
export interface GetConfigResult {
zipConfig: ZipConfig;
}
export async function decompressSavedConfig(req: NextApiRequest): Promise<Config> {
const zipConfig = await getSavedZipConfig(req);
const config = Utils.ConfigUtils.decompressConfig(zipConfig, serverConfig as Config);
return config;
}
export async function getSavedZipConfig(req: NextApiRequest): Promise<ZipConfig> {
return (await getSessionData(req))?.zipConfig || getInitialZipConfig();
}
export function getInitialZipConfig() {
return Utils.ConfigUtils.compressConfig(serverConfig as Config, CoreConfig);
}
async function saveZipConfig(req: NextApiRequest, zipConfig: ZipConfig) {
await saveSessionData(req, { zipConfig });
}
async function post(req: NextApiRequest, res: NextApiResponse<PostConfigResult>) {
const { zipConfig } = JSON.parse(req.body as string) as PostConfigBody;
await saveZipConfig(req, zipConfig);
const result: PostConfigResult = {};
return res.status(200).json(result);
}
async function get(req: NextApiRequest, res: NextApiResponse<GetConfigResult>) {
const zipConfig = (req.query as GetConfigQuery).initial ? getInitialZipConfig() : await getSavedZipConfig(req);
const result: GetConfigResult = {
zipConfig
};
return res.status(200).json(result);
}
async function route(req: NextApiRequest, res: NextApiResponse) {
if (req.method === "POST") {
return await post(req, res);
} else if (req.method === "GET") {
return await get(req, res);
} else {
return res.status(400).end();
}
}
export default withSessionRoute(route);