@opengis/fastify-table 1.0.27 → 1.0.28

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.
Files changed (36) hide show
  1. package/.eslintrc.cjs +42 -42
  2. package/Changelog.md +89 -81
  3. package/README.md +26 -26
  4. package/config.js +11 -11
  5. package/crud/controllers/deleteCrud.js +14 -14
  6. package/crud/controllers/utils/checkXSS.js +45 -45
  7. package/crud/controllers/utils/xssInjection.js +72 -72
  8. package/crud/funcs/dataDelete.js +15 -15
  9. package/crud/funcs/dataInsert.js +24 -24
  10. package/crud/funcs/dataUpdate.js +24 -24
  11. package/crud/funcs/getToken.js +27 -27
  12. package/crud/funcs/isFileExists.js +13 -13
  13. package/crud/funcs/setToken.js +53 -53
  14. package/dblist/controllers/createItem.js +19 -4
  15. package/dblist/controllers/deleteItem.js +4 -2
  16. package/dblist/controllers/readItems.js +5 -3
  17. package/dblist/controllers/setItem.js +21 -0
  18. package/dblist/controllers/updateItem.js +6 -3
  19. package/dblist/controllers/utils/checkItem.js +17 -2
  20. package/dblist/controllers/utils/formatData.js +7 -0
  21. package/dblist/index.js +9 -0
  22. package/package.json +22 -22
  23. package/pg/funcs/getPG.js +29 -29
  24. package/redis/funcs/getRedis.js +23 -23
  25. package/server.js +14 -14
  26. package/table/controllers/search.js +41 -41
  27. package/table/funcs/getFilterSQL/util/getTableSql.js +34 -34
  28. package/test/config.example +18 -18
  29. package/test/funcs/crud.test.js +76 -76
  30. package/test/funcs/pg.test.js +34 -34
  31. package/test/funcs/redis.test.js +19 -19
  32. package/test/templates/cls/test.json +9 -9
  33. package/test/templates/form/cp_building.form.json +32 -32
  34. package/test/templates/select/account_id.json +3 -3
  35. package/test/templates/select/storage.data.json +2 -2
  36. package/test/templates/table/gis.dataset.table.json +20 -20
