@opengis/fastify-table 1.4.47 → 1.4.49

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/index.js CHANGED
@@ -1,8 +1,9 @@
1
1
  import path from 'node:path';
2
2
  import { existsSync, readdirSync, readFileSync } from 'node:fs';
3
- import fp from 'fastify-plugin';
4
3
  import { fileURLToPath } from 'node:url';
5
4
 
5
+ import fp from 'fastify-plugin';
6
+
6
7
  import config from './config.js';
7
8
 
8
9
  const { maxFileSize = 512 } = config;
@@ -15,6 +16,7 @@ import cronPlugin from './server/plugins/cron/index.js';
15
16
  import crudPlugin from './server/plugins/crud/index.js';
16
17
 
17
18
  import pgPlugin from './server/plugins/pg/index.js';
19
+ import sqlitePlugin from './server/plugins/sqlite/index.js';
18
20
  import policyPlugin from './server/plugins/policy/index.js';
19
21
  import metricPlugin from './server/plugins/metric/index.js';
20
22
  import redisPlugin from './server/plugins/redis/index.js';
@@ -95,12 +97,20 @@ async function plugin(fastify, opt) {
95
97
  redisPlugin(fastify);
96
98
  // helperPlugin(fastify);
97
99
  await pgPlugin(fastify, opt);
100
+ await sqlitePlugin(fastify, opt);
98
101
  tablePlugin(fastify, opt);
99
102
  crudPlugin(fastify, opt);
100
103
  utilPlugin(fastify, opt);
101
104
  cronPlugin(fastify, opt);
102
105
  loggerPlugin(fastify, opt);
103
106
 
107
+ await fastify.register(import('@fastify/rate-limit'), {
108
+ max: 100,
109
+ timeWindow: '1 minute',
110
+ global: true,
111
+ keyGenerator: (req) => `${req.ip}-${req.raw.url.split('?')[0]}`,
112
+ });
113
+
104
114
  if (config.dblist) {
105
115
  dblistRoutes(fastify, opt);
106
116
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@opengis/fastify-table",
3
- "version": "1.4.47",
3
+ "version": "1.4.49",
4
4
  "type": "module",
5
5
  "description": "core-plugins",
6
6
  "keywords": [
@@ -34,8 +34,10 @@
34
34
  "@aws-sdk/client-s3": "3.554.0",
35
35
  "@fastify/http-proxy": "11.1.2",
36
36
  "@fastify/multipart": "9.0.3",
37
+ "@fastify/rate-limit": "10.3.0",
37
38
  "@grpc/grpc-js": "1.10.6",
38
39
  "@grpc/proto-loader": "0.7.12",
40
+ "better-sqlite3": "12.2.0",
39
41
  "dotenv": "16.5.0",
40
42
  "fastify": "5.3.3",
41
43
  "fastify-plugin": "5.0.1",
@@ -1,26 +1,33 @@
1
- /* eslint-disable consistent-return */
1
+ import path from 'node:path';
2
+ import { fileURLToPath } from 'url';
3
+
2
4
  import grpc from '@grpc/grpc-js';
3
5
  import protoLoader from '@grpc/proto-loader';
4
6
 
5
7
  import config from '../../../config.js';
6
8
  import logger from '../logger/getLogger.js';
7
9
 
8
- config.ready = config.ready || {};
10
+ const filename = fileURLToPath(import.meta.url);
11
+ const dirname = path.dirname(filename);
9
12
 
10
- // const { convertServerAddress = '193.239.152.181:44003' } = config;
13
+ config.ready = config.ready || {};
11
14
 
12
15
  // external ip not-accessible from internal network
13
- const defaultConvertServerAddress = config.pg?.host?.startsWith('192.168.3') ? '192.168.1.96:4003' : '193.239.152.181:44003';
16
+ const defaultConvertServerAddress = config.pg?.host?.startsWith?.('192.168.3')
17
+ ? '192.168.1.96:4003'
18
+ : '193.239.152.181:44003';
14
19
 
15
- const convertServerAddress = config.convertServerAddress || defaultConvertServerAddress;
20
+ const convertServerAddress = config.convertServerAddress === true
21
+ ? defaultConvertServerAddress
22
+ : config.convertServerAddress;
16
23
 
17
- console.log('convertServerAddress: ', convertServerAddress, !!config.convertServerAddress);
24
+ if (config.local || config.debug) console.log('convertServerAddress: ', convertServerAddress, !!config.convertServerAddress);
18
25
 
19
- const relpath = 'server/plugins/grpc/utils/convertp.proto';
20
- const protoLocation = process.cwd().includes('fastify-table') ? relpath : `node_modules/@opengis/fastify-table/${relpath}`;
26
+ // const relpath = 'server/plugins/grpc/utils/convertp.proto';
27
+ // const protoLocation = process.cwd().includes('fastify-table') ? relpath : `node_modules/@opengis/fastify-table/${relpath}`;
21
28
 
22
29
  const proto = grpc.loadPackageDefinition(
23
- protoLoader.loadSync(protoLocation, {
30
+ protoLoader.loadSync(`${dirname}/utils/convertp.proto`, {
24
31
  keepCase: true,
25
32
  longs: String,
26
33
  enums: String,
@@ -29,267 +36,85 @@ const proto = grpc.loadPackageDefinition(
29
36
  }),
30
37
  );
31
38
 
32
- const convertClient = new proto.Convert(
39
+ const convertClient = convertServerAddress ? new proto.Convert(
33
40
  convertServerAddress,
34
41
  grpc.credentials.createInsecure(),
35
42
  {
36
43
  'grpc.max_send_message_length': 512 * 1024 * 1024,
37
44
  'grpc.max_receive_message_length': 512 * 1024 * 1024,
38
45
  },
39
- );
40
-
41
- convertClient.waitForReady(Date.now() + 5000, (err) => {
42
- if (err) {
43
- config.ready.convert = false;
44
- console.error('Client connection timeout or failure:', err);
46
+ ) : {};
47
+
48
+ if (convertServerAddress) {
49
+ convertClient.waitForReady(Date.now() + 5000, (err) => {
50
+ if (err) {
51
+ config.ready.convert = false;
52
+ console.error('Client connection timeout or failure:', err);
53
+ }
54
+ else {
55
+ config.ready.convert = true;
56
+ console.log('Client connected successfully.');
57
+ // You can now make RPC calls safely
58
+ }
59
+ });
60
+ }
61
+
62
+ const methodNames = [
63
+ 'pdfMerge',
64
+ 'htmlToPdf',
65
+ 'csvToXls',
66
+ 'jsonToXls',
67
+ 'excelToJson',
68
+ 'xmlToJson',
69
+ 'htmlToDoc',
70
+ 'htmlToImage',
71
+ 'shpToGeojson',
72
+ 'geojsonToShp',
73
+ 'geojsonToGpkg',
74
+ 'docToPDF',
75
+ 'mergeImages',
76
+ 'resizeImage',
77
+ 'jsonToYaml',
78
+ 'yamlToJson',
79
+ 'log',
80
+ ];
81
+
82
+ const wrapGrpcCall = (methodName) => async (data) => new Promise((res, rej) => {
83
+ if (!convertServerAddress) {
84
+ logger.file('grpc/convert', {
85
+ method: methodName,
86
+ error: 'grpc convert not set',
87
+ stack: new Error().stack,
88
+ });
89
+ return rej(new Error('grpc convert not set'));
45
90
  }
46
- else {
47
- config.ready.convert = true;
48
- console.log('Client connected successfully.');
49
- // You can now make RPC calls safely
50
- }
51
- });
52
-
53
- // rewrite, merge??
54
- const pdfMerge = async (data) => new Promise((res, rej) => {
55
- convertClient.pdfMerge(data, (err, data1) => {
56
- if (err) {
57
- logger.file('grpc/convert', { error: err.toString(), stack: err.stack, ready: config.ready.convert });
58
- if (!config.ready.convert) {
59
- return rej(new Error('no grpc convert connection'));
60
- }
61
- return rej(err);
62
- }
63
- res(data1);
64
- });
65
- });
66
-
67
- const htmlToPdf = async (data) => new Promise((res, rej) => {
68
- convertClient.htmlToPdf(data, (err, data1) => {
69
- if (err) {
70
- logger.file('grpc/convert', { error: err.toString(), stack: err.stack, ready: config.ready.convert });
71
- if (!config.ready.convert) {
72
- return rej(new Error('no grpc convert connection'));
73
- }
74
- return rej(err);
75
- }
76
- res(data1);
77
- });
78
- });
79
-
80
- const csvToXls = async (data) => new Promise((res, rej) => {
81
- convertClient.csvToXls(data, (err, data1) => {
82
- if (err) {
83
- logger.file('grpc/convert', { error: err.toString(), stack: err.stack, ready: config.ready.convert });
84
- if (!config.ready.convert) {
85
- return rej(new Error('no grpc convert connection'));
86
- }
87
- return rej(err);
88
- }
89
- res(data1);
90
- });
91
- });
92
-
93
- const jsonToXls = async (data) => new Promise((res, rej) => {
94
- convertClient.jsonToXls(data, (err, data1) => {
95
- if (err) {
96
- logger.file('grpc/convert', { error: err.toString(), stack: err.stack, ready: config.ready.convert });
97
- if (!config.ready.convert) {
98
- return rej(new Error('no grpc convert connection'));
99
- }
100
- return rej(err);
101
- }
102
- res(data1);
103
- });
104
- });
105
-
106
- const excelToJson = async (data) => new Promise((res, rej) => {
107
- convertClient.excelToJson(data, (err, data1) => {
108
- if (err) {
109
- logger.file('grpc/convert', { error: err.toString(), stack: err.stack, ready: config.ready.convert });
110
- if (!config.ready.convert) {
111
- return rej(new Error('no grpc convert connection'));
112
- }
113
- return rej(err);
114
- }
115
- res(data1);
116
- });
117
- });
118
-
119
- const xmlToJson = async (data) => new Promise((res, rej) => {
120
- convertClient.xmlToJson(data, (err, data1) => {
121
- if (err) {
122
- logger.file('grpc/convert', { error: err.toString(), stack: err.stack, ready: config.ready.convert });
123
- if (!config.ready.convert) {
124
- return rej(new Error('no grpc convert connection'));
125
- }
126
- return rej(err);
127
- }
128
- res(data1);
129
- });
130
- });
131
-
132
- const html2Doc = async (data) => new Promise((res, rej) => {
133
- convertClient.htmlToDoc(data, (err, data1) => {
134
- if (err) {
135
- logger.file('grpc/convert', { error: err.toString(), stack: err.stack, ready: config.ready.convert });
136
- if (!config.ready.convert) {
137
- return rej(new Error('no grpc convert connection'));
138
- }
139
- return rej(err);
140
- }
141
- res(data1);
142
- });
143
- });
144
-
145
- const htmlToImg = async (data) => new Promise((res, rej) => {
146
- convertClient.htmlToImage(data, (err, data1) => {
147
- if (err) {
148
- logger.file('grpc/convert', { error: err.toString(), stack: err.stack, ready: config.ready.convert });
149
- if (!config.ready.convert) {
150
- return rej(new Error('no grpc convert connection'));
151
- }
152
- return rej(err);
153
- }
154
- res(data1);
155
- });
156
- });
157
-
158
- const shpToGeojson = async (data) => new Promise((res, rej) => {
159
- convertClient.shpToGeojson(data, (err, data1) => {
160
- if (err) {
161
- logger.file('grpc/convert', { error: err.toString(), stack: err.stack, ready: config.ready.convert });
162
- if (!config.ready.convert) {
163
- return rej(new Error('no grpc convert connection'));
164
- }
165
- return rej(err);
166
- }
167
- res(data1);
168
- });
169
- });
170
-
171
- const geojsonToShp = async (data) => new Promise((res, rej) => {
172
- convertClient.geojsonToShp(data, (err, data1) => {
173
- if (err) {
174
- logger.file('grpc/convert', { error: err.toString(), stack: err.stack, ready: config.ready.convert });
175
- if (!config.ready.convert) {
176
- return rej(new Error('no grpc convert connection'));
177
- }
178
- return rej(err);
179
- }
180
- res(data1);
181
- });
182
- });
183
-
184
- const geojsonToGpkg = async (data) => new Promise((res, rej) => {
185
- convertClient.geojsonToGpkg(data, (err, data1) => {
186
- if (err) {
187
- logger.file('grpc/convert', { error: err.toString(), stack: err.stack, ready: config.ready.convert });
188
- if (!config.ready.convert) {
189
- return rej(new Error('no grpc convert connection'));
190
- }
191
- return rej(err);
192
- }
193
- res(data1);
194
- });
195
- });
196
-
197
- const docToPDF = async (data) => new Promise((res, rej) => {
198
- convertClient.docToPDF(data, (err, data1) => {
199
- if (err) {
200
- logger.file('grpc/convert', { error: err.toString(), stack: err.stack, ready: config.ready.convert });
201
- if (!config.ready.convert) {
202
- return rej(new Error('no grpc convert connection'));
203
- }
204
- return rej(err);
205
- }
206
- res(data1);
207
- });
208
- });
209
-
210
- const mergeImages = async (data) => new Promise((res, rej) => {
211
- convertClient.mergeImages(data, (err, data1) => {
91
+ convertClient[methodName](data, (err, response) => {
212
92
  if (err) {
213
- logger.file('grpc/convert', { error: err.toString(), stack: err.stack, ready: config.ready.convert });
214
- if (!config.ready.convert) {
215
- return rej(new Error('no grpc convert connection'));
216
- }
217
- return rej(err);
218
- }
219
- res(data1);
220
- });
221
- });
93
+ logger.file('grpc/convert', {
94
+ method: methodName,
95
+ error: err.toString(),
96
+ stack: err.stack,
97
+ ready: config.ready.convert,
98
+ });
222
99
 
223
- const resizeImage = async (data) => new Promise((res, rej) => {
224
- convertClient.resizeImage(data, (err, data1) => {
225
- if (err) {
226
- logger.file('grpc/convert', { error: err.toString(), stack: err.stack, ready: config.ready.convert });
227
100
  if (!config.ready.convert) {
228
101
  return rej(new Error('no grpc convert connection'));
229
102
  }
230
- return rej(err);
231
- }
232
- res(data1);
233
- });
234
- });
235
103
 
236
- const jsonToYaml = async (data) => new Promise((res, rej) => {
237
- convertClient.jsonToYaml(data, (err, data1) => {
238
- if (err) {
239
- logger.file('grpc/convert', { error: err.toString(), stack: err.stack, ready: config.ready.convert });
240
- if (!config.ready.convert) {
241
- return rej(new Error('no grpc convert connection'));
242
- }
243
104
  return rej(err);
244
105
  }
245
- res(data1);
246
- });
247
- });
248
106
 
249
- const yamlToJson = async (data) => new Promise((res, rej) => {
250
- convertClient.yamlToJson(data, (err, data1) => {
251
- if (err) {
252
- logger.file('grpc/convert', { error: err.toString(), stack: err.stack, ready: config.ready.convert });
253
- if (!config.ready.convert) {
254
- return rej(new Error('no grpc convert connection'));
255
- }
256
- return rej(err);
257
- }
258
- res(data1);
107
+ return res(response);
259
108
  });
260
109
  });
261
110
 
262
- const log = async (data) => new Promise((res, rej) => {
263
- convertClient.log(data, (err, data1) => {
264
- if (err) {
265
- logger.file('grpc/convert', { error: err.toString(), stack: err.stack, ready: config.ready.convert });
266
- if (!config.ready.convert) {
267
- return rej(new Error('no grpc convert connection'));
268
- }
269
- return rej(err);
270
- }
271
- res(data1);
272
- });
273
- });
111
+ const grpcMethods = methodNames.reduce((acc, name) => {
112
+ acc[name] = wrapGrpcCall(name);
113
+ return acc;
114
+ }, {});
274
115
 
275
116
  const getGRPC = () => ({
276
- pdfMerge,
277
- htmlToPdf,
278
- csvToXls,
279
- jsonToXls,
280
- excelToJson,
281
- xmlToJson,
282
- html2Doc,
283
- htmlToImg,
284
- shpToGeojson,
285
- geojsonToShp,
286
- geojsonToGpkg,
287
- docToPDF,
288
- mergeImages,
289
- resizeImage,
290
- jsonToYaml,
291
- yamlToJson,
292
- log,
117
+ ...grpcMethods,
293
118
  convertServerAddress,
294
119
  });
295
120
 
@@ -1,24 +1,33 @@
1
- /* eslint-disable consistent-return */
1
+ import path from 'node:path';
2
+ import { fileURLToPath } from 'url';
3
+
2
4
  import grpc from '@grpc/grpc-js';
3
5
  import protoLoader from '@grpc/proto-loader';
4
6
 
5
7
  import config from '../../../config.js';
6
8
  import logger from '../logger/getLogger.js';
7
9
 
10
+ const filename = fileURLToPath(import.meta.url);
11
+ const dirname = path.dirname(filename);
12
+
8
13
  config.ready = config.ready || {};
9
14
 
10
15
  // external ip not-accessible from internal network
11
- const defaultOfficeConverterServerAddress = config.pg?.host?.startsWith('192.168.3') ? '192.168.1.96:4011' : '193.239.152.181:44011';
16
+ const defaultOfficeConverterServerAddress = config.pg?.host?.startsWith?.('192.168.3')
17
+ ? '192.168.1.96:4011'
18
+ : '193.239.152.181:44011';
12
19
 
13
- const officeConverterServerAddress = config.officeConverterServerAddress || defaultOfficeConverterServerAddress;
20
+ const officeConverterServerAddress = config.officeConverterServerAddress === true
21
+ ? defaultOfficeConverterServerAddress
22
+ : config.officeConverterServerAddress;
14
23
 
15
24
  console.log('officeConverterServerAddress: ', officeConverterServerAddress, !!config.officeConverterServerAddress);
16
25
 
17
- const relpath = 'server/plugins/grpc/utils/office2pdf.proto';
18
- const protoLocation = process.cwd().includes('fastify-table') ? relpath : `node_modules/@opengis/fastify-table/${relpath}`;
26
+ // const relpath = 'server/plugins/grpc/utils/office2pdf.proto';
27
+ // const protoLocation = process.cwd().includes('fastify-table') ? relpath : `node_modules/@opengis/fastify-table/${relpath}`;
19
28
 
20
29
  const proto = grpc.loadPackageDefinition(
21
- protoLoader.loadSync(protoLocation, {
30
+ protoLoader.loadSync(`${dirname}/utils/office2pdf.proto`, {
22
31
  keepCase: true,
23
32
  longs: String,
24
33
  enums: String,
@@ -27,28 +36,38 @@ const proto = grpc.loadPackageDefinition(
27
36
  }),
28
37
  );
29
38
 
30
- const officeClient = new proto.OfficeConverterService(
39
+ const officeClient = officeConverterServerAddress ? new proto.OfficeConverterService(
31
40
  officeConverterServerAddress,
32
41
  grpc.credentials.createInsecure(),
33
42
  {
34
43
  'grpc.max_send_message_length': 512 * 1024 * 1024,
35
44
  'grpc.max_receive_message_length': 512 * 1024 * 1024,
36
45
  },
37
- );
46
+ ) : {};
38
47
 
39
- officeClient.waitForReady(Date.now() + 5000, (err) => {
40
- if (err) {
41
- config.ready.office2pdf = false;
42
- console.error('Client connection timeout or failure:', err);
43
- }
44
- else {
45
- config.ready.office2pdf = true;
46
- console.log('Client connected successfully.');
47
- // You can now make RPC calls safely
48
- }
49
- });
48
+ if (officeConverterServerAddress) {
49
+ officeClient.waitForReady(Date.now() + 5000, (err) => {
50
+ if (err) {
51
+ config.ready.office2pdf = false;
52
+ console.error('Client connection timeout or failure:', err);
53
+ }
54
+ else {
55
+ config.ready.office2pdf = true;
56
+ console.log('Client connected successfully.');
57
+ // You can now make RPC calls safely
58
+ }
59
+ });
60
+ }
50
61
 
51
62
  const officeToPdf = async (data) => new Promise((res, rej) => {
63
+ if (!officeConverterServerAddress) {
64
+ logger.file('grpc/convert', {
65
+ method: 'officeToPdf',
66
+ error: 'grpc office2pdf not set',
67
+ stack: new Error().stack,
68
+ });
69
+ return rej(new Error('grpc office2pdf not set'));
70
+ }
52
71
  officeClient.OfficeToPdf(data, (err, data1) => {
53
72
  if (err) {
54
73
  logger.file('grpc/office2pdf', { error: err.toString(), stack: err.stack, ready: config.ready.office2pdf });
@@ -3,6 +3,12 @@ import logger from './getLogger.js';
3
3
  import pgClients from '../pg/pgClients.js';
4
4
 
5
5
  async function plugin(fastify) {
6
+ fastify.addHook('onResponse', async (req, reply) => {
7
+ if (reply?.statusCode && reply.statusCode >= 400) {
8
+ logger.metrics(`error-count:${reply.statusCode}`);
9
+ }
10
+ });
11
+
6
12
  fastify.setErrorHandler(async (error, request, reply) => {
7
13
  // validation not error
8
14
  if (error.validation) {
@@ -19,6 +25,7 @@ async function plugin(fastify) {
19
25
 
20
26
  return reply.status(error.statusCode || 500).send(msg);
21
27
  });
28
+
22
29
  fastify.addHook('onListen', async () => {
23
30
  logger.file('init', { db: pgClients.client?.options?.database });
24
31
  });
@@ -7,33 +7,57 @@ import pgClients from '../pg/pgClients.js';
7
7
  // import getCallerDir from './get.caller.dir.js';
8
8
 
9
9
  const time = Date.now();
10
+ const debug = config.debug || config.local;
10
11
 
11
12
  export default async function execMigrations(dirPath, pg = pgClients.client, iscore = false) {
12
- if (
13
- !dirPath
14
- || (config.migrationsCore === false && iscore)
15
- || config.migrations === false
16
- || process.env.NODE_ENV === 'unit test'
17
- ) {
18
- console.log('migrations skip', 'core: ', !!iscore, 'dir: ', dirPath || 'not specified');
19
- return;
13
+ if (!dirPath) {
14
+ const txt = 'migrations skip: path not specified';
15
+ if (debug) console.warn(txt);
16
+ return txt;
20
17
  }
21
18
 
22
- console.log('migrations start', dirPath, Date.now() - time);
19
+ if (config.migrationsCore === false && iscore) {
20
+ const txt = `migrations skip: core - ${dirPath}`;
21
+ if (debug) console.log(txt);
22
+ return txt;
23
+ }
24
+
25
+ if (config.migrations === false && !iscore) {
26
+ const txt = `migrations skip: path - ${dirPath}`;
27
+ if (debug) console.log(txt);
28
+ return txt;
29
+ }
30
+
31
+ if (process.env.NODE_ENV !== 'production' && (!config.migrations || !(config.migrationsCore && iscore))) {
32
+ const txt = `migrations skip: not a production environment - ${iscore ? 'core' : 'path'} : ${dirPath}`;
33
+ if (debug) console.log(txt);
34
+ return txt;
35
+ }
36
+
37
+ if (debug) console.log('migrations start', dirPath, Date.now() - time);
23
38
 
24
39
  const exists = existsSync(dirPath);
25
40
 
26
- if (exists) {
27
- // get directory sql file list
28
- const content = readdirSync(dirPath, { withFileTypes: true })
29
- ?.filter((el) => el.isFile() && path.extname(el.name) === '.sql')
30
- ?.map((el) => el.name) || [];
41
+ if (!exists) {
42
+ const txt = `migrations skip: directory not found - ${dirPath}`;
43
+ if (debug) console.warn(txt);
44
+ return txt;
45
+ }
46
+
47
+ // get directory sql file list
48
+ const content = readdirSync(dirPath, { withFileTypes: true })
49
+ ?.filter((el) => el.isFile() && path.extname(el.name) === '.sql')
50
+ ?.map((el) => el.name) || [];
31
51
 
32
- // execute sql files
33
- if (content?.length) {
34
- await content.reduce((promise, filename) => promise.then(() => execSql(path.join(dirPath, filename), pg)), Promise.resolve());
35
- }
52
+ // execute sql files
53
+ if (!content?.length) {
54
+ const txt = `migrations skip: no sql in specified directory - ${dirPath}`;
55
+ if (debug) console.warn(txt);
56
+ return txt;
36
57
  }
37
58
 
38
- console.log('migrations finish', dirPath, exists, Date.now() - time);
59
+ await content.reduce((promise, filename) => promise.then(() => execSql(path.join(dirPath, filename), pg)), Promise.resolve());
60
+ if (debug) console.log('migrations success', dirPath, exists, Date.now() - time);
61
+
62
+ return 'success';
39
63
  }
@@ -12,6 +12,8 @@ import getRedis from '../redis/funcs/getRedis.js';
12
12
 
13
13
  const rclient = getRedis();
14
14
 
15
+ const debug = config.debug || config.local;
16
+
15
17
  export default async function execSql(filepath, pg = pgClients.client) {
16
18
  const start = Date.now();
17
19
 
@@ -33,16 +35,16 @@ export default async function execSql(filepath, pg = pgClients.client) {
33
35
  const hash = createHash('md5').update(sql).digest('hex');
34
36
  const hashes = config.redis ? await rclient.hgetall(`${pg?.options?.database}:migration-hashes`).then(obj => Object.keys(obj)) : [];
35
37
 
36
- if (hashes.includes(hash) && !config.disableCache) {
38
+ if (hashes.includes(hash) && !config.disableCache && debug) {
37
39
  console.log(filename, 'skip equal hash', Date.now() - start);
38
40
  return null;
39
41
  }
40
42
 
41
43
  try {
42
- console.log(filename, 'start', Date.now() - start);
44
+ if (debug) console.log(filename, 'start', Date.now() - start);
43
45
  await pg.query(sql);
44
46
  if (!config.disableCache && config.redis) await rclient.hset(`${pg?.options?.database}:migration-hashes`, hash, 1);
45
- console.log(filename, 'finish', Date.now() - start);
47
+ if (debug) console.log(filename, 'finish', Date.now() - start);
46
48
  logger.file('migration/success', {
47
49
  filepath,
48
50
  result: 'success',
@@ -51,7 +53,7 @@ export default async function execSql(filepath, pg = pgClients.client) {
51
53
  return 'ok';
52
54
  }
53
55
  catch (err) {
54
- console.log(filename, 'error', err.toString(), Date.now() - start);
56
+ console.error(filename, 'error', err.toString(), Date.now() - start);
55
57
  logger.file('migration/error', {
56
58
  filepath,
57
59
  result: 'error',
@@ -109,6 +109,7 @@ async function init(client) {
109
109
  Object.assign(client, {
110
110
  one, pgType, pk, tlist, relkinds, queryCache, queryNotice, querySafe,
111
111
  });
112
+ console.log('db connected', client.options?.database);
112
113
  }
113
114
 
114
115
  // export default client;
@@ -17,7 +17,7 @@ function getRedis({ db } = { db: 0 }) {
17
17
  };
18
18
 
19
19
  redisClients[db] = new Redis(redisConfig);
20
-
20
+ console.log('redis connected', db);
21
21
  return redisClients[db];
22
22
  }
23
23
 
@@ -0,0 +1,32 @@
1
+ import Database from 'better-sqlite3';
2
+
3
+ import config from '../../../../config.js';
4
+ import sqliteClients from '../sqliteClients.js';
5
+ import init from './init.js';
6
+
7
+ function getSqliteAsync({
8
+ name,
9
+ readonly = false,
10
+ fileMustExist = false,
11
+ statement_timeout: timeout = 10000,
12
+ } = {}) {
13
+ if (!config.sqlite) return null;
14
+
15
+ if (sqliteClients.client?.tlist) {
16
+ return sqliteClients.client;
17
+ }
18
+
19
+ const dbConfig = {
20
+ readonly,
21
+ fileMustExist,
22
+ timeout,
23
+ verbose: config.trace ? console.log : undefined,
24
+ };
25
+
26
+ sqliteClients.client = new Database(name || ':memory:', dbConfig);
27
+ init(sqliteClients.client);
28
+
29
+ return sqliteClients.client;
30
+ }
31
+
32
+ export default getSqliteAsync;
@@ -0,0 +1,51 @@
1
+ function init(client) {
2
+ if (!client) { return; }
3
+
4
+ const rows = client.prepare(`WITH tables AS (
5
+ SELECT name AS table_name
6
+ FROM sqlite_master
7
+ WHERE type = 'table' AND name NOT LIKE 'sqlite_%'
8
+ ),
9
+ pk_columns AS (
10
+ SELECT
11
+ m.name AS table_name,
12
+ ti.name AS column_name,
13
+ ti.pk
14
+ FROM sqlite_master m
15
+ JOIN pragma_table_info(m.name) AS ti
16
+ WHERE ti.pk = 1
17
+ )
18
+ SELECT table_name, column_name
19
+ FROM pk_columns
20
+ WHERE table_name IN (
21
+ SELECT table_name
22
+ FROM pk_columns
23
+ GROUP BY table_name
24
+ HAVING COUNT(*) = 1
25
+ )
26
+ ORDER BY table_name;`).all();
27
+
28
+ const pk = Object.fromEntries(
29
+ rows.map(row => [row.table_name, row.column_name]),
30
+ );
31
+
32
+ const tlist = client.prepare('SELECT name FROM sqlite_master WHERE type=\'table\' AND name NOT LIKE \'sqlite_%\';').all().reduce((acc, curr) => {
33
+ acc.push(curr.name);
34
+ return acc;
35
+ }, []);
36
+
37
+ async function query(q, args = []) {
38
+ const data = client.prepare(q.replace(/\$\d+/g, '?')).all(...args);
39
+ return Promise.resolve({ rows: data, rowCount: data.length });
40
+ }
41
+
42
+ Object.assign(client, {
43
+ query,
44
+ pk,
45
+ tlist,
46
+ });
47
+
48
+ console.log('db connected', client.name || ':memory:');
49
+ }
50
+
51
+ export default init;
@@ -0,0 +1,11 @@
1
+ import fp from 'fastify-plugin';
2
+
3
+ import sqliteClients from './sqliteClients.js';
4
+
5
+ async function dbPlugin(app, opts) {
6
+ app.addHook('onClose', async () => {
7
+ Object.keys(sqliteClients).forEach(key => sqliteClients[key].close());
8
+ });
9
+ }
10
+
11
+ export default fp(dbPlugin);
@@ -0,0 +1,19 @@
1
+ import Database from 'better-sqlite3';
2
+
3
+ import config from '../../../config.js';
4
+ import init from './funcs/init.js';
5
+
6
+ const sqliteClients = {};
7
+
8
+ if (config.sqlite) {
9
+ const client = new Database(config.sqlite?.name || ':memory:', {
10
+ readonly: config.sqlite?.readonly || false,
11
+ fileMustExist: config.sqlite?.fileMustExist || false,
12
+ timeout: config.sqlite?.statement_timeout || 10000,
13
+ verbose: config.trace ? console.log : undefined,
14
+ });
15
+ client.init = () => init(client);
16
+ client.init();
17
+ sqliteClients.client = client;
18
+ }
19
+ export default sqliteClients;
@@ -14,8 +14,11 @@ export default function unflattenObject(flatObj) {
14
14
  nestedObj[part] = flatObj[key]; // fallback to original value if parsing fails
15
15
  }
16
16
  }
17
+ else if (['true', 'false'].includes(flatObj[key]) || !isNaN(flatObj[key])) {
18
+ nestedObj[part] = JSON.parse(flatObj[key]);
19
+ }
17
20
  else {
18
- nestedObj[part] = ['true', 'false'].includes(flatObj[key]) ? JSON.parse(flatObj[key]) : flatObj[key];
21
+ nestedObj[part] = flatObj[key];
19
22
  }
20
23
  }
21
24
  else {
@@ -16,7 +16,7 @@ const loggerSchema = {
16
16
  };
17
17
 
18
18
  async function plugin(app) {
19
- app.get('/logger-file/*', { config: { policy: ['public'] }, schema: loggerSchema }, loggerFile);
19
+ app.get('/logger-file/*', { config: { policy: ['public'], rateLimit: false }, schema: loggerSchema }, loggerFile);
20
20
  }
21
21
 
22
22
  export default plugin;
@@ -27,7 +27,16 @@ async function plugin(app, config = {}) {
27
27
  app.get(`${prefix}/table-filter/:table`, { config: { policy }, schema: filterSchema }, filter);
28
28
 
29
29
  app.get(`${prefix}/table-info/:table/:id?`, { config: { policy }, schema: tableDataSchema }, tableInfo);
30
- app.get(`${prefix}/suggest/:data`, { config: { policy }, schema: suggestSchema }, suggest);
30
+ app.get(`${prefix}/suggest/:data`, {
31
+ config: {
32
+ policy,
33
+ rateLimit: {
34
+ max: 10000,
35
+ timeWindow: '1 minute',
36
+ },
37
+ },
38
+ schema: suggestSchema,
39
+ }, suggest);
31
40
  app.get(`${prefix}/data/:table/:id?`, { config: { policy: ['public', 'no-sql'] }, schema: tableSchema }, data);
32
41
  app.get(`${prefix}/table-data/:table`, { config: { policy: ['user', 'no-sql'] }, schema: tableDataSchema }, data);
33
42
  app.get(`${prefix}/table-data/:table/:id`, { config: { policy }, schema: tableDataIdSchema }, cardData);
package/utils.js CHANGED
@@ -7,6 +7,9 @@ import { handlebars, handlebarsSync } from './server/helpers/index.js';
7
7
  // pg
8
8
  import getPG from './server/plugins/pg/funcs/getPG.js';
9
9
  import getPGAsync from './server/plugins/pg/funcs/getPGAsync.js';
10
+ import getSqlite from './server/plugins/sqlite/funcs/getSqlite.js';
11
+ import initSqlite from './server/plugins/sqlite/funcs/init.js';
12
+ import sqliteClients from './server/plugins/sqlite/sqliteClients.js';
10
13
  import getDBParams from './server/plugins/pg/funcs/getDBParams.js';
11
14
  import initPG from './server/plugins/pg/funcs/init.js';
12
15
  import pgClients from './server/plugins/pg/pgClients.js';
@@ -170,6 +173,11 @@ export {
170
173
  pgClients,
171
174
  getDBParams,
172
175
 
176
+ // sqlite
177
+ getSqlite,
178
+ initSqlite,
179
+ sqliteClients,
180
+
173
181
  // select
174
182
  getSelectVal,
175
183
  getSelectMeta,