@opengis/fastify-table 1.0.89 → 1.0.91

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,114 +1,117 @@
1
- import { test } from 'node:test';
2
- import assert from 'node:assert';
3
-
4
- import build from '../../helper.js';
5
- import config from '../config.js';
6
-
7
- const session = { passport: { user: { uid: config.testUser?.uid || '1' } } };
8
-
9
- import widgetGet from '../../widget/controllers/widget.get.js';
10
- import widgetSet from '../../widget/controllers/widget.set.js';
11
- import widgetDel from '../../widget/controllers/widget.del.js';
12
-
13
- import pgClients from '../../pg/pgClients.js';
14
-
15
- test('widget api', async (t) => {
16
- await build(t);
17
- const pg = pgClients.client;
18
-
19
- // comment
20
- let commentId;
21
- await t.test('POST /widget/comment/:objectid', async () => {
22
- const body = {};
23
- const resp = await widgetSet({
24
- pg, params: { type: 'comment', objectid: '1' }, session, body,
25
- });
26
- commentId = resp.id;
27
- assert.ok(commentId, 'comment widget insert fail');
28
- });
29
- await t.test('GET /widget/comment/:objectid', async () => {
30
- const resp = await widgetGet({
31
- pg, session, params: { type: 'comment', objectid: '1' },
32
- });
33
- assert.ok(resp.rows?.length, 'comment widget get fail');
34
- });
35
- await t.test('DELETE /widget/comment/:objectid', async () => {
36
- const resp = await widgetDel({
37
- pg, session, params: { type: 'comment', objectid: '1', id: commentId },
38
- });
39
- assert.ok(resp?.data?.id === commentId, 'comment widget delete fail');
40
- });
41
-
42
- // checklist
43
- let checklistId;
44
- await t.test('POST /widget/checklist/:objectid', async () => {
45
- const body = {};
46
- const resp = await widgetSet({
47
- pg, params: { type: 'checklist', objectid: '1' }, session, body,
48
- });
49
- checklistId = resp.id;
50
- assert.ok(checklistId, 'checklist widget insert fail');
51
- });
52
- await t.test('GET /widget/checklist/:objectid', async () => {
53
- const resp = await widgetGet({
54
- pg, session, params: { type: 'checklist', objectid: '1' },
55
- });
56
- assert.ok(resp.rows?.length, 'checklist widget data get fail');
57
- });
58
- await t.test('DELETE /widget/checklist/:objectid', async () => {
59
- const resp = await widgetDel({
60
- pg, session, params: { type: 'checklist', objectid: '1', id: checklistId },
61
- });
62
- assert.ok(resp?.data?.id === checklistId, 'checklist widget delete fail');
63
- });
64
-
65
- // before GET log request
66
- await t.test('FAKE POST /widget/history/:objectid', async() => {
67
- const res = await pg.query(`insert into log.table_changes(uid, entity_id, entity_type)
68
- select $1, '1', 'admin.users'`, [config.testUser?.uid || '1']);
69
- // console.log(res.rowCount);
70
- });
71
-
72
- // history
73
- await t.test('GET /widget/history/:objectid', async () => {
74
- const resp = await widgetGet({
75
- pg, session, params: { type: 'history', objectid: '1' },
76
- });
77
- assert.ok(resp.rows?.length > 0, 'history widget data get fail');
78
- });
79
-
80
- // file
81
- let fileId;
82
- /* @opengis/fastify-file dependency - funcs */
83
- /* await t.test('POST /widget/file/:objectid', async () => {
84
- const body = {};
85
- const resp = await widgetSet({
86
- pg, params: { type: 'file', objectid: '1' }, session, body,
87
- });
88
- fileId = resp.id;
89
- assert.ok(fileId, 'file widget insert fail');
90
- }); */
91
- await t.test('GET /widget/file/:objectid', async () => {
92
- const { rows } = await pg.query(`insert into crm.files(entity_id, entity_type, uid, file_status)
93
- select '1', 'admin.users', $1, 1 returning *`, [config.testUser?.uid || '1']);
94
- fileId = rows?.[0]?.file_id; // substitude for POST request
95
- const resp = await widgetGet({
96
- pg, session, params: { type: 'file', objectid: '1' },
97
- });
98
- assert.ok(resp.rows?.length, 'file widget data get fail');
99
- });
100
- await t.test('DELETE /widget/file/:objectid', async () => {
101
- const resp = await widgetDel({
102
- pg, session, params: { type: 'file', objectid: '1', id: fileId },
103
- });
104
- assert.ok(resp?.data?.id === fileId, 'file widget delete fail');
105
- });
106
-
107
- await t.test('clean after test', async() => {
108
- const res1 = await pg.query(`delete from crm.communications where entity_id=$1`, ['1']);
109
- const res2 = await pg.query(`delete from crm.checklists where entity_id=$1`, ['1']);
110
- const res3 = await pg.query(`delete from crm.files where entity_id=$1`, ['1']);
111
- const res4 = await pg.query(`delete from log.table_changes where entity_id=$1`, ['1']);
112
- pg.end();
113
- });
114
- });
1
+ import { test } from 'node:test';
2
+ import assert from 'node:assert';
3
+
4
+ import build from '../../helper.js';
5
+ import config from '../config.js';
6
+
7
+ const session = { passport: { user: { uid: config.testUser?.uid || '1' } } };
8
+
9
+ import widgetGet from '../../widget/controllers/widget.get.js';
10
+ import widgetSet from '../../widget/controllers/widget.set.js';
11
+ import widgetDel from '../../widget/controllers/widget.del.js';
12
+
13
+ import pgClients from '../../pg/pgClients.js';
14
+
15
+ test('widget api', async (t) => {
16
+ await build(t);
17
+ const pg = pgClients.client;
18
+
19
+ // comment
20
+ let commentId;
21
+ await t.test('POST /widget/comment/:objectid', async () => {
22
+ const body = {};
23
+ const resp = await widgetSet({
24
+ pg, params: { type: 'comment', objectid: '1' }, session, body,
25
+ });
26
+ commentId = resp.id;
27
+ assert.ok(commentId, 'comment widget insert fail');
28
+ });
29
+ await t.test('GET /widget/comment/:objectid', async () => {
30
+ const resp = await widgetGet({
31
+ pg, session, params: { type: 'comment', objectid: '1' },
32
+ });
33
+ assert.ok(resp.rows?.length, 'comment widget get fail');
34
+ });
35
+ await t.test('DELETE /widget/comment/:objectid', async () => {
36
+ const resp = await widgetDel({
37
+ pg, session, params: { type: 'comment', objectid: '1', id: commentId },
38
+ });
39
+ assert.ok(resp?.data?.id === commentId, 'comment widget delete fail');
40
+ });
41
+
42
+ // checklist
43
+ let checklistId;
44
+ await t.test('POST /widget/checklist/:objectid', async () => {
45
+ const body = {};
46
+ const resp = await widgetSet({
47
+ pg, params: { type: 'checklist', objectid: '1' }, session, body,
48
+ });
49
+ checklistId = resp.id;
50
+ assert.ok(checklistId, 'checklist widget insert fail');
51
+ });
52
+ await t.test('GET /widget/checklist/:objectid', async () => {
53
+ const resp = await widgetGet({
54
+ pg, session, params: { type: 'checklist', objectid: '1' },
55
+ });
56
+ assert.ok(resp.rows?.length, 'checklist widget data get fail');
57
+ });
58
+ await t.test('DELETE /widget/checklist/:objectid', async () => {
59
+ const resp = await widgetDel({
60
+ pg, session, params: { type: 'checklist', objectid: '1', id: checklistId },
61
+ });
62
+ assert.ok(resp?.data?.id === checklistId, 'checklist widget delete fail');
63
+ });
64
+
65
+ // before GET log request
66
+ await t.test('FAKE POST /widget/history/:objectid', async () => {
67
+ const { changeId } = await pg.query(`insert into log.table_changes(uid, entity_id, entity_type)
68
+ select $1, '1', 'admin.users' returning change_id as "changeId"`, [config.testUser?.uid || '1']).then((res) => res.rows?.[0] || {});
69
+ const res1 = await pg.query(`insert into log.table_changes_data(change_id, entity_key, value_new)
70
+ select $1, 'uid', $2`, [changeId, config.testUser?.uid || '1']);
71
+ // console.log(res.rowCount);
72
+ });
73
+
74
+ // history
75
+ await t.test('GET /widget/history/:objectid', async () => {
76
+ const resp = await widgetGet({
77
+ pg, session, params: { type: 'history', objectid: '1' },
78
+ });
79
+ assert.ok(resp.rows?.length > 0, 'history widget data get fail');
80
+ });
81
+
82
+ // file
83
+ let fileId;
84
+ /* @opengis/fastify-file dependency - funcs */
85
+ /* await t.test('POST /widget/file/:objectid', async () => {
86
+ const body = {};
87
+ const resp = await widgetSet({
88
+ pg, params: { type: 'file', objectid: '1' }, session, body,
89
+ });
90
+ fileId = resp.id;
91
+ assert.ok(fileId, 'file widget insert fail');
92
+ }); */
93
+ await t.test('GET /widget/file/:objectid', async () => {
94
+ const { rows } = await pg.query(`insert into crm.files(entity_id, entity_type, uid, file_status)
95
+ select '1', 'admin.users', $1, 1 returning *`, [config.testUser?.uid || '1']);
96
+ fileId = rows?.[0]?.file_id; // substitude for POST request
97
+ const resp = await widgetGet({
98
+ pg, session, params: { type: 'file', objectid: '1' },
99
+ });
100
+ assert.ok(resp.rows?.length, 'file widget data get fail');
101
+ });
102
+ await t.test('DELETE /widget/file/:objectid', async () => {
103
+ const resp = await widgetDel({
104
+ pg, session, params: { type: 'file', objectid: '1', id: fileId },
105
+ });
106
+ assert.ok(resp?.data?.id === fileId, 'file widget delete fail');
107
+ });
108
+
109
+ await t.test('clean after test', async () => {
110
+ const res1 = await pg.query('delete from crm.communications where entity_id=$1', ['1']);
111
+ const res2 = await pg.query('delete from crm.checklists where entity_id=$1', ['1']);
112
+ const res3 = await pg.query('delete from crm.files where entity_id=$1', ['1']);
113
+ const res4 = await pg.query('delete from log.table_changes_data where change_id in (select change_id from log.table_changes where entity_id=$1)', ['1']);
114
+ const res5 = await pg.query('delete from log.table_changes where entity_id=$1', ['1']);
115
+ pg.end();
116
+ });
117
+ });
@@ -1,76 +1,122 @@
1
- import { test } from 'node:test';
2
- import assert from 'node:assert';
3
- import config from '../config.js';
4
- import pgClients from '../../pg/pgClients.js';
5
- import rclient from '../../redis/client.js';
6
-
7
- import dataInsert from '../../crud/funcs/dataInsert.js';
8
- import dataUpdate from '../../crud/funcs/dataUpdate.js';
9
- import dataDelete from '../../crud/funcs/dataDelete.js';
10
- import isFileExists from '../../crud/funcs/isFileExists.js';
11
-
12
- import getOpt from '../../crud/funcs/getOpt.js';
13
- import setOpt from '../../crud/funcs/setOpt.js';
14
-
15
- import getToken from '../../crud/funcs/getToken.js';
16
- import setToken from '../../crud/funcs/setToken.js';
17
-
18
- test('funcs crud', async (t) => {
19
- await pgClients.client.init();
20
- await t.test('getOpt/setOpt', async () => {
21
- const opt = await setOpt({ table: 'gis.dataset' });
22
- const data = await getOpt(opt);
23
- // console.log(data);
24
- assert.equal(data.table, 'gis.dataset');
25
- });
26
-
27
- const id = (Math.random() * 10000).toFixed();
28
- /* await t.test('dataInsert', async () => {
29
- const data = await dataInsert({ table: 'gis.dataset', data: { dataset_id: id, dataset_name: '222' } });
30
- assert.equal(data.dataset_id, id);
31
- });
32
-
33
- await t.test('dataUpdate', async () => {
34
- const data = await dataUpdate({ table: 'gis.dataset', id, data: { dataset_name: '22211' } });
35
- assert.equal(data.dataset_name, '22211');
36
- });
37
-
38
- await t.test('dataDelete', async () => {
39
- const data = await dataDelete({ table: 'gis.dataset', id });
40
- assert.ok(data);
41
- }); */
42
-
43
- await t.test('isFileExists', async () => {
44
- const data = await isFileExists({ filepath: '../../crud/funcs/isFileExists.js' });
45
- assert.equal(data, false);
46
- });
47
-
48
- let tokens;
49
- const session = { passport: { user: { uid: '1' } } };
50
- const tokenData = JSON.stringify({ add: 'gis.dataset', form: 'test.dataset.form' });
51
-
52
- await t.test('setToken', async () => {
53
- tokens = setToken({
54
- funcs: { config },
55
- ids: [tokenData],
56
- mode: 'a',
57
- uid: 1,
58
- array: 1,
59
- });
60
- assert.equal(tokens.length, 1);
61
- });
62
- await t.test('getToken', async () => {
63
- const data = await getToken({
64
- uid: 1,
65
- token: tokens[0],
66
- mode: 'a',
67
- });
68
- assert.equal(data, tokenData);
69
- });
70
-
71
- // pgClients.client.query('delete from gis.dataset where dataset_id=$1', [id]);
72
- t.after(() => {
73
- pgClients.client?.end();
74
- rclient.quit();
75
- });
76
- });
1
+ import { test } from 'node:test';
2
+ import assert from 'node:assert';
3
+ import config from '../config.js';
4
+ import pgClients from '../../pg/pgClients.js';
5
+ import rclient from '../../redis/client.js';
6
+
7
+ import dataInsert from '../../crud/funcs/dataInsert.js';
8
+ import dataUpdate from '../../crud/funcs/dataUpdate.js';
9
+ import dataDelete from '../../crud/funcs/dataDelete.js';
10
+ import logChanges from '../../crud/funcs/utils/logChanges.js';
11
+ import isFileExists from '../../crud/funcs/isFileExists.js';
12
+
13
+ import getOpt from '../../crud/funcs/getOpt.js';
14
+ import setOpt from '../../crud/funcs/setOpt.js';
15
+
16
+ import getToken from '../../crud/funcs/getToken.js';
17
+ import setToken from '../../crud/funcs/setToken.js';
18
+
19
+ test('funcs crud', async (t) => {
20
+ await pgClients.client.init();
21
+ await t.test('getOpt/setOpt', async () => {
22
+ const opt = await setOpt({ table: 'gis.dataset' });
23
+ const data = await getOpt(opt);
24
+ // console.log(data);
25
+ assert.equal(data.table, 'gis.dataset');
26
+ });
27
+
28
+ if (config?.local) {
29
+ const id = (Math.random() * 10000).toFixed();
30
+ await t.test('dataInsert', async () => {
31
+ const data = await dataInsert({ table: 'gis.dataset', data: { dataset_id: id, dataset_name: '222' }, uid: '2' });
32
+ assert.equal(data.rows?.[0]?.dataset_id, id);
33
+ });
34
+ await t.test('dataUpdate', async () => {
35
+ const data = await dataUpdate({
36
+ table: 'gis.dataset', id, data: { dataset_name: '22211' }, uid: '2',
37
+ });
38
+ assert.equal(data.dataset_name, '22211');
39
+ });
40
+ await t.test('dataDelete', async () => {
41
+ const data = await dataDelete({ table: 'gis.dataset', id, uid: '2' });
42
+ assert.ok(data);
43
+ });
44
+ await t.test('clean up after test', async () => {
45
+ if (pgClients.client.pk?.['log.table_changes_data']) {
46
+ const { rowCount: testDatasets } = await pgClients.client.query('delete from gis.dataset where uid=$1', ['2']);
47
+ const { rowCount } = await pgClients.client.query('delete from log.table_changes_data where change_id in (select change_id from log.table_changes where entity_id=$1)', [id]);
48
+ const { rowCount: rowCount1 } = await pgClients.client.query('delete from log.table_changes where entity_id=$1', [id]);
49
+ console.log('CRUD test clean up', id, testDatasets, rowCount, rowCount1);
50
+ assert.ok(rowCount1);
51
+ }
52
+ });
53
+ }
54
+
55
+ if (pgClients.client.pk?.['log.table_changes_data']) {
56
+ const id = (Math.random() * 10000).toFixed();
57
+ const name = '222';
58
+ await t.test('logChanges INSERT', async () => {
59
+ await pgClients.client.query(`insert into gis.dataset(dataset_id,dataset_name, uid) values($1,$2,$3) on conflict(dataset_id) do
60
+ update set dataset_name = excluded.dataset_name, uid = excluded.uid`, [id, name, '2']);
61
+
62
+ const data = await logChanges({
63
+ pg: pgClients.client, id, table: 'gis.dataset', data: { dataset_id: id, dataset_name: '222' }, uid: '2', type: 'INSERT',
64
+ });
65
+ assert.ok(data?.change_type === 'INSERT' && data?.entity_id === id && data?.new?.dataset_name === '222', typeof data === 'object' ? JSON.stringify(data) : data);
66
+ });
67
+ await t.test('logChanges UPDATE', async () => {
68
+ /* await pgClients.client.query('update gis.dataset(dataset_id,dataset_name) set dataset_name=$', [id, name]); */
69
+ const data = await logChanges({
70
+ pg: pgClients.client, id, table: 'gis.dataset', data: { dataset_id: id, dataset_name: '2222' }, uid: '2', type: 'UPDATE',
71
+ });
72
+ assert.ok(data?.change_type === 'UPDATE' && data?.entity_id === id && data?.new?.dataset_name === '2222' && data?.old?.dataset_name === '222', typeof data === 'object' ? JSON.stringify(data) : data);
73
+ });
74
+ await t.test('logChanges DELETE', async () => {
75
+ const data = await logChanges({
76
+ pg: pgClients.client, id, table: 'gis.dataset', uid: '2', type: 'DELETE',
77
+ });
78
+ assert.ok(data?.change_type === 'DELETE' && data?.old?.dataset_id === id, typeof data === 'object' ? JSON.stringify(data) : data);
79
+ });
80
+ await t.test('clean up after test', async () => {
81
+ const { rowCount: testDatasets } = await pgClients.client.query('delete from gis.dataset where uid=$1', ['2']);
82
+ const { rowCount } = await pgClients.client.query('delete from log.table_changes_data where change_id in (select change_id from log.table_changes where entity_id=$1)', [id]);
83
+ const { rowCount: rowCount1 } = await pgClients.client.query('delete from log.table_changes where entity_id=$1', [id]);
84
+ console.log('logChanges test clean up', id, testDatasets, rowCount, rowCount1);
85
+ assert.ok(rowCount1);
86
+ });
87
+ }
88
+
89
+ await t.test('isFileExists', async () => {
90
+ const data = await isFileExists({ filepath: '../../crud/funcs/isFileExists.js' });
91
+ assert.equal(data, false);
92
+ });
93
+
94
+ let tokens;
95
+ // const session = { passport: { user: { uid: '1' } } };
96
+ const tokenData = JSON.stringify({ add: 'gis.dataset', form: 'test.dataset.form' });
97
+
98
+ await t.test('setToken', async () => {
99
+ tokens = setToken({
100
+ funcs: { config },
101
+ ids: [tokenData],
102
+ mode: 'a',
103
+ uid: 1,
104
+ array: 1,
105
+ });
106
+ assert.equal(tokens.length, 1);
107
+ });
108
+ await t.test('getToken', async () => {
109
+ const data = await getToken({
110
+ uid: 1,
111
+ token: tokens[0],
112
+ mode: 'a',
113
+ });
114
+ assert.equal(data, tokenData);
115
+ });
116
+
117
+ // pgClients.client.query('delete from gis.dataset where dataset_id=$1', [id]);
118
+ t.after(() => {
119
+ pgClients.client?.end();
120
+ rclient.quit();
121
+ });
122
+ });
@@ -0,0 +1,90 @@
1
+ import path from 'path';
2
+ import { lstat, readdir } from 'fs/promises';
3
+ import { createReadStream, existsSync } from 'fs';
4
+ import readline from 'readline';
5
+
6
+ import checkUserAccess from './utils/checkUserAccess.js';
7
+ import getRootDir from './utils/getRootDir.js';
8
+
9
+ /**
10
+ *
11
+ * @method GET
12
+ * @summary API для перегляду логів
13
+ *
14
+ */
15
+
16
+ export default async function loggerFile({
17
+ pg, params = {}, user = {}, query = {}, originalUrl, funcs = {},
18
+ }, reply) {
19
+ const limit = 200000;
20
+ const access = pg ? await checkUserAccess({ user, pg }) : {};
21
+
22
+ const { config = {} } = funcs;
23
+ if (access?.status === 403 && !config?.local) return access;
24
+
25
+ // absolute / relative path
26
+ const rootDir = getRootDir(config);
27
+ const filepath = path.join(rootDir, params['*'] || '');
28
+
29
+ if (!existsSync(filepath)) {
30
+ return { error: 'file not exists', status: 404 };
31
+ }
32
+ const stat = await lstat(filepath);
33
+ const isFile = stat.isFile();
34
+
35
+ if (query.download && isFile) {
36
+ return reply.download(filepath);
37
+ }
38
+
39
+ if (query.full && isFile) {
40
+ if (stat.size > 20 * 1000 * 1000) {
41
+ return { message: 'file size > 20MB' };
42
+ }
43
+ const buffer = await readFile(filepath, { buffer: true });
44
+ return buffer;
45
+ }
46
+
47
+ if (isFile) {
48
+ const ext = path.extname(filepath);
49
+
50
+ const lines = await new Promise((resolve) => {
51
+ const rl = readline.createInterface({
52
+ input: createReadStream(filepath, { start: stat.size > limit ? stat.size - limit : 0 }),
53
+ });
54
+ const lines1 = [];
55
+ rl.on('close', () => resolve(lines1));
56
+ rl.on('line', (line) => lines1.push(line));
57
+ });
58
+
59
+ if (ext === '.html') {
60
+ const buffer = await readFile(filepath, { buffer: true });
61
+ reply.headers({ 'Content-type': 'text/html; charset=UTF-8' });
62
+ return buffer;
63
+ }
64
+
65
+ reply.headers({ 'Content-type': 'text/plain' });
66
+ return stat.size > limit && lines.length > 1
67
+ ? lines.reverse().slice(0, -1).join('\n')
68
+ : lines.reverse().join('\n');
69
+ }
70
+
71
+ // dir
72
+ const files = await readdir(filepath);
73
+
74
+ if (query.dir) {
75
+ return files.filter((el) => !['backup', 'marker_icon', 'error', 'migration'].includes(el));
76
+ }
77
+
78
+ const lstatsArr = await Promise.all(files.map(async (file) => [file, await lstat(path.join(filepath, file))]));
79
+ const lstats = Object.fromEntries(lstatsArr);
80
+
81
+ const message = (params['*'] ? '<a href="/logger-file/">...</a><br>' : '')
82
+ + files.map((file) => `<a href="${originalUrl}/${file}">${file}</a> (${lstats[file].size} bytes)`).join('</br>');
83
+
84
+ reply.headers({
85
+ 'Content-Type': 'text/html; charset=UTF-8',
86
+ 'Content-Security-Policy': "default-src 'none'",
87
+ 'X-Content-Type-Options': 'nosniff',
88
+ });
89
+ return message;
90
+ }
@@ -1,51 +1,57 @@
1
- import dataInsert from "../../crud/funcs/dataInsert.js";
2
-
3
- const table = 'crm.properties';
4
-
5
- function checkKeyType({ body, key }) {
6
- if (typeof body[key] === 'number' && (!/\D/.test(body[key].toString()) && body[key].toString().length < 10)) {
7
- return { [key]: 'int' };
8
- } else if (typeof body[key] === 'object') {
9
- return { [key]: 'json' };
10
- } else if (Date.parse(body[key], 'yyyy/MM/ddTHH:mm:ss.000Z')) {
11
- return { [key]: 'date' };
12
- }
13
- return { [key]: 'text' };
14
- }
15
-
16
- export default async function addExtraProperties({
17
- pg, params = {}, body = {},
18
- }) {
19
- const { id } = params;
20
- if (!id) {
21
- return { message: 'not enougn params: 1', status: 400 };
22
- }
23
- const extraProperties = Object.keys(body);
24
- if (!extraProperties.length) {
25
- return { message: 'not enougn params: 2', status: 400 };
26
- }
27
-
28
- if (!pg.pk?.[table]) {
29
- return { message: 'table not found: crm.properties', status: 400 };
30
- }
31
-
32
- try {
33
- await pg.query(`delete from crm.properties where object_id=$1`, [id]);
34
- const keyTypeMatch = extraProperties.filter((key) => body[key]).reduce((acc, curr) => Object.assign(acc, checkKeyType({ body, key: curr })), {});
35
- const res = await Promise.all(Object.keys(keyTypeMatch).map(async (key) => {
36
- const propertyType = keyTypeMatch[key];
37
- const { rows = [] } = await dataInsert({
38
- pg, table, data: {
39
- property_type: propertyType,
40
- property_key: key,
41
- object_id: id,
42
- [`property_${propertyType}`]: body[key],
43
- }
44
- });
45
- return { id: rows[0]?.property_id, type: propertyType, value: body[key] };
46
- }));
47
- return { message: { rows: res }, status: 200 };
48
- } catch (err) {
49
- return { error: err.toString(), status: 500 };
50
- }
51
- }
1
+ import dataInsert from '../../crud/funcs/dataInsert.js';
2
+
3
+ const table = 'crm.properties';
4
+
5
+ function checkKeyType({ body, key }) {
6
+ if (typeof body[key] === 'number' && (!/\D/.test(body[key].toString()) && body[key].toString().length < 10)) {
7
+ return { [key]: 'int' };
8
+ } if (typeof body[key] === 'object') {
9
+ return { [key]: 'json' };
10
+ }
11
+ if (Date.parse(body[key], 'yyyy/MM/ddTHH:mm:ss.000Z')) {
12
+ return { [key]: 'date' };
13
+ }
14
+ return { [key]: 'text' };
15
+ }
16
+
17
+ export default async function addExtraProperties({
18
+ pg, funcs, params = {}, body = {}, user = {},
19
+ }) {
20
+ const { id } = params;
21
+ if (!id) {
22
+ return { message: 'not enougn params: 1', status: 400 };
23
+ }
24
+ const extraProperties = Object.keys(body);
25
+ if (!extraProperties.length) {
26
+ return { message: 'not enougn params: 2', status: 400 };
27
+ }
28
+
29
+ if (!pg.pk?.[table]) {
30
+ return { message: 'table not found: crm.properties', status: 400 };
31
+ }
32
+
33
+ try {
34
+ const uid = funcs.config?.auth?.disable ? '1' : user.uid;
35
+ await pg.query('delete from crm.properties where object_id=$1', [id]); // rewrite?
36
+ const keyTypeMatch = extraProperties.filter((key) => body[key]).reduce((acc, curr) => Object.assign(acc, checkKeyType({ body, key: curr })), {});
37
+ const res = await Promise.all(Object.keys(keyTypeMatch).map(async (key) => {
38
+ const propertyType = keyTypeMatch[key];
39
+ const { rows = [] } = await dataInsert({
40
+ pg,
41
+ table,
42
+ data: {
43
+ property_type: propertyType,
44
+ property_key: key,
45
+ object_id: id,
46
+ [`property_${propertyType}`]: body[key],
47
+ },
48
+ uid,
49
+ });
50
+ return { id: rows[0]?.property_id, type: propertyType, value: body[key] };
51
+ }));
52
+ return { message: { rows: res }, status: 200 };
53
+ }
54
+ catch (err) {
55
+ return { error: err.toString(), status: 500 };
56
+ }
57
+ }