@@ -1,24 +1,24 @@
1
- import getPG from '../../pg/funcs/getPG.js';
2
- import getMeta from '../../pg/funcs/getMeta.js';
3
-
4
- export default async function dataInsert({ table, data }) {
5
- const pg = getPG({ name: 'client' });
6
- if (!data) return null;
7
- const { columns } = await getMeta(table);
8
- if (!columns) return null;
9
-
10
- const names = columns.map((el) => el.name);
11
- const filterData = Object.keys(data)
12
- .filter((el) => data[el] && names.includes(el)).map((el) => [el, data[el]]);
13
-
14
- const insertQuery = `insert into ${table}
15
-
16
- ( ${filterData?.map((key) => `"${key[0]}"`).join(',')})
17
-
18
- values (${filterData?.map((key, i) => `$${i + 1}`).join(',')})
19
-
20
- returning *`;
21
-
22
- const res = await pg.query(insertQuery, [...filterData.map((el) => (typeof el[1] === 'object' && (!Array.isArray(el[1]) || typeof el[1]?.[0] === 'object') ? JSON.stringify(el[1]) : el[1]))]) || {};
23
- return res;
24
- }
1
+ import getPG from '../../pg/funcs/getPG.js';
2
+ import getMeta from '../../pg/funcs/getMeta.js';
3
+
4
+ export default async function dataInsert({ table, data }) {
5
+ const pg = getPG({ name: 'client' });
6
+ if (!data) return null;
7
+ const { columns } = await getMeta(table);
8
+ if (!columns) return null;
9
+
10
+ const names = columns.map((el) => el.name);
11
+ const filterData = Object.keys(data)
12
+ .filter((el) => data[el] && names.includes(el)).map((el) => [el, data[el]]);
13
+
14
+ const insertQuery = `insert into ${table}
15
+
16
+ ( ${filterData?.map((key) => `"${key[0]}"`).join(',')})
17
+
18
+ values (${filterData?.map((key, i) => `$${i + 1}`).join(',')})
19
+
20
+ returning *`;
21
+
22
+ const res = await pg.query(insertQuery, [...filterData.map((el) => (typeof el[1] === 'object' && (!Array.isArray(el[1]) || typeof el[1]?.[0] === 'object') ? JSON.stringify(el[1]) : el[1]))]) || {};
23
+ return res;
24
+ }
@@ -1,24 +1,24 @@
1
- import getPG from '../../pg/funcs/getPG.js';
2
-
3
- import getMeta from '../../pg/funcs/getMeta.js';
4
-
5
- export default async function dataUpdate({
6
- table, id, data,
7
- }) {
8
- if (!data || !table || !id) return null;
9
-
10
- const pg = getPG({ name: 'client' });
11
- const { columns, pk } = await getMeta(table);
12
-
13
- const names = columns?.map((el) => el.name);
14
- const filterData = Object.keys(data)
15
- .filter((el) => data[el] && names?.includes(el));
16
-
17
- const filterValue = filterData.map((el) => [el, data[el]]).map((el) => (typeof el[1] === 'object' && (!Array.isArray(el[1]) || typeof el[1]?.[0] === 'object') ? JSON.stringify(el[1]) : el[1]));
18
-
19
- const updateQuery = `UPDATE ${table} SET ${filterData?.map((key, i) => `"${key}"=$${i + 2}`).join(',')}
20
- WHERE ${pk} = $1 returning *`;
21
- // console.log(updateDataset);
22
- const res = await pg.query(updateQuery, [id, ...filterValue]).then(el => el?.rows?.[0]) || {};
23
- return res;
24
- }
1
+ import getPG from '../../pg/funcs/getPG.js';
2
+
3
+ import getMeta from '../../pg/funcs/getMeta.js';
4
+
5
+ export default async function dataUpdate({
6
+ table, id, data,
7
+ }) {
8
+ if (!data || !table || !id) return null;
9
+
10
+ const pg = getPG({ name: 'client' });
11
+ const { columns, pk } = await getMeta(table);
12
+
13
+ const names = columns?.map((el) => el.name);
14
+ const filterData = Object.keys(data)
15
+ .filter((el) => data[el] && names?.includes(el));
16
+
17
+ const filterValue = filterData.map((el) => [el, data[el]]).map((el) => (typeof el[1] === 'object' && (!Array.isArray(el[1]) || typeof el[1]?.[0] === 'object') ? JSON.stringify(el[1]) : el[1]));
18
+
19
+ const updateQuery = `UPDATE ${table} SET ${filterData?.map((key, i) => `"${key}"=$${i + 2}`).join(',')}
20
+ WHERE ${pk} = $1 returning *`;
21
+ // console.log(updateDataset);
22
+ const res = await pg.query(updateQuery, [id, ...filterValue]).then(el => el?.rows?.[0]) || {};
23
+ return res;
24
+ }
@@ -1,27 +1,27 @@
1
- import getRedis from '../../redis/funcs/getRedis.js';
2
- import config from '../../config.js';
3
-
4
- function sprintf(str, ...args) {
5
- return str.replace(/%s/g, () => args.shift());
6
- }
7
-
8
- const keys = {
9
- r: '%s:token:view:%s',
10
- a: '%s:token:add:%s',
11
- w: '%s:token:edit:%s',
12
- e: '%s:token:exec:%s',
13
- };
14
-
15
- async function getIdByToken({
16
- uid, token, mode = 'r', json,
17
- }) {
18
- if (mode === 'r') return token;
19
-
20
- const rclient = getRedis({ db: 0 });
21
-
22
- const key = sprintf(keys[mode], config?.pg?.database, uid?.toString());
23
- const id = await rclient.hget(key, token);
24
- return json && id[0] === '{' ? JSON.parse(id) : id;
25
- }
26
-
27
- export default getIdByToken;
1
+ import getRedis from '../../redis/funcs/getRedis.js';
2
+ import config from '../../config.js';
3
+
4
+ function sprintf(str, ...args) {
5
+ return str.replace(/%s/g, () => args.shift());
6
+ }
7
+
8
+ const keys = {
9
+ r: '%s:token:view:%s',
10
+ a: '%s:token:add:%s',
11
+ w: '%s:token:edit:%s',
12
+ e: '%s:token:exec:%s',
13
+ };
14
+
15
+ async function getIdByToken({
16
+ uid, token, mode = 'r', json,
17
+ }) {
18
+ if (mode === 'r') return token;
19
+
20
+ const rclient = getRedis({ db: 0 });
21
+
22
+ const key = sprintf(keys[mode], config?.pg?.database, uid?.toString());
23
+ const id = await rclient.hget(key, token);
24
+ return json && id[0] === '{' ? JSON.parse(id) : id;
25
+ }
26
+
27
+ export default getIdByToken;
@@ -1,13 +1,13 @@
1
- import { access } from 'fs/promises';
2
-
3
- const isFileExists = async (filepath) => {
4
- try {
5
- await access(filepath);
6
- return true;
7
- }
8
- catch (err) {
9
- return false;
10
- }
11
- };
12
-
13
- export default isFileExists;
1
+ import { access } from 'fs/promises';
2
+
3
+ const isFileExists = async (filepath) => {
4
+ try {
5
+ await access(filepath);
6
+ return true;
7
+ }
8
+ catch (err) {
9
+ return false;
10
+ }
11
+ };
12
+
13
+ export default isFileExists;
@@ -1,53 +1,53 @@
1
- import { createHash, randomUUID } from 'crypto';
2
-
3
- import config from '../../config.js';
4
- import getRedis from '../../redis/funcs/getRedis.js';
5
-
6
- const generateCodes = (ids, userToken) => {
7
- const token = userToken || randomUUID();
8
- const notNullIds = ids.filter((el) => el);
9
- const obj = {};
10
- const codes = notNullIds.reduce((acc, id) => {
11
- const newToken = createHash('sha1').update(token + id).digest('base64url').replace(/-/g, '');
12
- acc[newToken] = id; obj[id] = newToken;
13
- return acc;
14
- }, {});
15
- return { codes, obj };
16
- };
17
-
18
- function setToken({
19
- ids: idsOrigin, mode = 'r', uid, referer, array,
20
- }) {
21
- const rclient2 = getRedis({ db: 0 });
22
- // const rclient5 = getRedis({ db: 0, funcs });
23
-
24
- if (!uid) return { user: 'empty' };
25
- if (!Object.keys(idsOrigin).length) return { ids: 'empty' };
26
-
27
- const ids = idsOrigin.map((el) => (typeof el === 'object' ? JSON.stringify(el) : el));
28
- // update/delete
29
-
30
- if (mode === 'r') return null;
31
-
32
- // TODO generate salt
33
- const { codes, obj } = generateCodes(ids, uid);
34
-
35
- if (!Object.keys(codes).length) return { ids: 'empty' };
36
-
37
- rclient2.hmset(`${config.pg.database}:token:${{
38
- e: 'exec', r: 'view', w: 'edit', a: 'add',
39
- }[mode]}:${uid}`, codes);
40
-
41
- // log token for debug. add extra data - uid, mode, date
42
- /* const dt = new Date().toISOString();
43
- const codesLog = Object.keys(codes).reduce((acc, key) => {
44
- acc[key] = `{"referer": "${referer}" ,"uid":"${uid}","mode":"${mode}","date":"${dt}",${codes[key].substr(1)}`;
45
- return acc;
46
- }, {});
47
- rclient5.hmset(`${config.pg.database}:token:edit`, codesLog); // 'EX', 64800 */
48
-
49
- // TODO дополнительно писать в hset token -> uid
50
- return array ? Object.values(obj) : obj;
51
- }
52
-
53
- export default setToken;
1
+ import { createHash, randomUUID } from 'crypto';
2
+
3
+ import config from '../../config.js';
4
+ import getRedis from '../../redis/funcs/getRedis.js';
5
+
6
+ const generateCodes = (ids, userToken) => {
7
+ const token = userToken || randomUUID();
8
+ const notNullIds = ids.filter((el) => el);
9
+ const obj = {};
10
+ const codes = notNullIds.reduce((acc, id) => {
11
+ const newToken = createHash('sha1').update(token + id).digest('base64url').replace(/-/g, '');
12
+ acc[newToken] = id; obj[id] = newToken;
13
+ return acc;
14
+ }, {});
15
+ return { codes, obj };
16
+ };
17
+
18
+ function setToken({
19
+ ids: idsOrigin, mode = 'r', uid, referer, array,
20
+ }) {
21
+ const rclient2 = getRedis({ db: 0 });
22
+ // const rclient5 = getRedis({ db: 0, funcs });
23
+
24
+ if (!uid) return { user: 'empty' };
25
+ if (!Object.keys(idsOrigin).length) return { ids: 'empty' };
26
+
27
+ const ids = idsOrigin.map((el) => (typeof el === 'object' ? JSON.stringify(el) : el));
28
+ // update/delete
29
+
30
+ if (mode === 'r') return null;
31
+
32
+ // TODO generate salt
33
+ const { codes, obj } = generateCodes(ids, uid);
34
+
35
+ if (!Object.keys(codes).length) return { ids: 'empty' };
36
+
37
+ rclient2.hmset(`${config.pg.database}:token:${{
38
+ e: 'exec', r: 'view', w: 'edit', a: 'add',
39
+ }[mode]}:${uid}`, codes);
40
+
41
+ // log token for debug. add extra data - uid, mode, date
42
+ /* const dt = new Date().toISOString();
43
+ const codesLog = Object.keys(codes).reduce((acc, key) => {
44
+ acc[key] = `{"referer": "${referer}" ,"uid":"${uid}","mode":"${mode}","date":"${dt}",${codes[key].substr(1)}`;
45
+ return acc;
46
+ }, {});
47
+ rclient5.hmset(`${config.pg.database}:token:edit`, codesLog); // 'EX', 64800 */
48
+
49
+ // TODO дополнительно писать в hset token -> uid
50
+ return array ? Object.values(obj) : obj;
51
+ }
52
+
53
+ export default setToken;
@@ -3,15 +3,30 @@ import { existsSync } from 'fs';
3
3
  import { readFile, writeFile } from 'fs/promises';
