@opengis/fastify-table 2.0.13 → 2.0.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/config.js
CHANGED
|
@@ -1,23 +1,26 @@
|
|
|
1
1
|
/* eslint-disable no-console */
|
|
2
2
|
import dotenv from "dotenv";
|
|
3
|
-
dotenv.config(); // load .env for node
|
|
3
|
+
dotenv.config(); // ! load .env (workaround for node)
|
|
4
4
|
import { existsSync, readFileSync } from "node:fs";
|
|
5
5
|
import unflattenObject from "./server/plugins/util/funcs/unflattenObject.js";
|
|
6
6
|
const fileName = ["config.json", "/data/local/config.json"].find((el) => existsSync(el) ? el : null);
|
|
7
7
|
const config = fileName ? JSON.parse(readFileSync(fileName, "utf-8")) : {};
|
|
8
8
|
const { skipKeys = ["windir"] } = config;
|
|
9
|
-
// npm run dev === cross-env NODE_ENV=development
|
|
10
|
-
// alt: node --env=development
|
|
11
9
|
Object.assign(config, {
|
|
12
10
|
storageList: {},
|
|
13
11
|
allTemplates: config?.allTemplates || {},
|
|
14
12
|
env: process.env?.NODE_ENV,
|
|
15
13
|
});
|
|
14
|
+
if (existsSync(`.env.local`)) {
|
|
15
|
+
dotenv.config({ path: `.env.local` }); // ! load .env.local
|
|
16
|
+
}
|
|
16
17
|
if (process.env?.NODE_ENV && existsSync(`.env.${process.env.NODE_ENV}`)) {
|
|
17
|
-
dotenv.config({ path: `.env.${process.env.NODE_ENV}` }); // load .env.{{production}} etc.
|
|
18
|
+
dotenv.config({ path: `.env.${process.env.NODE_ENV}` }); // ! load .env.{{production}} etc.
|
|
19
|
+
}
|
|
20
|
+
if (process.env?.NODE_ENV && existsSync(`.env.${process.env.NODE_ENV}.local`)) {
|
|
21
|
+
dotenv.config({ path: `.env.${process.env.NODE_ENV}.local` }); // ! load .env.{{production}}.local etc.
|
|
18
22
|
}
|
|
19
23
|
function loadEnvConfig() {
|
|
20
|
-
// node --env-file-if-exists=.env.dev --env-file-if-exists=.env server
|
|
21
24
|
if (config.trace) {
|
|
22
25
|
console.log(Object.keys(process.env));
|
|
23
26
|
}
|
package/dist/index.js
CHANGED
|
@@ -1,9 +1,18 @@
|
|
|
1
1
|
import fp from "fastify-plugin";
|
|
2
2
|
import path from "node:path";
|
|
3
|
-
import { existsSync, readdirSync, readFileSync } from "node:fs";
|
|
3
|
+
import { existsSync, readdirSync, readFileSync, mkdirSync, writeFileSync, } from "node:fs";
|
|
4
|
+
import { createHash } from "node:crypto";
|
|
4
5
|
import { fileURLToPath } from "node:url";
|
|
5
6
|
import proxy from "@fastify/http-proxy";
|
|
6
7
|
import config from "./config.js";
|
|
8
|
+
import getTemplatePath from "./server/plugins/table/funcs/getTemplatePath.js";
|
|
9
|
+
import addHook from "./server/plugins/hook/addHook.js";
|
|
10
|
+
import getToken from "./server/plugins/crud/funcs/getToken.js";
|
|
11
|
+
import getTemplate from "./server/plugins/table/funcs/getTemplate.js";
|
|
12
|
+
import getRedis from "./server/plugins/redis/funcs/getRedis.js";
|
|
13
|
+
import logger from "./server/plugins/logger/getLogger.js";
|
|
14
|
+
import getMenu from "./server/routes/menu/controllers/getMenu.js";
|
|
15
|
+
import getSelectVal from "./server/plugins/table/funcs/metaFormat/getSelectVal.js";
|
|
7
16
|
const { maxFileSize = 512 } = config;
|
|
8
17
|
const { name: execName } = path.parse(process.argv0);
|
|
9
18
|
// helpers
|
|
@@ -37,17 +46,221 @@ import widgetRoutes from "./server/routes/widget/index.js";
|
|
|
37
46
|
import authRoutes from "./server/routes/auth/index.js";
|
|
38
47
|
import fileRoutes from "./server/routes/file/index.js";
|
|
39
48
|
import grpcRoutes from "./server/routes/grpc/index.js";
|
|
49
|
+
const { client } = pgClients;
|
|
50
|
+
const rclient = getRedis();
|
|
40
51
|
// core templates && cls
|
|
41
52
|
const filename = fileURLToPath(import.meta.url);
|
|
42
53
|
const cwd = path.dirname(filename);
|
|
54
|
+
addHook("preForm", async ({ form, user }) => {
|
|
55
|
+
if (!user?.uid)
|
|
56
|
+
return null;
|
|
57
|
+
const opt = await getToken({
|
|
58
|
+
mode: "w",
|
|
59
|
+
token: form,
|
|
60
|
+
uid: user.uid,
|
|
61
|
+
json: 1,
|
|
62
|
+
});
|
|
63
|
+
return opt;
|
|
64
|
+
});
|
|
65
|
+
addHook("afterTable", async ({ table, res = {}, payload: rows = [], user = {}, }) => {
|
|
66
|
+
const loadTable = await getTemplate("table", table);
|
|
67
|
+
const { uid } = config?.auth?.disable || process.env.NODE_ENV !== "admin"
|
|
68
|
+
? { uid: "1" }
|
|
69
|
+
: user;
|
|
70
|
+
if (!uid ||
|
|
71
|
+
!table ||
|
|
72
|
+
!client?.pk?.[table] ||
|
|
73
|
+
!rows.length ||
|
|
74
|
+
!loadTable?.table ||
|
|
75
|
+
!client?.pk?.["crm.extra_data"] ||
|
|
76
|
+
!client?.pk?.["admin.custom_column"])
|
|
77
|
+
return;
|
|
78
|
+
// admin.custom_column - user column data
|
|
79
|
+
const { rows: properties = [] } = await client.query(`select column_id, name, title, format, data from admin.custom_column
|
|
80
|
+
where _table and entity=$1 and uid=$2`, [table, uid]);
|
|
81
|
+
const extraColumnList = properties.map((row) => ({
|
|
82
|
+
id: row.column_id,
|
|
83
|
+
name: row.name,
|
|
84
|
+
title: row.title,
|
|
85
|
+
format: row.format,
|
|
86
|
+
data: row.data,
|
|
87
|
+
}));
|
|
88
|
+
if (!extraColumnList?.length)
|
|
89
|
+
return;
|
|
90
|
+
if (Array.isArray(res?.columns) && res?.columns?.length) {
|
|
91
|
+
extraColumnList.forEach((col) => res.columns.push(col));
|
|
92
|
+
}
|
|
93
|
+
const { rows: extraData = [] } = await client.query(`select object_id, json_object_agg( property_id, coalesce(value_date::text,value_text) ) as extra from crm.extra_data
|
|
94
|
+
where property_entity=$1 and property_id=any($2) and object_id=any($3) group by object_id`, [
|
|
95
|
+
table,
|
|
96
|
+
extraColumnList?.map((el) => el.id),
|
|
97
|
+
rows.map((el) => el.id),
|
|
98
|
+
]);
|
|
99
|
+
if (!extraData?.length) {
|
|
100
|
+
// Object.assign(rows?.[0] || {}, { ...extraColumnList.reduce((acc, curr) => Object.assign(acc, { [curr.name]: null }), {}) });
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
rows
|
|
104
|
+
.filter((row) => extraData.map((el) => el?.object_id).includes(row.id))
|
|
105
|
+
.forEach((row) => {
|
|
106
|
+
const { extra = {} } = extraData.find((el) => el.object_id === row.id);
|
|
107
|
+
Object.assign(row, {
|
|
108
|
+
...Object.fromEntries(Object.entries(extra).map((el) => [
|
|
109
|
+
extraColumnList.find((col) => col.id === el[0]).name,
|
|
110
|
+
el[1],
|
|
111
|
+
])),
|
|
112
|
+
});
|
|
113
|
+
});
|
|
114
|
+
// admin.custom_column - metaFormat
|
|
115
|
+
await Promise.all(extraColumnList
|
|
116
|
+
.filter((el) => el?.data)
|
|
117
|
+
.map(async (attr) => {
|
|
118
|
+
const values = [
|
|
119
|
+
...new Set(rows?.map((el) => el[attr.name]).flat()),
|
|
120
|
+
].filter((el) => el);
|
|
121
|
+
if (!values.length)
|
|
122
|
+
return;
|
|
123
|
+
const cls = await getSelectVal({ name: attr.data, values });
|
|
124
|
+
if (!cls)
|
|
125
|
+
return;
|
|
126
|
+
rows.forEach((el) => {
|
|
127
|
+
const val = el[attr.name]?.map?.((c) => cls[c] || c) ||
|
|
128
|
+
cls[el[attr.name]] ||
|
|
129
|
+
el[attr.name];
|
|
130
|
+
if (!val)
|
|
131
|
+
return;
|
|
132
|
+
Object.assign(el, {
|
|
133
|
+
[val?.color ? `${attr.name}_data` : `${attr.name}_text`]: val.color ? val : val.text || val,
|
|
134
|
+
});
|
|
135
|
+
});
|
|
136
|
+
}));
|
|
137
|
+
});
|
|
138
|
+
// extract table from form token for user columns - p.2 - read (refactor to global token)
|
|
139
|
+
addHook("preTemplate", async ({ name, type, user = {}, }) => {
|
|
140
|
+
if (!name || !type)
|
|
141
|
+
return;
|
|
142
|
+
const { uid } = config?.auth?.disable || process.env.NODE_ENV !== "admin"
|
|
143
|
+
? { uid: "1" }
|
|
144
|
+
: user;
|
|
145
|
+
const tokenData = (await getToken({
|
|
146
|
+
uid,
|
|
147
|
+
token: name,
|
|
148
|
+
mode: "w",
|
|
149
|
+
json: 1,
|
|
150
|
+
})) || // edit?
|
|
151
|
+
(await getToken({
|
|
152
|
+
uid,
|
|
153
|
+
token: name,
|
|
154
|
+
mode: "a",
|
|
155
|
+
json: 1,
|
|
156
|
+
})) ||
|
|
157
|
+
{}; // add?
|
|
158
|
+
return { name: tokenData?.[type] };
|
|
159
|
+
});
|
|
160
|
+
addHook("afterTemplate", async ({ name, type, payload: data = {}, user = {}, }) => {
|
|
161
|
+
const { uid } = config?.auth?.disable || process.env.NODE_ENV !== "admin"
|
|
162
|
+
? { uid: "1" }
|
|
163
|
+
: user;
|
|
164
|
+
// extract table from form token for user columns - p.1 - assign (refactor to global token)
|
|
165
|
+
if (!uid ||
|
|
166
|
+
!data ||
|
|
167
|
+
type !== "form" ||
|
|
168
|
+
!name ||
|
|
169
|
+
!client?.pk?.["admin.custom_column"])
|
|
170
|
+
return null;
|
|
171
|
+
const { form, id, table } = (await getToken({
|
|
172
|
+
uid,
|
|
173
|
+
token: name,
|
|
174
|
+
mode: "w",
|
|
175
|
+
json: 1,
|
|
176
|
+
})) || // edit?
|
|
177
|
+
(await getToken({
|
|
178
|
+
uid,
|
|
179
|
+
token: name,
|
|
180
|
+
mode: "a",
|
|
181
|
+
json: 1,
|
|
182
|
+
})) ||
|
|
183
|
+
{}; // add?
|
|
184
|
+
const { rows: properties = [] } = await client.query(`select name, title, format, data from admin.custom_column
|
|
185
|
+
where entity=$1 and uid=$2`, [table || name, uid]);
|
|
186
|
+
await Promise.all(properties.map(async (el) => {
|
|
187
|
+
const clsData = el.data
|
|
188
|
+
? await getTemplate(["cls", "select"], el.data)
|
|
189
|
+
: undefined;
|
|
190
|
+
const type = clsData
|
|
191
|
+
? "Select"
|
|
192
|
+
: { date: "DatePicker" }[el.format || ""] || "Text";
|
|
193
|
+
Object.assign(data?.schema || data || {}, {
|
|
194
|
+
[el.name]: {
|
|
195
|
+
type,
|
|
196
|
+
ua: el.title,
|
|
197
|
+
data: el.data,
|
|
198
|
+
options: type === "Select" && Array.isArray(clsData) && clsData?.length
|
|
199
|
+
? clsData
|
|
200
|
+
: undefined,
|
|
201
|
+
extra: 1,
|
|
202
|
+
},
|
|
203
|
+
});
|
|
204
|
+
}));
|
|
205
|
+
});
|
|
206
|
+
addHook("afterUpdate", async ({ table, body = {}, payload: res = {}, user = {}, }) => {
|
|
207
|
+
const { uid } = config?.auth?.disable || process.env.NODE_ENV !== "admin"
|
|
208
|
+
? { uid: "1" }
|
|
209
|
+
: user;
|
|
210
|
+
if (!uid ||
|
|
211
|
+
!table ||
|
|
212
|
+
!Object.keys(body)?.length ||
|
|
213
|
+
!client?.pk?.["crm.extra_data"] ||
|
|
214
|
+
!client?.pk?.["admin.custom_column"])
|
|
215
|
+
return null;
|
|
216
|
+
const loadTable = await getTemplate("table", table);
|
|
217
|
+
if (!client?.pk?.[loadTable?.table || table])
|
|
218
|
+
return null;
|
|
219
|
+
const pk = client?.pk?.[loadTable?.table || table];
|
|
220
|
+
const id = res[pk];
|
|
221
|
+
const { rows: properties = [] } = await client.query(`select column_id, name, title, format, data from admin.custom_column
|
|
222
|
+
where entity=$1 and uid=$2`, [table, uid]);
|
|
223
|
+
if (!id || !properties?.length || !client.pk?.["crm.extra_data"])
|
|
224
|
+
return null;
|
|
225
|
+
const q = `delete from crm.extra_data where property_entity='${table}' and object_id='${id}';${properties
|
|
226
|
+
.filter((el) => Object.keys(body).includes(el.name))
|
|
227
|
+
.map((el) => `insert into crm.extra_data(property_id,property_key,property_entity,object_id,${el.format?.toLowerCase() === "date" ? "value_date" : "value_text"})
|
|
228
|
+
select '${el.column_id}', '${el.name}', '${table}', '${id}', ${el.format?.toLowerCase() === "date"
|
|
229
|
+
? `'${body[el.name]}'::timestamp without time zone`
|
|
230
|
+
: `'${body[el.name]}'::text`}`)
|
|
231
|
+
.join(";\n") || ""}`;
|
|
232
|
+
return client.query(q);
|
|
233
|
+
});
|
|
234
|
+
addHook("afterInsert", async ({ table, body, payload: res = {}, user = {}, }) => {
|
|
235
|
+
const { uid } = config?.auth?.disable || process.env.NODE_ENV !== "admin"
|
|
236
|
+
? { uid: "1" }
|
|
237
|
+
: user;
|
|
238
|
+
if (!uid ||
|
|
239
|
+
!table ||
|
|
240
|
+
!Object.keys(body)?.length ||
|
|
241
|
+
!client?.pk?.["crm.extra_data"] ||
|
|
242
|
+
!client?.pk?.["admin.custom_column"])
|
|
243
|
+
return null;
|
|
244
|
+
const loadTable = await getTemplate("table", table);
|
|
245
|
+
if (!client?.pk?.[loadTable?.table || table])
|
|
246
|
+
return null;
|
|
247
|
+
const pk = client?.pk?.[loadTable?.table || table];
|
|
248
|
+
const id = res.rows?.[0]?.[pk];
|
|
249
|
+
const { rows: properties = [] } = await client.query(`select column_id, name, title, format, data from admin.custom_column
|
|
250
|
+
where entity=$1 and uid=$2`, [table, uid]);
|
|
251
|
+
if (!id || !properties?.length)
|
|
252
|
+
return null;
|
|
253
|
+
const q = properties
|
|
254
|
+
.filter((el) => Object.keys(body).includes(el.name))
|
|
255
|
+
.map((el) => `insert into crm.extra_data(property_id,property_key,property_entity,object_id,${el.format?.toLowerCase() === "date" ? "value_date" : "value_text"})
|
|
256
|
+
select '${el.column_id}', '${el.name}', '${table}', '${id}', ${el.format?.toLowerCase() === "date"
|
|
257
|
+
? `'${body[el.name]}'::timestamp without time zone`
|
|
258
|
+
: `'${body[el.name]}'::text`}`)
|
|
259
|
+
.join(";\n");
|
|
260
|
+
return client.query(q);
|
|
261
|
+
});
|
|
43
262
|
function plugin(fastify) {
|
|
44
263
|
const opt = { prefix: "/api" };
|
|
45
|
-
// fastify.register(import('@fastify/sensible'), {
|
|
46
|
-
// errorHandler: false,
|
|
47
|
-
// });
|
|
48
|
-
// fastify.register(import('@fastify/url-data'), {
|
|
49
|
-
// errorHandler: false,
|
|
50
|
-
// });
|
|
51
264
|
if (config.disableCors) {
|
|
52
265
|
fastify.addHook("onSend", async (request, reply) => {
|
|
53
266
|
reply.header("Access-Control-Allow-Origin", "*");
|
|
@@ -98,6 +311,12 @@ function plugin(fastify) {
|
|
|
98
311
|
keyGenerator: (req) => `${req.ip}-${req.raw.url.split("?")[0]}`,
|
|
99
312
|
});
|
|
100
313
|
}
|
|
314
|
+
// add multipart parser before any route registration
|
|
315
|
+
fastify.register(import("@fastify/multipart"), {
|
|
316
|
+
limits: {
|
|
317
|
+
fileSize: maxFileSize * 1024 * 1024,
|
|
318
|
+
},
|
|
319
|
+
});
|
|
101
320
|
if (config.dblist) {
|
|
102
321
|
fastify.register(dblistRoutes, opt);
|
|
103
322
|
}
|
|
@@ -114,11 +333,6 @@ function plugin(fastify) {
|
|
|
114
333
|
fastify.register(templatesRoutes, opt);
|
|
115
334
|
fastify.register(authRoutes); // from fastify-auth
|
|
116
335
|
// from fastify-file
|
|
117
|
-
fastify.register(import("@fastify/multipart"), {
|
|
118
|
-
limits: {
|
|
119
|
-
fileSize: maxFileSize * 1024 * 1024,
|
|
120
|
-
},
|
|
121
|
-
}); // content parser, await before adding upload routes
|
|
122
336
|
fastify.register(fileRoutes);
|
|
123
337
|
fastify.register(grpcRoutes, opt);
|
|
124
338
|
config.proxy?.forEach?.((el) => {
|
|
@@ -165,5 +379,172 @@ function plugin(fastify) {
|
|
|
165
379
|
});
|
|
166
380
|
}
|
|
167
381
|
});
|
|
382
|
+
// from opengis/admin
|
|
383
|
+
const user1 = config?.auth?.disable || process.env.NODE_ENV !== "admin"
|
|
384
|
+
? { uid: "1" }
|
|
385
|
+
: null;
|
|
386
|
+
fastify.addHook("onListen", async () => {
|
|
387
|
+
const json = await getMenu({ user: { uid: "1" }, pg: client }, null);
|
|
388
|
+
// insert interface list to db (user access management)
|
|
389
|
+
if (client?.pk?.["admin.routes"] && json?.menus?.length) {
|
|
390
|
+
const menuList = json?.menus?.filter?.((el) => el?.table ||
|
|
391
|
+
el?.component ||
|
|
392
|
+
el?.menu?.length /*&& el?.ua || el?.en || el?.name*/) || [];
|
|
393
|
+
// skip dupes
|
|
394
|
+
//admin_route_menu_id_fkey
|
|
395
|
+
menuList.forEach((el) => Object.assign(el, { ua: el?.ua || el?.en || el?.name }));
|
|
396
|
+
const uniqueList = menuList.filter((el, idx, arr) => el?.ua &&
|
|
397
|
+
arr.map((item) => item?.ua).indexOf(el?.ua) ===
|
|
398
|
+
idx);
|
|
399
|
+
const q = `insert into admin.menu(name, ord) values${uniqueList
|
|
400
|
+
.map((el, i) => `('${el?.ua.replace(/'/g, "''")}', ${i}) `)
|
|
401
|
+
.join(",")}
|
|
402
|
+
on conflict (name) do update set ord=excluded.ord, enabled=true returning name, menu_id`;
|
|
403
|
+
const { rows = [] } = uniqueList.length ? await client.query(q) : {};
|
|
404
|
+
const menus = rows.reduce((acc, curr) => Object.assign(acc, {
|
|
405
|
+
[curr.menu_id]: uniqueList.find((item) => item?.ua === curr.name),
|
|
406
|
+
}), {});
|
|
407
|
+
const values = Object.entries(menus).reduce((acc, curr) => {
|
|
408
|
+
if (curr[1]?.table || curr[1]?.component) {
|
|
409
|
+
acc.push({ ...curr[1], menuId: curr[0] });
|
|
410
|
+
}
|
|
411
|
+
curr[1]?.menu?.forEach?.((el) => acc.push({ ...el, menuId: curr[0] }));
|
|
412
|
+
return acc;
|
|
413
|
+
}, []);
|
|
414
|
+
await Promise.all(values
|
|
415
|
+
.filter((el) => el?.table)
|
|
416
|
+
.map(async (el) => {
|
|
417
|
+
const loadTable = await getTemplate("table", el.table);
|
|
418
|
+
Object.assign(el, {
|
|
419
|
+
table1: loadTable?.table || el.table,
|
|
420
|
+
actions: loadTable?.actions,
|
|
421
|
+
access: loadTable?.access,
|
|
422
|
+
});
|
|
423
|
+
}));
|
|
424
|
+
// console.log(values)
|
|
425
|
+
const q1 = `insert into admin.routes(route_id, alias, title, menu_id, table_name, actions, access, query)
|
|
426
|
+
values ${values
|
|
427
|
+
.filter((el) => el?.path)
|
|
428
|
+
.map((el) => `('${el.path}', ${el.table ? `'${el.table}'` : null},
|
|
429
|
+
${el.title || el.ua
|
|
430
|
+
? `'${(el.title || el.ua).replace(/'/g, "''")}'`
|
|
431
|
+
: null},
|
|
432
|
+
${el.menuId ? `'${el.menuId}'` : null}, ${el.table1 ? `'${el.table1}'` : null},
|
|
433
|
+
${el.actions?.length ? `'{ ${el.actions} }'::text[]` : null}, ${el.access ? `'${el.access}'` : null},
|
|
434
|
+
${el.query ? `'${el.query.replace(/'/g, "''")}'` : "'1=1'"})`)
|
|
435
|
+
.join(",")}
|
|
436
|
+
on conflict (route_id) do update set menu_id=excluded.menu_id, alias=excluded.alias, title=excluded.title, enabled=true, query=excluded.query,
|
|
437
|
+
table_name=excluded.table_name, actions=excluded.actions, access=excluded.access returning route_id, table_name`;
|
|
438
|
+
try {
|
|
439
|
+
console.log("admin/hook routes sql start");
|
|
440
|
+
const { rowCount: menuCount } = await client.query(`delete from admin.menu
|
|
441
|
+
where not array[menu_id] <@ $1::text[] and menu_id not in (select menu_id from admin.routes)`, [rows.map((el) => el.menu_id)]);
|
|
442
|
+
console.log("delete deprecated menus ok", menuCount);
|
|
443
|
+
const { rowCount: interfaceCount } = await client.query(`delete from admin.routes
|
|
444
|
+
where not array[route_id] <@ $1::text[] and route_id not in (select route_id from admin.role_access)`, [values.filter((el) => el?.path)]);
|
|
445
|
+
console.log("delete deprecated interfaces ok", interfaceCount);
|
|
446
|
+
const { rowCount } = values?.length ? await client.query(q1) : {};
|
|
447
|
+
console.log("insert interfaces ok", rowCount);
|
|
448
|
+
}
|
|
449
|
+
catch (err) {
|
|
450
|
+
console.log("admin/hook routes sql error", values, q1, err);
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
});
|
|
454
|
+
fastify.addHook("onListen", async () => {
|
|
455
|
+
const clsQuery = [];
|
|
456
|
+
if (!client?.pk?.["admin.cls"])
|
|
457
|
+
return;
|
|
458
|
+
const selectList = getTemplatePath("select");
|
|
459
|
+
const clsList = getTemplatePath("cls")?.filter((el) => !(selectList?.map((el) => el?.[0]) || []).includes(el[0]));
|
|
460
|
+
const cls = (selectList || []).concat(clsList || [])?.map((el) => ({
|
|
461
|
+
name: el[0],
|
|
462
|
+
module: path.basename(path.dirname(path.dirname(el[1]))),
|
|
463
|
+
type: { json: "cls", sql: "select" }[el[2]],
|
|
464
|
+
}));
|
|
465
|
+
if (!cls?.length)
|
|
466
|
+
return;
|
|
467
|
+
try {
|
|
468
|
+
const hashes = await rclient
|
|
469
|
+
.hgetall("cls-insert-hashes")
|
|
470
|
+
.then((obj) => Object.keys(obj));
|
|
471
|
+
const dbdata = await client
|
|
472
|
+
.query(`select json_object_agg(name, hash) from admin.cls where parent is null`)
|
|
473
|
+
.then((el) => el.rows?.[0]?.json_object_agg || {});
|
|
474
|
+
const names = Object.keys(dbdata);
|
|
475
|
+
console.log("admin/hook cls promise start");
|
|
476
|
+
const qHashes = await Promise.all(cls
|
|
477
|
+
.filter((el, idx, arr) => arr.map((item) => item.name).indexOf(el.name) === idx)
|
|
478
|
+
.map(async (el) => {
|
|
479
|
+
const { name, module, type } = el;
|
|
480
|
+
const loadTemplate = await getTemplate(type, name);
|
|
481
|
+
el.hash = createHash("md5")
|
|
482
|
+
.update(type === "cls"
|
|
483
|
+
? JSON.stringify(loadTemplate)
|
|
484
|
+
: loadTemplate?.sql || loadTemplate)
|
|
485
|
+
.digest("hex");
|
|
486
|
+
el.dbhash = dbdata[name];
|
|
487
|
+
// check for changes by redis hash / dropped from db / changed at git project
|
|
488
|
+
el.update =
|
|
489
|
+
!hashes.includes(el.hash) ||
|
|
490
|
+
!names.includes(name) ||
|
|
491
|
+
el.hash !== el.dbhash;
|
|
492
|
+
if (type === "select" &&
|
|
493
|
+
(loadTemplate?.sql || loadTemplate) &&
|
|
494
|
+
el.update) {
|
|
495
|
+
clsQuery.push(`insert into admin.cls(name,type,data,module,hash) values('${name}','sql','${(loadTemplate?.sql || loadTemplate)?.replace(/'/g, "''")}', '${module?.replace(/'/g, "''")}','${el.hash}')`);
|
|
496
|
+
if (config.trace)
|
|
497
|
+
console.log(name, type, "insert fresh select");
|
|
498
|
+
return el.hash;
|
|
499
|
+
}
|
|
500
|
+
else if (type === "cls" && loadTemplate?.length && el.update) {
|
|
501
|
+
clsQuery.push(`insert into admin.cls(name,type, module,hash) values('${name}','json', '${module?.replace(/'/g, "''")}','${el.hash}');
|
|
502
|
+
insert into admin.cls(code,name,parent,icon,data)
|
|
503
|
+
select value->>'id',value->>'text','${name}',value->>'icon',value->>'data'
|
|
504
|
+
from json_array_elements('${JSON.stringify(loadTemplate).replace(/'/g, "''")}'::json)`);
|
|
505
|
+
if (config.trace)
|
|
506
|
+
console.log(name, type, "insert fresh cls");
|
|
507
|
+
return el.hash;
|
|
508
|
+
}
|
|
509
|
+
else if (hashes.includes(el.hash)) {
|
|
510
|
+
if (config.trace)
|
|
511
|
+
console.log(name, type, names.includes(name)
|
|
512
|
+
? "skip equal hash"
|
|
513
|
+
: "insert missing cls");
|
|
514
|
+
return el.hash;
|
|
515
|
+
}
|
|
516
|
+
else {
|
|
517
|
+
if (config.trace)
|
|
518
|
+
console.log(name, type, "empty");
|
|
519
|
+
return el.hash;
|
|
520
|
+
}
|
|
521
|
+
}));
|
|
522
|
+
// debug
|
|
523
|
+
const logDir = path.join(cwd, "log/migration");
|
|
524
|
+
mkdirSync(logDir, { recursive: true });
|
|
525
|
+
writeFileSync(path.join(logDir, `${path.basename(cwd)}-${client.options?.database}-cls.sql`), clsQuery.filter(Boolean).join(";"));
|
|
526
|
+
writeFileSync(path.join(logDir, `${path.basename(cwd)}-${client.options?.database}-cls.json`), JSON.stringify(cls));
|
|
527
|
+
const { rowCount = 0 } = await client.query("delete from admin.cls where $1::text[] && array[name,parent]", [
|
|
528
|
+
cls
|
|
529
|
+
.filter((el) => el.update)
|
|
530
|
+
.map((el) => el.name),
|
|
531
|
+
]);
|
|
532
|
+
console.log("fastify-table/hook old cls deleted", rowCount);
|
|
533
|
+
if (clsQuery.filter((el) => el).length) {
|
|
534
|
+
console.log("fastify-table cls sql start", clsQuery?.length);
|
|
535
|
+
await client.query(clsQuery.filter((el) => el).join(";"));
|
|
536
|
+
await Promise.all(qHashes
|
|
537
|
+
.filter(Boolean)
|
|
538
|
+
.map(async (el) => rclient.hset("cls-insert-hashes", el, 1)));
|
|
539
|
+
logger.file("migration/hash", { list: qHashes.filter(Boolean) });
|
|
540
|
+
console.log("fastify-table/hook cls sql finish", clsQuery?.length);
|
|
541
|
+
}
|
|
542
|
+
console.log("fastify-table/hook cls promise finish", rowCount);
|
|
543
|
+
}
|
|
544
|
+
catch (err) {
|
|
545
|
+
console.error("fastify-table/hook cls sql error", err.toString());
|
|
546
|
+
console.trace(err);
|
|
547
|
+
}
|
|
548
|
+
});
|
|
168
549
|
}
|
|
169
550
|
export default fp(plugin);
|
|
@@ -31,7 +31,7 @@ async function readMenu() {
|
|
|
31
31
|
}
|
|
32
32
|
export default async function adminMenu({ user = {}, session, pg = pgClients.client, }, reply) {
|
|
33
33
|
const time = Date.now();
|
|
34
|
-
if (!user.uid && !config.auth?.disable) {
|
|
34
|
+
if (!user.uid && !config.auth?.disable && reply) {
|
|
35
35
|
return reply.status(403).send("access restricted");
|
|
36
36
|
}
|
|
37
37
|
const menus = isProduction && menuCache.length ? menuCache : await readMenu();
|
|
@@ -28,10 +28,10 @@ export default async function getForm({ pg = pgClients.client, params, user = {}
|
|
|
28
28
|
(await getTemplate("table", table).then((el) => el?.form)) ||
|
|
29
29
|
{};
|
|
30
30
|
if (!form) {
|
|
31
|
-
return reply.status(404).send("form not found");
|
|
31
|
+
// return reply.status(404).send("form not found");
|
|
32
32
|
}
|
|
33
33
|
const { actions = [] } = (await getAccess({ table, form, user }, pg)) || {};
|
|
34
|
-
const loadTemplate =
|
|
34
|
+
const loadTemplate = await getTemplate("form", form || params.name);
|
|
35
35
|
if (!loadTemplate) {
|
|
36
36
|
return reply.status(404).send("form template not found");
|
|
37
37
|
}
|
|
@@ -56,7 +56,8 @@ export default async function getForm({ pg = pgClients.client, params, user = {}
|
|
|
56
56
|
if (!isAllowedByTemplate &&
|
|
57
57
|
!config.local &&
|
|
58
58
|
process.env.NODE_ENV !== "test" &&
|
|
59
|
-
!(tokenData?.form || hookData?.form)
|
|
59
|
+
!(tokenData?.form || hookData?.form) &&
|
|
60
|
+
form) {
|
|
60
61
|
return reply.status(403).send("access restricted: actions");
|
|
61
62
|
}
|
|
62
63
|
const token = setToken({
|