@opengis/fastify-table 1.2.19 → 1.2.21

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.
@@ -1,45 +1,45 @@
1
- import { handlebars } from '@opengis/fastify-hb/utils.js';
2
-
3
- import getTemplate from '../getTemplate.js';
4
- import getSelectVal from './getSelectVal.js';
5
-
6
- export default async function metaFormat({
7
- rows, table, cls, sufix = true,
8
- }) {
9
- const loadTable = table ? await getTemplate('table', table) : {};
10
- const selectCols = Object.keys(cls || {}).map(key => ({ name: key, data: cls[key] })).concat(loadTable?.columns?.filter((e) => e.data) || []);
11
- const metaCls = Object.keys(loadTable?.meta?.cls || {}).map((el) => ({ name: el, data: loadTable?.meta?.cls[el] }));
12
- const htmlCols = loadTable?.columns?.filter?.((e) => e.name && e.format === 'html' && e.html) || [];
13
- if (!selectCols?.length && !metaCls?.length && !htmlCols?.length) return rows;
14
-
15
- await Promise.all(htmlCols.map(async (attr) => {
16
- await Promise.all(rows.filter(row => row?.[attr.name])?.map(async (row) => {
17
- const html = await handlebars.compile(attr.html)(row);
18
- Object.assign(row, { [attr.name]: html?.replaceAll(/<[^>]*>/g, '')?.replace(/\n/g, '')?.trim() });
19
- }));
20
- }));
21
- // cls & select format
22
-
23
- await Promise.all(selectCols.concat(metaCls)?.map(async (attr) => {
24
- const values = [...new Set(rows?.map((el) => el[attr.name]).flat())].filter((el) => (typeof el === 'boolean' ? true : el));
25
- if (!values.length) return null;
26
-
27
- const clsValues = await getSelectVal({ name: attr.data, values });
28
- if (!clsValues) return null;
29
-
30
- rows.forEach(el => {
31
- const val = el[attr.name]?.map?.(c => c ? clsValues[c.toString()] || clsValues[c] || c : null) || clsValues[el[attr.name]?.toString()] || clsValues[el[attr.name]] || el[attr.name];
32
- if (!val) return;
33
- if (!sufix) {
34
- Object.assign(el, { [attr.name]: val.text || val });
35
- }
36
- else {
37
- Object.assign(el, { [val?.color ? `${attr.name}_data` : `${attr.name}_text`]: (val.color ? val : val.text || val) });
38
- }
39
- });
40
-
41
- return null;
42
- }));
43
-
44
- return rows;
45
- }
1
+ import { handlebars } from '@opengis/fastify-hb/utils.js';
2
+
3
+ import getTemplate from '../getTemplate.js';
4
+ import getSelectVal from './getSelectVal.js';
5
+
6
+ export default async function metaFormat({
7
+ rows, table, cls, sufix = true,
8
+ }) {
9
+ const loadTable = table ? await getTemplate('table', table) : {};
10
+ const selectCols = Object.keys(cls || {}).map(key => ({ name: key, data: cls[key] })).concat(loadTable?.columns?.filter((e) => e.data) || []);
11
+ const metaCls = Object.keys(loadTable?.meta?.cls || {}).map((el) => ({ name: el, data: loadTable?.meta?.cls[el] }));
12
+ const htmlCols = loadTable?.columns?.filter?.((e) => e.name && e.format === 'html' && e.html) || [];
13
+ if (!selectCols?.length && !metaCls?.length && !htmlCols?.length) return rows;
14
+
15
+ await Promise.all(htmlCols.map(async (attr) => {
16
+ await Promise.all(rows.filter(row => row?.[attr.name])?.map(async (row) => {
17
+ const html = await handlebars.compile(attr.html)(row);
18
+ Object.assign(row, { [attr.name]: html?.replaceAll(/<[^>]*>/g, '')?.replace(/\n/g, '')?.trim() });
19
+ }));
20
+ }));
21
+ // cls & select format
22
+
23
+ await Promise.all(selectCols.concat(metaCls)?.map(async (attr) => {
24
+ const values = [...new Set(rows?.map((el) => el[attr.name]).flat())].filter((el) => (typeof el === 'boolean' ? true : el));
25
+ if (!values.length) return null;
26
+
27
+ const clsValues = await getSelectVal({ name: attr.data, values });
28
+ if (!clsValues) return null;
29
+
30
+ rows.forEach(el => {
31
+ const val = el[attr.name]?.map?.(c => c ? clsValues[c.toString()] || clsValues[c] || c : null) || clsValues[el[attr.name]?.toString()] || clsValues[el[attr.name]] || el[attr.name];
32
+ if (!val) return;
33
+ if (!sufix) {
34
+ Object.assign(el, { [attr.name]: val.text || val });
35
+ }
36
+ else {
37
+ Object.assign(el, { [val?.color ? `${attr.name}_data` : `${attr.name}_text`]: (val.color ? val : val.text || val) });
38
+ }
39
+ });
40
+
41
+ return null;
42
+ }));
43
+
44
+ return rows;
45
+ }
@@ -1,39 +1,39 @@
1
- import {
2
- dataDelete, getTemplate, getAccess, applyHook, getToken, config,
3
- } from '../../../../utils.js';
4
-
5
- export default async function deleteCrud(req) {
6
- const { user, params = {}, headers = {} } = req || {};
7
-
8
- const hookData = await applyHook('preDelete', {
9
- table: params?.table, id: params?.id, user,
10
- });
11
-
12
- if (hookData?.message && hookData?.status) {
13
- return { message: hookData?.message, status: hookData?.status };
14
- }
15
-
16
- const { referer } = headers;
17
- const tokenData = await getToken({
18
- uid: user.uid, token: params.table, json: 1,
19
- });
20
-
21
- const { table: del, id } = hookData || tokenData || (config.auth?.disable ? req.params : {});
22
- const { actions = [] } = await getAccess({ table: del, id, user }) || {};
23
-
24
- if (!actions.includes('del') && !config?.local && !tokenData) {
25
- return { message: 'access restricted', status: 403 };
26
- }
27
- const loadTemplate = await getTemplate('table', del);
28
-
29
- const { table } = loadTemplate || hookData || tokenData || req.params || {};
30
-
31
- if (!table) return { status: 404, message: 'table is required' };
32
- if (!id) return { status: 404, message: 'id is required' };
33
-
34
- const data = await dataDelete({
35
- table, id, uid: user?.uid, tokenData, referer,
36
- });
37
-
38
- return { rowCount: data.rowCount, msg: !data.rowCount ? data : null };
39
- }
1
+ import {
2
+ dataDelete, getTemplate, getAccess, applyHook, getToken, config,
3
+ } from '../../../../utils.js';
4
+
5
+ export default async function deleteCrud(req) {
6
+ const { user, params = {}, headers = {} } = req || {};
7
+
8
+ const hookData = await applyHook('preDelete', {
9
+ table: params?.table, id: params?.id, user,
10
+ });
11
+
12
+ if (hookData?.message && hookData?.status) {
13
+ return { message: hookData?.message, status: hookData?.status };
14
+ }
15
+
16
+ const { referer } = headers;
17
+ const tokenData = await getToken({
18
+ uid: user.uid, token: params.table, json: 1,
19
+ });
20
+
21
+ const { table: del, id } = hookData || tokenData || (config.auth?.disable ? req.params : {});
22
+ const { actions = [] } = await getAccess({ table: del, id, user }) || {};
23
+
24
+ if (!actions.includes('del') && !config?.local && !tokenData) {
25
+ return { message: 'access restricted', status: 403 };
26
+ }
27
+ const loadTemplate = await getTemplate('table', del);
28
+
29
+ const { table } = loadTemplate || hookData || tokenData || req.params || {};
30
+
31
+ if (!table) return { status: 404, message: 'table is required' };
32
+ if (!id) return { status: 404, message: 'id is required' };
33
+
34
+ const data = await dataDelete({
35
+ table, id, uid: user?.uid, tokenData, referer,
36
+ });
37
+
38
+ return { rowCount: data.rowCount, msg: !data.rowCount ? data : null };
39
+ }
@@ -1,67 +1,67 @@
1
- import { getSelect, getFilterSQL, getTemplate, getSelectVal, pgClients } from '../../../../utils.js';
2
-
3
- export default async function filterAPI(req) {
4
- const time = Date.now();
5
-
6
- const {
7
- params, query = {}, pg = pgClients.client, user = {},
8
- } = req;
9
-
10
- const loadTable = await getTemplate('table', params.table);
11
- if (!loadTable) { return { status: 404, message: 'not found' }; }
12
-
13
- const sqlTable = loadTable.sql?.filter?.((el) => !el?.disabled && el?.sql?.replace).map((el, i) => ` left join lateral (${el.sql.replace('{{uid}}', user?.uid)}) ${el.name || `t${i}`} on 1=1 `)?.join('') || '';
14
- const { fields: columns } = await pg.query(`select * from ${loadTable.table} t ${sqlTable} limit 0`);
15
-
16
- const {
17
- filter, custom, state, search,
18
- } = query;
19
-
20
- const { optimizedSQL = `select * from ${loadTable.table}` } = loadTable?.sql || filter || custom || state || search ? await getFilterSQL({
21
- pg,
22
- table: params.table,
23
- filter,
24
- custom,
25
- state,
26
- search,
27
- }) : {};
28
-
29
- const filters = loadTable?.filter_list || loadTable?.filters || loadTable?.filterList || [];
30
- await Promise.all(filters.filter((el) => el.data && (el.id || el.name)).map(async (el) => {
31
- const name = el.id || el.name;
32
- const cls = await getSelect(el.data, pg);
33
-
34
- if (!cls || !loadTable.table) return;
35
- const { dataTypeID } = columns.find((item) => item.name === name) || {};
36
-
37
- const countArr = pg.pgType[dataTypeID]?.includes('[]')
38
- ? await pg.queryCache(`select unnest(${name})::text as id,count(*) from (${optimizedSQL})q group by unnest(${name})`, { table: loadTable.table, time: 5 })
39
- : await pg.queryCache(`select ${name}::text as id,count(*) from (${optimizedSQL})q group by ${name}`, { table: loadTable.table, time: 5 });
40
- const ids = countArr.rows.map(el1 => el1.id);
41
-
42
- const clsData = await getSelectVal({ pg, values: ids, name: el.data });
43
-
44
- const options = countArr.rows.map(cel => {
45
- const data = cls?.arr?.find(c => c.id === cel.id) || { text: clsData[cel.id] };
46
- return { ...cel, ...data };
47
- });
48
- Object.assign(el, { options });
49
- }));
50
-
51
- const q = ((loadTable?.filterState || []).concat(loadTable?.filterCustom || [])).filter((el) => el.name && el.sql).map((el) => `select count(*), '${el.name}' as name from (${optimizedSQL})q where ${el.sql}`).join(' union all ');
52
- const { rows = [] } = q ? await pg.query(q) : {};
53
- if (rows?.length) {
54
- ((loadTable?.filterState || []).concat(loadTable?.filterCustom || [])).filter((el) => el.name && el.sql).forEach((el) => {
55
- const { count } = rows.find((row) => row.name === el.name) || {};
56
- Object.assign(el, { count, sql: undefined });
57
- });
58
- }
59
-
60
- return {
61
- time: Date.now() - time,
62
- list: filters,
63
- custom: loadTable?.filterCustom,
64
- inline: loadTable?.filterInline,
65
- state: loadTable?.filterState,
66
- };
67
- }
1
+ import { getSelect, getFilterSQL, getTemplate, getSelectVal, pgClients } from '../../../../utils.js';
2
+
3
+ export default async function filterAPI(req) {
4
+ const time = Date.now();
5
+
6
+ const {
7
+ params, query = {}, pg = pgClients.client, user = {},
8
+ } = req;
9
+
10
+ const loadTable = await getTemplate('table', params.table);
11
+ if (!loadTable) { return { status: 404, message: 'not found' }; }
12
+
13
+ const sqlTable = loadTable.sql?.filter?.((el) => !el?.disabled && el?.sql?.replace).map((el, i) => ` left join lateral (${el.sql.replace('{{uid}}', user?.uid)}) ${el.name || `t${i}`} on 1=1 `)?.join('') || '';
14
+ const { fields: columns } = await pg.query(`select * from ${loadTable.table} t ${sqlTable} limit 0`);
15
+
16
+ const {
17
+ filter, custom, state, search,
18
+ } = query;
19
+
20
+ const { optimizedSQL = `select * from ${loadTable.table}` } = loadTable?.sql || filter || custom || state || search ? await getFilterSQL({
21
+ pg,
22
+ table: params.table,
23
+ filter,
24
+ custom,
25
+ state,
26
+ search,
27
+ }) : {};
28
+
29
+ const filters = loadTable?.filter_list || loadTable?.filters || loadTable?.filterList || [];
30
+ await Promise.all(filters.filter((el) => el.data && (el.id || el.name)).map(async (el) => {
31
+ const name = el.id || el.name;
32
+ const cls = await getSelect(el.data, pg);
33
+
34
+ if (!cls || !loadTable.table) return;
35
+ const { dataTypeID } = columns.find((item) => item.name === name) || {};
36
+
37
+ const countArr = pg.pgType[dataTypeID]?.includes('[]')
38
+ ? await pg.queryCache(`select unnest(${name})::text as id,count(*) from (${optimizedSQL})q group by unnest(${name})`, { table: loadTable.table, time: 5 })
39
+ : await pg.queryCache(`select ${name}::text as id,count(*) from (${optimizedSQL})q group by ${name}`, { table: loadTable.table, time: 5 });
40
+ const ids = countArr.rows.map(el1 => el1.id);
41
+
42
+ const clsData = await getSelectVal({ pg, values: ids, name: el.data });
43
+
44
+ const options = countArr.rows.map(cel => {
45
+ const data = cls?.arr?.find(c => c.id === cel.id) || { text: clsData[cel.id] };
46
+ return { ...cel, ...data };
47
+ });
48
+ Object.assign(el, { options });
49
+ }));
50
+
51
+ const q = ((loadTable?.filterState || []).concat(loadTable?.filterCustom || [])).filter((el) => el.name && el.sql).map((el) => `select count(*), '${el.name}' as name from (${optimizedSQL})q where ${el.sql}`).join(' union all ');
52
+ const { rows = [] } = q ? await pg.query(q) : {};
53
+ if (rows?.length) {
54
+ ((loadTable?.filterState || []).concat(loadTable?.filterCustom || [])).filter((el) => el.name && el.sql).forEach((el) => {
55
+ const { count } = rows.find((row) => row.name === el.name) || {};
56
+ Object.assign(el, { count, sql: undefined });
57
+ });
58
+ }
59
+
60
+ return {
61
+ time: Date.now() - time,
62
+ list: filters,
63
+ custom: loadTable?.filterCustom,
64
+ inline: loadTable?.filterInline,
65
+ state: loadTable?.filterState,
66
+ };
67
+ }
@@ -1,166 +1,166 @@
1
- import {
2
- config, getPG, getTemplate, getSelectMeta, getMeta, applyHook,
3
- } from '../../../../utils.js';
4
-
5
- const limit = 50;
6
- const headers = {
7
- 'Access-Control-Allow-Origin': '*',
8
- 'Access-Control-Allow-Methods': 'GET',
9
- 'Cache-Control': 'no-cache',
10
- };
11
-
12
- export default async function suggest(req) {
13
- const {
14
- params, query, pg: pg1, user,
15
- } = req;
16
-
17
- const lang = query.lang || 'ua';
18
- const time = Date.now();
19
- const parent = query.parent || '';
20
-
21
- const [table, column] = params.data?.includes(':') ? params.data.split(':') : [];
22
- const selectName = query.sel || query.name || params.data;
23
-
24
- if (!selectName) return { status: 400, message: 'name is required' };
25
-
26
- const { body: hookBody } = table || query.token ? await applyHook('preSuggest', { pg: pg1, table: table || query.token }) || {} : {};
27
- const body = await getTemplate('table', table);
28
- const tableName = hookBody?.table || body?.table || table || query.token;
29
-
30
- if (table && !pg1.pk?.[tableName]) {
31
- return { status: 400, message: 'param name is invalid: 1' };
32
- }
33
-
34
- const tableMeta = await getMeta({ pg: pg1, table: tableName });
35
- const columnExists = (hookBody?.columns || body?.columns || tableMeta?.columns)?.find((col) => col?.name === column);
36
-
37
- if (table && (!column || !columnExists)) {
38
- return { status: 400, message: 'param name is invalid: 2' };
39
- }
40
-
41
- if (query.limit && query.limit < 0) {
42
- return { status: 400, message: 'param limit is invalid' };
43
- }
44
-
45
- const meta = table && column
46
- ? {
47
- original: `with c(id,text) as (select row_number() over(), ${column} from ${tableName} group by ${column} limit ${limit}) select * from c`,
48
- searchQuery: '(lower("text") ~ $1 )',
49
- }
50
- : await getSelectMeta({ name: selectName, nocache: query?.nocache });
51
-
52
- if (meta?.minLength && query.key && query.key.length < meta?.minLength) {
53
- return { message: `min length: ${meta.minLength}` };
54
- }
55
-
56
- const pg = meta?.db ? getPG(meta.db) : pg1;
57
-
58
- if (!meta) {
59
- return { headers, status: 404, message: 'Not found query select ' };
60
- }
61
-
62
- if (query.meta) {
63
- return meta;
64
- }
65
-
66
- const { arr, searchQuery } = meta;
67
-
68
- if (arr && query.token && query.column) {
69
- const loadTable = await getTemplate('table', query.token);
70
-
71
- const { columns = [] } = await getMeta({ pg, table: tableName });
72
-
73
- const column = columns.find(el => el.name === query.column);
74
- const args = { table: tableName };
75
-
76
- const sqlCls = `select array_agg(distinct value) from (select ${pg.pgType[column.dataTypeID].includes('[]') ? `unnest(${column.name})` : `${column.name}`} as value from ${(tableName).replace(/'/g, "''")} where ${hookBody?.query || loadTable?.query || '1=1'})q`;
77
-
78
- if (query.sql && (config.local || user?.user_type?.includes?.('admin'))) {
79
- return sqlCls;
80
- }
81
-
82
- if (pg.pk?.[tableName] && column?.name) {
83
- const vals = await pg.queryCache(sqlCls, args).then(el => el.rows?.[0]?.array_agg || []);
84
- // console.log(vals);
85
-
86
- const lower = query.key?.toLowerCase();
87
- const data1 = query.key || query.val
88
- ? arr?.filter((el) => !lower || (el[lang] || el.text)?.toLowerCase()?.indexOf(lower) !== -1)?.filter((el) => !query.val || el.id === query.val)
89
- : arr;
90
-
91
- const data2 = data1.filter((el) => vals.includes(el.id));
92
- const data = data2.slice(0, Math.min(query.limit || limit, limit));
93
- return {
94
- time: Date.now() - time,
95
- limit: Math.min(query.limit || limit, limit),
96
- count: data.length,
97
- total: arr.length,
98
- mode: 'array',
99
- sql: (config.local || user?.user_type?.includes?.('admin')) ? sqlCls : undefined,
100
- data,
101
- };
102
- };
103
- }
104
-
105
- if (arr) {
106
- const lower = query.key?.toLowerCase();
107
- const data1 = query.key || query.val
108
- ? arr?.filter((el) => !lower || (el[lang] || el.text)?.toLowerCase()?.indexOf(lower) !== -1)?.filter((el) => !query.val || el.id === query.val)
109
- : arr;
110
- const data = data1.slice(0, Math.min(query.limit || limit, limit));
111
- return {
112
- time: Date.now() - time,
113
- limit: Math.min(query.limit || limit, limit),
114
- count: data.length,
115
- total: arr.length,
116
- mode: 'array',
117
- data,
118
- };
119
- }
120
-
121
- // search
122
- const search = query.key ? searchQuery : null;
123
-
124
- // val
125
- // const pk = meta.originalCols.split(',')[0];
126
- // return meta;
127
-
128
- const val = query.val ? ` ${meta.pk}=any('{${query.val.replace(/'/g, "''")}}')` : '';
129
- const where = [search, val, meta.pk ? `${meta.pk} is not null` : null].filter((el) => el).join(' and ') || 'true';
130
-
131
- const loadTable = await getTemplate('table', query.token);
132
-
133
- const tableName1 = hookBody?.table || loadTable?.table || query.token;
134
-
135
- const { columns = [] } = await getMeta({ pg: pg1, table: tableName1 });
136
-
137
- const filterColumn = query.column ? columns.find(el => el.name === query.column)?.name : null;
138
- const filter = query.token && pg.pk?.[loadTable?.table || query.token] && filterColumn
139
- ? `id in (select ${filterColumn} from ${(loadTable?.table || query.token).replace(/'/g, "''")})`
140
- : 'true';
141
-
142
- const sqlSuggest = `with c(id,text) as ( ${meta.original.replace(/{{parent}}/gi, parent)} where ${where} order by 2) select * from c where ${filter} limit ${Math.min(query.limit || meta.limit || limit, limit)}`.replace(/{{uid}}/g, user?.uid || '0');
143
-
144
- if (query.sql && (config.local || user?.user_type?.includes?.('admin'))) {
145
- return sqlSuggest;
146
- }
147
-
148
- // query
149
- const { rows: dataNew } = await pg.query(sqlSuggest, query.key ? [`${query.key.toLowerCase()}`] : []);
150
- // const { rows: dataNew1 } = dataNew.length < limit ? await pg.query(sqlSuggest, query.key ? [`${query.key}`] : []) : {};
151
- const ids = dataNew.map((el) => el.id);
152
- const data = dataNew.concat((/* dataNew1 || */[]).filter((el) => !ids?.includes(el.id)));
153
-
154
- const message = {
155
- time: Date.now() - time,
156
- limit: Math.min(query.limit || meta.limit || limit, limit),
157
- count: data.length,
158
- total: meta.count - 0,
159
- mode: 'sql',
160
- db: meta.db,
161
- sql: (config.local || user?.user_type?.includes?.('admin')) ? sqlSuggest : undefined,
162
- data,
163
- };
164
-
165
- return message;
166
- }
1
+ import {
2
+ config, getPG, getTemplate, getSelectMeta, getMeta, applyHook,
3
+ } from '../../../../utils.js';
4
+
5
+ const limit = 50;
6
+ const headers = {
7
+ 'Access-Control-Allow-Origin': '*',
8
+ 'Access-Control-Allow-Methods': 'GET',
9
+ 'Cache-Control': 'no-cache',
10
+ };
11
+
12
+ export default async function suggest(req) {
13
+ const {
14
+ params, query, pg: pg1, user,
15
+ } = req;
16
+
17
+ const lang = query.lang || 'ua';
18
+ const time = Date.now();
19
+ const parent = query.parent || '';
20
+
21
+ const [table, column] = params.data?.includes(':') ? params.data.split(':') : [];
22
+ const selectName = query.sel || query.name || params.data;
23
+
24
+ if (!selectName) return { status: 400, message: 'name is required' };
25
+
26
+ const { body: hookBody } = table || query.token ? await applyHook('preSuggest', { pg: pg1, table: table || query.token }) || {} : {};
27
+ const body = await getTemplate('table', table);
28
+ const tableName = hookBody?.table || body?.table || table || query.token;
29
+
30
+ if (table && !pg1.pk?.[tableName]) {
31
+ return { status: 400, message: 'param name is invalid: 1' };
32
+ }
33
+
34
+ const tableMeta = await getMeta({ pg: pg1, table: tableName });
35
+ const columnExists = (hookBody?.columns || body?.columns || tableMeta?.columns)?.find((col) => col?.name === column);
36
+
37
+ if (table && (!column || !columnExists)) {
38
+ return { status: 400, message: 'param name is invalid: 2' };
39
+ }
40
+
41
+ if (query.limit && query.limit < 0) {
42
+ return { status: 400, message: 'param limit is invalid' };
43
+ }
44
+
45
+ const meta = table && column
46
+ ? {
47
+ original: `with c(id,text) as (select row_number() over(), ${column} from ${tableName} group by ${column} limit ${limit}) select * from c`,
48
+ searchQuery: '(lower("text") ~ $1 )',
49
+ }
50
+ : await getSelectMeta({ name: selectName, nocache: query?.nocache });
51
+
52
+ if (meta?.minLength && query.key && query.key.length < meta?.minLength) {
53
+ return { message: `min length: ${meta.minLength}` };
54
+ }
55
+
56
+ const pg = meta?.db ? getPG(meta.db) : pg1;
57
+
58
+ if (!meta) {
59
+ return { headers, status: 404, message: 'Not found query select ' };
60
+ }
61
+
62
+ if (query.meta) {
63
+ return meta;
64
+ }
65
+
66
+ const { arr, searchQuery } = meta;
67
+
68
+ if (arr && query.token && query.column) {
69
+ const loadTable = await getTemplate('table', query.token);
70
+
71
+ const { columns = [] } = await getMeta({ pg, table: tableName });
72
+
73
+ const column = columns.find(el => el.name === query.column);
74
+ const args = { table: tableName };
75
+
76
+ const sqlCls = `select array_agg(distinct value) from (select ${pg.pgType[column.dataTypeID].includes('[]') ? `unnest(${column.name})` : `${column.name}`} as value from ${(tableName).replace(/'/g, "''")} where ${hookBody?.query || loadTable?.query || '1=1'})q`;
77
+
78
+ if (query.sql && (config.local || user?.user_type?.includes?.('admin'))) {
79
+ return sqlCls;
80
+ }
81
+
82
+ if (pg.pk?.[tableName] && column?.name) {
83
+ const vals = await pg.queryCache(sqlCls, args).then(el => el.rows?.[0]?.array_agg || []);
84
+ // console.log(vals);
85
+
86
+ const lower = query.key?.toLowerCase();
87
+ const data1 = query.key || query.val
88
+ ? arr?.filter((el) => !lower || (el[lang] || el.text)?.toLowerCase()?.indexOf(lower) !== -1)?.filter((el) => !query.val || el.id === query.val)
89
+ : arr;
90
+
91
+ const data2 = data1.filter((el) => vals.includes(el.id));
92
+ const data = data2.slice(0, Math.min(query.limit || limit, limit));
93
+ return {
94
+ time: Date.now() - time,
95
+ limit: Math.min(query.limit || limit, limit),
96
+ count: data.length,
97
+ total: arr.length,
98
+ mode: 'array',
99
+ sql: (config.local || user?.user_type?.includes?.('admin')) ? sqlCls : undefined,
100
+ data,
101
+ };
102
+ };
103
+ }
104
+
105
+ if (arr) {
106
+ const lower = query.key?.toLowerCase();
107
+ const data1 = query.key || query.val
108
+ ? arr?.filter((el) => !lower || (el[lang] || el.text)?.toLowerCase()?.indexOf(lower) !== -1)?.filter((el) => !query.val || el.id === query.val)
109
+ : arr;
110
+ const data = data1.slice(0, Math.min(query.limit || limit, limit));
111
+ return {
112
+ time: Date.now() - time,
113
+ limit: Math.min(query.limit || limit, limit),
114
+ count: data.length,
115
+ total: arr.length,
116
+ mode: 'array',
117
+ data,
118
+ };
119
+ }
120
+
121
+ // search
122
+ const search = query.key ? searchQuery : null;
123
+
124
+ // val
125
+ // const pk = meta.originalCols.split(',')[0];
126
+ // return meta;
127
+
128
+ const val = query.val ? ` ${meta.pk}=any('{${query.val.replace(/'/g, "''")}}')` : '';
129
+ const where = [search, val, meta.pk ? `${meta.pk} is not null` : null].filter((el) => el).join(' and ') || 'true';
130
+
131
+ const loadTable = await getTemplate('table', query.token);
132
+
133
+ const tableName1 = hookBody?.table || loadTable?.table || query.token;
134
+
135
+ const { columns = [] } = await getMeta({ pg: pg1, table: tableName1 });
136
+
137
+ const filterColumn = query.column ? columns.find(el => el.name === query.column)?.name : null;
138
+ const filter = query.token && pg.pk?.[loadTable?.table || query.token] && filterColumn
139
+ ? `id in (select ${filterColumn} from ${(loadTable?.table || query.token).replace(/'/g, "''")})`
140
+ : 'true';
141
+
142
+ const sqlSuggest = `with c(id,text) as ( ${meta.original.replace(/{{parent}}/gi, parent)} where ${where} order by 2) select * from c where ${filter} limit ${Math.min(query.limit || meta.limit || limit, limit)}`.replace(/{{uid}}/g, user?.uid || '0');
143
+
144
+ if (query.sql && (config.local || user?.user_type?.includes?.('admin'))) {
145
+ return sqlSuggest;
146
+ }
147
+
148
+ // query
149
+ const { rows: dataNew } = await pg.query(sqlSuggest, query.key ? [`${query.key.toLowerCase()}`] : []);
150
+ // const { rows: dataNew1 } = dataNew.length < limit ? await pg.query(sqlSuggest, query.key ? [`${query.key}`] : []) : {};
151
+ const ids = dataNew.map((el) => el.id);
152
+ const data = dataNew.concat((/* dataNew1 || */[]).filter((el) => !ids?.includes(el.id)));
153
+
154
+ const message = {
155
+ time: Date.now() - time,
156
+ limit: Math.min(query.limit || meta.limit || limit, limit),
157
+ count: data.length,
158
+ total: meta.count - 0,
159
+ mode: 'sql',
160
+ db: meta.db,
161
+ sql: (config.local || user?.user_type?.includes?.('admin')) ? sqlSuggest : undefined,
162
+ data,
163
+ };
164
+
165
+ return message;
166
+ }