4
4
 
5
5
  import checkItem from './utils/checkItem.js';
6
+ import formatData from './utils/formatData.js';
6
7
 
7
8
  export default async function insertItem({ body = {} }) {
8
- const check = checkItem(body.data);
9
+ const check = checkItem(body);
9
10
  if (check?.error) return check;
10
11
 
11
- Object.assign(body.data, { id: randomUUID() });
12
12
  const data = existsSync('dblist.json') ? JSON.parse(await readFile('dblist.json') || '[]') : [];
13
- data.push(body.data);
13
+ const {
14
+ key, name, database, host, port = 5432,
15
+ } = body;
16
+
17
+ const keys = data.map((el) => el.key);
18
+ if (keys.includes(key)) {
19
+ return { error: 'key duplication not allowed', status: 400 };
20
+ }
21
+ data.push({
22
+ id: randomUUID(),
23
+ key,
24
+ name,
25
+ database,
26
+ host,
27
+ port,
28
+ });
14
29
 
15
30
  await writeFile('dblist.json', JSON.stringify(data));
16
- return { data };
31
+ return { data: formatData(data) };
17
32
  }
@@ -1,12 +1,14 @@
1
1
  import { existsSync } from 'fs';
2
2
  import { readFile, writeFile } from 'fs/promises';
3
3
 
4
+ import formatData from './utils/formatData.js';
5
+
4
6
  export default async function deleteItem({ params = {} }) {
5
7
  const { id } = params;
6
8
  if (!id) return { error: 'not enough params', status: 400 };
7
9
  if (!existsSync('dblist.json')) return { data: [] };
8
10
  const data = JSON.parse(await readFile('dblist.json') || '[]');
9
11
 
10
- await writeFile('dblist.json', JSON.stringify(data.filter((el) => el.id !== id)));
11
- return { data };
12
+ await writeFile('dblist.json', JSON.stringify(data.filter((el) => el.key !== id && el.id !== id)));
13
+ return { data: formatData(data.filter((el) => el.key !== id && el.id !== id)) };
12
14
  }
@@ -1,8 +1,10 @@
1
1
  import { existsSync } from 'fs';
2
2
  import { readFile } from 'fs/promises';
3
3
 
4
+ import formatData from './utils/formatData.js';
5
+
4
6
  export default async function readItemList(req) {
5
- const data = existsSync('dblist.json') ? JSON.parse(await readFile('dblist.json') || '[]') : [];
6
- // const { user = {} } = req.session?.passport || {};
7
- return { data };
7
+ const filedata = existsSync('dblist.json') ? JSON.parse(await readFile('dblist.json') || '[]') : [];
8
+ const data = formatData(filedata);
9
+ return { current: req.session?.currentDB || data[0]?.id, data };
8
10
  }
@@ -0,0 +1,21 @@
1
+ import { existsSync } from 'fs';
2
+ import { readFile } from 'fs/promises';
3
+
4
+ export default async function setItem({
5
+ params = {}, session = {},
6
+ }) {
7
+ const { id } = params;
8
+ if (!id) return { error: 'not enough params', status: 400 };
9
+
10
+ if (!existsSync('dblist.json')) {
11
+ return { error: 'nothing to update: 1', status: 400 };
12
+ }
13
+
14
+ const data = JSON.parse(await readFile('dblist.json') || '[]');
15
+ const current = data.find((el) => [el.id, el.key].includes(id));
16
+ if (!current?.database) {
17
+ return { error: 'invalid param id', status: 400 };
18
+ }
19
+ Object.assign(session, { currentDB: id });
20
+ return { current: id };
21
+ }
@@ -2,6 +2,7 @@ import { existsSync } from 'fs';
2
2
  import { readFile, writeFile } from 'fs/promises';
3
3
 
4
4
  import checkItem from './utils/checkItem.js';
5
+ import formatData from './utils/formatData.js';
5
6
 
6
7
  export default async function updateItem({ body = {}, params = {} }) {
7
8
  const { id } = params;
@@ -11,12 +12,14 @@ export default async function updateItem({ body = {}, params = {} }) {
11
12
  return { error: 'nothing to update: 1', status: 400 };
12
13
  }
13
14
 
14
- const check = checkItem(body.data);
15
+ const check = checkItem(body);
15
16
  if (check?.error) return check;
16
17
 
17
18
  const data = JSON.parse(await readFile('dblist.json') || '[]');
18
- data.filter((el) => el.id === id)?.forEach((el) => Object.assign(el, body.data));
19
+ data.filter((el) => [el.id, el.key].includes(id))?.forEach((el) => {
20
+ ['key', 'name', 'database', 'host', 'port'].forEach((key) => Object.assign(el, { [key]: body[key] }));
21
+ });
19
22
 
20
23
  await writeFile('dblist.json', JSON.stringify(data));
21
- return { data };
24
+ return { data: formatData(data) };
22
25
  }
@@ -2,8 +2,23 @@ export default function validateItem(item) {
2
2
  if (!item || typeof item !== 'object' || Array.isArray(item)) {
3
3
  return { error: 'param data is invalid: 1', status: 400 };
4
4
  }
5
- if (!item.options?.database || Object.keys(item).filter((key) => !['key', 'name', 'options'].includes(key) || (typeof item[key] !== 'string' && key !== 'options')).length) {
6
- return { error: 'param data is invalid: 2', status: 400 };
5
+ const {
6
+ key, name, database, host, port,
7
+ } = item;
8
+ if (!key) {
9
+ return { error: 'param body.key is required', status: 400 };
10
+ }
11
+ if (!name) {
12
+ return { error: 'param body.name is required', status: 400 };
13
+ }
14
+ if (!database) {
15
+ return { error: 'param body.database is required', status: 400 };
16
+ }
17
+ if (!host) {
18
+ return { error: 'param body.host is required', status: 400 };
19
+ }
20
+ if (!port) {
21
+ return { error: 'param body.port is required', status: 400 };
7
22
  }
8
23
  return null;
9
24
  }
@@ -0,0 +1,7 @@
1
+ const showKeys = ['id', 'key', 'name'];
2
+
3
+ export default function formatData(data = []) {
4
+ return data?.length
5
+ ? data.map((el) => Object.keys(el).filter((key) => showKeys.includes(key)).reduce((acc, curr) => Object.assign(acc, { [curr]: el[curr] }), {}))
6
+ : [];
7
+ }
package/dblist/index.js CHANGED
@@ -2,6 +2,7 @@ import createItem from './controllers/createItem.js';
2
2
  import readItemList from './controllers/readItems.js';
3
3
  import updateItem from './controllers/updateItem.js';
4
4
  import deleteItem from './controllers/deleteItem.js';
5
+ import setItem from './controllers/setItem.js';
5
6
 
6
7
  export default async function plugin(fastify, config = {}) {
7
8
  const prefix = config.prefix || '/api';
@@ -37,4 +38,12 @@ export default async function plugin(fastify, config = {}) {
37
38
  },
38
39
  handler: deleteItem,
39
40
  });
41
+ fastify.route({
42
+ method: 'GET',
43
+ url: `${prefix}/list/:id`,
44
+ config: {
45
+ policy: [],
46
+ },
47
+ handler: setItem,
48
+ });
40
49
  }
package/package.json CHANGED
@@ -1,23 +1,23 @@
1
- {
2
- "name": "@opengis/fastify-table",
3
- "version": "1.0.27",
4
- "type": "module",
5
- "description": "core-plugins",
6
- "main": "index.js",
7
- "scripts": {
8
- "lint": "eslint . --ext .vue,.js,.jsx,.cjs,.mjs,.ts,.tsx,.cts,.mts --fix --ignore-path .gitignore",
9
- "test": "echo \"Error: no test specified\" && exit 1"
10
- },
11
- "dependencies": {
12
- "ioredis": "^5.3.2",
13
- "fastify": "^4.26.1",
14
- "fastify-plugin": "^4.0.0",
15
- "pg": "^8.11.3"
16
- },
17
- "devDependencies": {
18
- "eslint": "^8.49.0",
19
- "eslint-config-airbnb": "^19.0.4"
20
- },
21
- "author": "Softpro",
22
- "license": "ISC"
1
+ {
2
+ "name": "@opengis/fastify-table",
3
+ "version": "1.0.28",
4
+ "type": "module",
5
+ "description": "core-plugins",
6
+ "main": "index.js",
7
+ "scripts": {
8
+ "lint": "eslint . --ext .vue,.js,.jsx,.cjs,.mjs,.ts,.tsx,.cts,.mts --fix --ignore-path .gitignore",
9
+ "test": "echo \"Error: no test specified\" && exit 1"
10
+ },
11
+ "dependencies": {
12
+ "ioredis": "^5.3.2",
13
+ "fastify": "^4.26.1",
14
+ "fastify-plugin": "^4.0.0",
15
+ "pg": "^8.11.3"
16
+ },
17
+ "devDependencies": {
18
+ "eslint": "^8.49.0",
19
+ "eslint-config-airbnb": "^19.0.4"
20
+ },
21
+ "author": "Softpro",
22
+ "license": "ISC"
23
23
  }
package/pg/funcs/getPG.js CHANGED
@@ -1,29 +1,29 @@
1
- import pg from 'pg';
2
- import config from '../../config.js';
3
- import pgClients from '../pgClients.js';
4
- import init from './init.js';
5
-
6
- function getPG({
7
- user, password, host, port, db, database, name: origin, funcs,
8
- } = { name: 'client' }) {
9
- if (funcs?.config) Object.assign(config, { ...funcs.config }); // unit test
10
- const name = origin || db || database;
11
- if (pgClients[name]) return pgClients[name];
12
-
13
- const dbConfig = {
14
- user: user || config.pg?.user,
15
- password: password || config.pg?.password,
16
- host: host || config.pg?.host,
17
- port: port || config.pg?.port,
18
- database: db || database || config.pg?.db || config.pg?.database,
19
- };
20
-
21
- pgClients[name] = new pg.Pool(dbConfig);
22
- pgClients[name].init = async () => {
23
- await init(pgClients[name]);
24
- };
25
- init(pgClients[name]);
26
- return pgClients[name];
27
- }
28
-
29
- export default getPG;
1
+ import pg from 'pg';
2
+ import config from '../../config.js';
3
+ import pgClients from '../pgClients.js';
4
+ import init from './init.js';
5
+
6
+ function getPG({
7
+ user, password, host, port, db, database, name: origin, funcs,
8
+ } = { name: 'client' }) {
9
+ if (funcs?.config) Object.assign(config, { ...funcs.config }); // unit test
10
+ const name = origin || db || database;
11
+ if (pgClients[name]) return pgClients[name];
12
+
13
+ const dbConfig = {
14
+ user: user || config.pg?.user,
15
+ password: password || config.pg?.password,
16
+ host: host || config.pg?.host,
17
+ port: port || config.pg?.port,
18
+ database: db || database || config.pg?.db || config.pg?.database,
19
+ };
20
+
21
+ pgClients[name] = new pg.Pool(dbConfig);
22
+ pgClients[name].init = async () => {
23
+ await init(pgClients[name]);
24
+ };
25
+ init(pgClients[name]);
26
+ return pgClients[name];
27
+ }
28
+
29
+ export default getPG;
@@ -1,23 +1,23 @@
1
- import Redis from 'ioredis';
2
- import config from '../../config.js';
3
- import redisClients from './redisClients.js';
4
-
5
- function getRedis({ db } = { db: 0 }) {
6
- if (!config.redis) return null;
7
- if (redisClients[db]) return redisClients[db];
8
-
9
- const redisConfig = {
10
- db,
11
- keyPrefix: `${config.db}:`,
12
- host: config.redis?.host || '127.0.0.1',
13
- port: config.redis?.port || 6379, // Redis port
14
- family: 4, // 4 (IPv4) or 6 (IPv6)
15
- closeClient: true,
16
- };
17
-
18
- redisClients[db] = new Redis(redisConfig);
19
-
20
- return redisClients[db];
21
- }
22
-
23
- export default getRedis;
1
+ import Redis from 'ioredis';
2
+ import config from '../../config.js';
3
+ import redisClients from './redisClients.js';
4
+
5
+ function getRedis({ db } = { db: 0 }) {
6
+ if (!config.redis) return null;
7
+ if (redisClients[db]) return redisClients[db];
8
+
9
+ const redisConfig = {
10
+ db,
11
+ keyPrefix: `${config.db}:`,
12
+ host: config.redis?.host || '127.0.0.1',
13
+ port: config.redis?.port || 6379, // Redis port
14
+ family: 4, // 4 (IPv4) or 6 (IPv6)
15
+ closeClient: true,
16
+ };
17
+
18
+ redisClients[db] = new Redis(redisConfig);
19
+
20
+ return redisClients[db];
21
+ }
22
+
23
+ export default getRedis;
package/server.js CHANGED
@@ -1,14 +1,14 @@
1
- // This file contains code that we reuse
2
- // between our tests.
3
- import Fastify from 'fastify';
4
- import config from './test/config.js';
5
- import appService from './index.js';
6
-
7
- const app = Fastify({ logger: false });
8
- app.register(appService, config);
9
- app.listen({ host: '0.0.0.0', port: process.env.PORT || 3000 }, (err) => {
10
- if (err) {
11
- app.log.error(err);
12
- process.exit(1);
13
- }
14
- });
1
+ // This file contains code that we reuse
2
+ // between our tests.
3
+ import Fastify from 'fastify';
4
+ import config from './test/config.js';
5
+ import appService from './index.js';
6
+
7
+ const app = Fastify({ logger: false });
8
+ app.register(appService, config);
9
+ app.listen({ host: '0.0.0.0', port: process.env.PORT || 3000 }, (err) => {
10
+ if (err) {
11
+ app.log.error(err);
12
+ process.exit(1);
13
+ }
14
+ });