@nestjs-kitchen/connextion-postgres 1.0.0
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/LICENSE +21 -0
- package/README.md +179 -0
- package/dist/constants.d.ts +9 -0
- package/dist/constants.js +45 -0
- package/dist/define-postgres.d.ts +41 -0
- package/dist/define-postgres.js +63 -0
- package/dist/errors.d.ts +11 -0
- package/dist/errors.js +41 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.js +30 -0
- package/dist/postgres.instance.d.ts +29 -0
- package/dist/postgres.instance.js +213 -0
- package/dist/transaction.d.ts +6 -0
- package/dist/transaction.js +121 -0
- package/dist/types.d.ts +12 -0
- package/dist/types.js +15 -0
- package/dist/utils.d.ts +26 -0
- package/dist/utils.js +263 -0
- package/package.json +71 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 yikenman
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
# @nestjs-kitchen/connextion-postgres
|
|
2
|
+
|
|
3
|
+
[
|
|
4
|
+
](https://www.npmjs.com/package/@nestjs-kitchen/connextion-postgres)
|
|
5
|
+

|
|
6
|
+
[](https://codecov.io/gh/yikenman/nestjs-kitchen)
|
|
7
|
+
|
|
8
|
+
A flexible module to provide [node-postgres](https://node-postgres.com/) interface in NextJS.
|
|
9
|
+
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
## Install
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
$ npm install --save @nestjs-kitchen/connextion @nestjs-kitchen/connextion-postgres pg @types/pg
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
## Usage
|
|
19
|
+
|
|
20
|
+
### Apply `PostgresModule`
|
|
21
|
+
|
|
22
|
+
1. Export module, service & decorator.
|
|
23
|
+
|
|
24
|
+
```typescript
|
|
25
|
+
export const { Postgres, PostgresModule, Transaction } = definePostgres();
|
|
26
|
+
export type Postgres = InstanceType<typeof Postgres>;
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
2. Register postgres connection instance with options.
|
|
30
|
+
|
|
31
|
+
```typescript
|
|
32
|
+
@Module({
|
|
33
|
+
imports: [
|
|
34
|
+
// By default it will register a connection instance called `default`.
|
|
35
|
+
PostgresModule.register({
|
|
36
|
+
// default's options...
|
|
37
|
+
})
|
|
38
|
+
],
|
|
39
|
+
providers: [SampleService]
|
|
40
|
+
})
|
|
41
|
+
export class SampleModule {}
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
3. Inject `Postgres` service.
|
|
45
|
+
|
|
46
|
+
```typescript
|
|
47
|
+
import { Postgres } from './file-that-exported-postgres';
|
|
48
|
+
|
|
49
|
+
@Injectable()
|
|
50
|
+
class SampleService {
|
|
51
|
+
constructor(
|
|
52
|
+
private readonly postgres: Postgres,
|
|
53
|
+
) {}
|
|
54
|
+
|
|
55
|
+
async sampleMethod() {
|
|
56
|
+
const result1 = await this.postgres.default.query(`select 1=1;`);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
### Register multiple postgres instances
|
|
62
|
+
|
|
63
|
+
1. Define postgres connection instance names and export module, service & decorator.
|
|
64
|
+
|
|
65
|
+
e.g.: `instance_1`,`instance_2`.
|
|
66
|
+
|
|
67
|
+
```typescript
|
|
68
|
+
export const { Postgres, PostgresModule, Transaction } = definePostgres<'instance_1' | 'instance_2'>();
|
|
69
|
+
export type Postgres = InstanceType<typeof Postgres>;
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
2. Register postgres connection instances with options.
|
|
73
|
+
|
|
74
|
+
```typescript
|
|
75
|
+
@Module({
|
|
76
|
+
imports: [
|
|
77
|
+
PostgresModule.register({
|
|
78
|
+
connections: [
|
|
79
|
+
{
|
|
80
|
+
name: 'instance1',
|
|
81
|
+
// instance_1's options...
|
|
82
|
+
},
|
|
83
|
+
{
|
|
84
|
+
name: 'instance2',
|
|
85
|
+
// instance_2's options...
|
|
86
|
+
}
|
|
87
|
+
]
|
|
88
|
+
})
|
|
89
|
+
],
|
|
90
|
+
providers: [SampleService]
|
|
91
|
+
})
|
|
92
|
+
export class SampleModule {}
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
3. Inject `Postgres` service.
|
|
96
|
+
|
|
97
|
+
```typescript
|
|
98
|
+
import { Postgres } from './file-that-exported-postgres';
|
|
99
|
+
|
|
100
|
+
@Injectable()
|
|
101
|
+
class SampleService {
|
|
102
|
+
constructor(
|
|
103
|
+
private readonly postgres: Postgres,
|
|
104
|
+
) {}
|
|
105
|
+
|
|
106
|
+
async sampleMethod() {
|
|
107
|
+
const result1 = await this.postgres.instance1.query(`select 1=1;`);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
### Using with node-postgres [`Query`](https://node-postgres.com/apis/client#clientquery)
|
|
113
|
+
|
|
114
|
+
```typescript
|
|
115
|
+
import { Query } from 'pg';
|
|
116
|
+
import { Postgres } from './file-that-exported-postgres';
|
|
117
|
+
|
|
118
|
+
@Injectable()
|
|
119
|
+
class SampleService {
|
|
120
|
+
constructor(
|
|
121
|
+
private readonly postgres: Postgres
|
|
122
|
+
) {}
|
|
123
|
+
|
|
124
|
+
async sampleMethod() {
|
|
125
|
+
const query = new Query('select $1::text as name', ['brianc']);
|
|
126
|
+
const result = await this.postgres.default.query(query);
|
|
127
|
+
|
|
128
|
+
result.on('row', (row) => {
|
|
129
|
+
console.log('row!', row); // { name: 'brianc' }
|
|
130
|
+
})
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
### Enable transaction
|
|
136
|
+
|
|
137
|
+
Apply transaction on all postgres connection instances:
|
|
138
|
+
|
|
139
|
+
```typescript
|
|
140
|
+
import { Postgres, Transaction } from './file-that-exported-postgres';
|
|
141
|
+
|
|
142
|
+
@Injectable()
|
|
143
|
+
class SampleService {
|
|
144
|
+
constructor(
|
|
145
|
+
private readonly postgres: Postgres
|
|
146
|
+
) {}
|
|
147
|
+
|
|
148
|
+
// Supposes we have connection instances: `instance1` and `instance2`.
|
|
149
|
+
// By default it will enable transaction for both `instance1` and `instance2` if not specified.
|
|
150
|
+
@Transaction()
|
|
151
|
+
async sampleMethod() {
|
|
152
|
+
const result = await this.postgres.instance1.query(`select 1=1;`);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
Apply transaction on specified postgres connection instances:
|
|
158
|
+
|
|
159
|
+
```typescript
|
|
160
|
+
import { Postgres, Transaction } from './file-that-exported-postgres';
|
|
161
|
+
|
|
162
|
+
@Injectable()
|
|
163
|
+
class SampleService {
|
|
164
|
+
constructor(
|
|
165
|
+
private readonly postgres: Postgres
|
|
166
|
+
) {}
|
|
167
|
+
|
|
168
|
+
// Supposes we have connection instances: `instance1` and `instance2`.
|
|
169
|
+
// It will enable transaction for `instance1` as specified.
|
|
170
|
+
@Transaction(`instance1`)
|
|
171
|
+
async sampleMethod() {
|
|
172
|
+
const result = await this.postgres.instance1.query(`select 1=1;`);
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
## License
|
|
178
|
+
|
|
179
|
+
MIT License
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
declare const ALS: unique symbol;
|
|
2
|
+
declare const GET_CLIENT: unique symbol;
|
|
3
|
+
declare const DEFAULT_INSTANCE_NAME = "default";
|
|
4
|
+
declare const MAX_LENGTH = 42;
|
|
5
|
+
declare const CONNEXTION_POSTGRES_DEBUG = "CONNEXTION_POSTGRES_DEBUG";
|
|
6
|
+
declare const DATE_FORMAT = "YYYY-MM-DD HH:mm:sssZ";
|
|
7
|
+
declare const TRANSACTION_META = "postgres:transaction";
|
|
8
|
+
|
|
9
|
+
export { ALS, CONNEXTION_POSTGRES_DEBUG, DATE_FORMAT, DEFAULT_INSTANCE_NAME, GET_CLIENT, MAX_LENGTH, TRANSACTION_META };
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
3
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
4
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
5
|
+
var __export = (target, all) => {
|
|
6
|
+
for (var name in all)
|
|
7
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
8
|
+
};
|
|
9
|
+
var __copyProps = (to, from, except, desc) => {
|
|
10
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
11
|
+
for (let key of __getOwnPropNames(from))
|
|
12
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
13
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
14
|
+
}
|
|
15
|
+
return to;
|
|
16
|
+
};
|
|
17
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
18
|
+
var constants_exports = {};
|
|
19
|
+
__export(constants_exports, {
|
|
20
|
+
ALS: () => ALS,
|
|
21
|
+
CONNEXTION_POSTGRES_DEBUG: () => CONNEXTION_POSTGRES_DEBUG,
|
|
22
|
+
DATE_FORMAT: () => DATE_FORMAT,
|
|
23
|
+
DEFAULT_INSTANCE_NAME: () => DEFAULT_INSTANCE_NAME,
|
|
24
|
+
GET_CLIENT: () => GET_CLIENT,
|
|
25
|
+
MAX_LENGTH: () => MAX_LENGTH,
|
|
26
|
+
TRANSACTION_META: () => TRANSACTION_META
|
|
27
|
+
});
|
|
28
|
+
module.exports = __toCommonJS(constants_exports);
|
|
29
|
+
const ALS = Symbol(`ALS`);
|
|
30
|
+
const GET_CLIENT = Symbol(`GET_CLIENT`);
|
|
31
|
+
const DEFAULT_INSTANCE_NAME = "default";
|
|
32
|
+
const MAX_LENGTH = 42;
|
|
33
|
+
const CONNEXTION_POSTGRES_DEBUG = "CONNEXTION_POSTGRES_DEBUG";
|
|
34
|
+
const DATE_FORMAT = "YYYY-MM-DD HH:mm:sssZ";
|
|
35
|
+
const TRANSACTION_META = "postgres:transaction";
|
|
36
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
37
|
+
0 && (module.exports = {
|
|
38
|
+
ALS,
|
|
39
|
+
CONNEXTION_POSTGRES_DEBUG,
|
|
40
|
+
DATE_FORMAT,
|
|
41
|
+
DEFAULT_INSTANCE_NAME,
|
|
42
|
+
GET_CLIENT,
|
|
43
|
+
MAX_LENGTH,
|
|
44
|
+
TRANSACTION_META
|
|
45
|
+
});
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { PostgresInstanceOptions } from './types.js';
|
|
2
|
+
import * as _nestjs_common from '@nestjs/common';
|
|
3
|
+
import * as _nestjs_kitchen_connextion from '@nestjs-kitchen/connextion';
|
|
4
|
+
import { PostgresInstance } from './postgres.instance.js';
|
|
5
|
+
import 'pg';
|
|
6
|
+
import 'node:async_hooks';
|
|
7
|
+
import './constants.js';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Creates a set of Postgres services, modules, and their associated Transaction decorator.
|
|
11
|
+
*/
|
|
12
|
+
declare const definePostgres: <T extends string = "default">() => {
|
|
13
|
+
/**
|
|
14
|
+
* The Postgres service, responsible for managing all postgres connection instances registered by the module.
|
|
15
|
+
*/
|
|
16
|
+
Postgres: _nestjs_common.Type<Record<_nestjs_kitchen_connextion.ConnectionOptionName<T>, Omit<PostgresInstance, keyof _nestjs_kitchen_connextion.ConnextionInstance<unknown>>>>;
|
|
17
|
+
/**
|
|
18
|
+
* The Postgres module, used to register and create postgres connection instances with options.
|
|
19
|
+
*
|
|
20
|
+
* This module can be configured using 2 static methods:
|
|
21
|
+
*
|
|
22
|
+
* - `register`
|
|
23
|
+
* - `registerAsync`
|
|
24
|
+
*
|
|
25
|
+
*/
|
|
26
|
+
PostgresModule: {
|
|
27
|
+
new (): {};
|
|
28
|
+
register(options: _nestjs_kitchen_connextion.ModuleOptions<T, PostgresInstanceOptions>): _nestjs_common.DynamicModule;
|
|
29
|
+
registerAsync(options: _nestjs_kitchen_connextion.AsyncModuleOptions<T, PostgresInstanceOptions>): _nestjs_common.DynamicModule;
|
|
30
|
+
};
|
|
31
|
+
/**
|
|
32
|
+
* A decorator that automatically enables transactions for the specific Postgres
|
|
33
|
+
* service instances associated with the decorated method.
|
|
34
|
+
*
|
|
35
|
+
* - By default, transactions are enabled for all instances of the associated Postgres service.
|
|
36
|
+
* - If specific instances are specified, only those instances will have transactions enabled.
|
|
37
|
+
*/
|
|
38
|
+
Transaction: (...rest: T[]) => (target: any, _propertyKey: string, propertyDescriptor: PropertyDescriptor) => PropertyDescriptor;
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
export { definePostgres };
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
3
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
4
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
5
|
+
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
var define_postgres_exports = {};
|
|
20
|
+
__export(define_postgres_exports, {
|
|
21
|
+
definePostgres: () => definePostgres
|
|
22
|
+
});
|
|
23
|
+
module.exports = __toCommonJS(define_postgres_exports);
|
|
24
|
+
var import_connextion = require("@nestjs-kitchen/connextion");
|
|
25
|
+
var import_constants = require("./constants");
|
|
26
|
+
var import_postgres = require("./postgres.instance");
|
|
27
|
+
var import_transaction = require("./transaction");
|
|
28
|
+
const innerDefinePostgres = (0, import_connextion.defineConnextionBuilder)({
|
|
29
|
+
connextionName: "Postgres",
|
|
30
|
+
InstanceClass: import_postgres.PostgresInstance,
|
|
31
|
+
defaultInstanceName: import_constants.DEFAULT_INSTANCE_NAME
|
|
32
|
+
});
|
|
33
|
+
const definePostgres = /* @__PURE__ */ __name(() => {
|
|
34
|
+
const { Postgres, PostgresModule } = innerDefinePostgres();
|
|
35
|
+
return {
|
|
36
|
+
/**
|
|
37
|
+
* The Postgres service, responsible for managing all postgres connection instances registered by the module.
|
|
38
|
+
*/
|
|
39
|
+
Postgres,
|
|
40
|
+
/**
|
|
41
|
+
* The Postgres module, used to register and create postgres connection instances with options.
|
|
42
|
+
*
|
|
43
|
+
* This module can be configured using 2 static methods:
|
|
44
|
+
*
|
|
45
|
+
* - `register`
|
|
46
|
+
* - `registerAsync`
|
|
47
|
+
*
|
|
48
|
+
*/
|
|
49
|
+
PostgresModule,
|
|
50
|
+
/**
|
|
51
|
+
* A decorator that automatically enables transactions for the specific Postgres
|
|
52
|
+
* service instances associated with the decorated method.
|
|
53
|
+
*
|
|
54
|
+
* - By default, transactions are enabled for all instances of the associated Postgres service.
|
|
55
|
+
* - If specific instances are specified, only those instances will have transactions enabled.
|
|
56
|
+
*/
|
|
57
|
+
Transaction: (0, import_transaction.createTransaction)(Postgres)
|
|
58
|
+
};
|
|
59
|
+
}, "definePostgres");
|
|
60
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
61
|
+
0 && (module.exports = {
|
|
62
|
+
definePostgres
|
|
63
|
+
});
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { ConnextionError } from '@nestjs-kitchen/connextion';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Internal error type.
|
|
5
|
+
*/
|
|
6
|
+
declare class PostgresError extends ConnextionError {
|
|
7
|
+
cause?: unknown;
|
|
8
|
+
constructor(message?: string | Error, cause?: unknown);
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export { PostgresError };
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
3
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
4
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
5
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
6
|
+
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
|
7
|
+
var __export = (target, all) => {
|
|
8
|
+
for (var name in all)
|
|
9
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
10
|
+
};
|
|
11
|
+
var __copyProps = (to, from, except, desc) => {
|
|
12
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
13
|
+
for (let key of __getOwnPropNames(from))
|
|
14
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
15
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
16
|
+
}
|
|
17
|
+
return to;
|
|
18
|
+
};
|
|
19
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
20
|
+
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
21
|
+
var errors_exports = {};
|
|
22
|
+
__export(errors_exports, {
|
|
23
|
+
PostgresError: () => PostgresError
|
|
24
|
+
});
|
|
25
|
+
module.exports = __toCommonJS(errors_exports);
|
|
26
|
+
var import_connextion = require("@nestjs-kitchen/connextion");
|
|
27
|
+
const _PostgresError = class _PostgresError extends import_connextion.ConnextionError {
|
|
28
|
+
constructor(message, cause) {
|
|
29
|
+
super(typeof message === "string" ? message : message?.message);
|
|
30
|
+
__publicField(this, "cause");
|
|
31
|
+
this.name = "PostgresError";
|
|
32
|
+
this.cause = cause;
|
|
33
|
+
Object.setPrototypeOf(this, new.target.prototype);
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
__name(_PostgresError, "PostgresError");
|
|
37
|
+
let PostgresError = _PostgresError;
|
|
38
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
39
|
+
0 && (module.exports = {
|
|
40
|
+
PostgresError
|
|
41
|
+
});
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export { definePostgres } from './define-postgres.js';
|
|
2
|
+
export { PostgresError } from './errors.js';
|
|
3
|
+
import './types.js';
|
|
4
|
+
import 'pg';
|
|
5
|
+
import '@nestjs/common';
|
|
6
|
+
import '@nestjs-kitchen/connextion';
|
|
7
|
+
import './postgres.instance.js';
|
|
8
|
+
import 'node:async_hooks';
|
|
9
|
+
import './constants.js';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
3
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
4
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
5
|
+
var __export = (target, all) => {
|
|
6
|
+
for (var name in all)
|
|
7
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
8
|
+
};
|
|
9
|
+
var __copyProps = (to, from, except, desc) => {
|
|
10
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
11
|
+
for (let key of __getOwnPropNames(from))
|
|
12
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
13
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
14
|
+
}
|
|
15
|
+
return to;
|
|
16
|
+
};
|
|
17
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
18
|
+
var src_exports = {};
|
|
19
|
+
__export(src_exports, {
|
|
20
|
+
PostgresError: () => import_errors.PostgresError,
|
|
21
|
+
definePostgres: () => import_define_postgres.definePostgres
|
|
22
|
+
});
|
|
23
|
+
module.exports = __toCommonJS(src_exports);
|
|
24
|
+
var import_define_postgres = require("./define-postgres");
|
|
25
|
+
var import_errors = require("./errors");
|
|
26
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
27
|
+
0 && (module.exports = {
|
|
28
|
+
PostgresError,
|
|
29
|
+
definePostgres
|
|
30
|
+
});
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
2
|
+
import { ConnextionInstance } from '@nestjs-kitchen/connextion';
|
|
3
|
+
import { PoolClient, Submittable, QueryArrayConfig, QueryConfigValues, QueryArrayResult, QueryResultRow, QueryConfig, QueryResult } from 'pg';
|
|
4
|
+
import { ALS, GET_CLIENT } from './constants.js';
|
|
5
|
+
import { PostgresInstanceOptions, ALSType } from './types.js';
|
|
6
|
+
|
|
7
|
+
declare class PostgresInstance extends ConnextionInstance<PostgresInstanceOptions> {
|
|
8
|
+
private pool;
|
|
9
|
+
private logger;
|
|
10
|
+
private debug;
|
|
11
|
+
[ALS]: AsyncLocalStorage<ALSType>;
|
|
12
|
+
private listener1;
|
|
13
|
+
private listener2;
|
|
14
|
+
constructor(name: string, options?: PostgresInstanceOptions);
|
|
15
|
+
private end;
|
|
16
|
+
dispose(): Promise<void> | undefined;
|
|
17
|
+
create(options: PostgresInstanceOptions): void;
|
|
18
|
+
[GET_CLIENT](): Promise<PoolClient>;
|
|
19
|
+
query<T extends Submittable>(queryStream: T): Promise<T>;
|
|
20
|
+
query<R extends any[] = any[], I = any[]>(queryConfig: QueryArrayConfig<I>, values?: QueryConfigValues<I>): Promise<QueryArrayResult<R>>;
|
|
21
|
+
query<R extends QueryResultRow = any, I = any[]>(queryConfig: QueryConfig<I>): Promise<QueryResult<R>>;
|
|
22
|
+
query<R extends QueryResultRow = any, I = any[]>(queryTextOrConfig: string | QueryConfig<I>, values?: QueryConfigValues<I>): Promise<QueryResult<R>>;
|
|
23
|
+
private queryWithConfig;
|
|
24
|
+
private transactionQueryWithConfig;
|
|
25
|
+
private queryWithSubmittable;
|
|
26
|
+
private transactionQueryWithSubmittable;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export { PostgresInstance };
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
3
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
4
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
5
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
6
|
+
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
|
7
|
+
var __export = (target, all) => {
|
|
8
|
+
for (var name in all)
|
|
9
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
10
|
+
};
|
|
11
|
+
var __copyProps = (to, from, except, desc) => {
|
|
12
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
13
|
+
for (let key of __getOwnPropNames(from))
|
|
14
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
15
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
16
|
+
}
|
|
17
|
+
return to;
|
|
18
|
+
};
|
|
19
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
20
|
+
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
21
|
+
var postgres_instance_exports = {};
|
|
22
|
+
__export(postgres_instance_exports, {
|
|
23
|
+
PostgresInstance: () => PostgresInstance
|
|
24
|
+
});
|
|
25
|
+
module.exports = __toCommonJS(postgres_instance_exports);
|
|
26
|
+
var import_node_async_hooks = require("node:async_hooks");
|
|
27
|
+
var import_connextion = require("@nestjs-kitchen/connextion");
|
|
28
|
+
var import_common = require("@nestjs/common");
|
|
29
|
+
var import_pg = require("pg");
|
|
30
|
+
var import_uid = require("uid");
|
|
31
|
+
var import_constants = require("./constants");
|
|
32
|
+
var import_errors = require("./errors");
|
|
33
|
+
var import_utils = require("./utils");
|
|
34
|
+
var _a;
|
|
35
|
+
const _PostgresInstance = class _PostgresInstance extends import_connextion.ConnextionInstance {
|
|
36
|
+
constructor(name, options) {
|
|
37
|
+
super(name, options);
|
|
38
|
+
__publicField(this, "pool");
|
|
39
|
+
__publicField(this, "logger");
|
|
40
|
+
__publicField(this, "debug");
|
|
41
|
+
// Every instance should have its own als to avoid accessing wrong context.
|
|
42
|
+
__publicField(this, _a, new import_node_async_hooks.AsyncLocalStorage());
|
|
43
|
+
__publicField(this, "listener1", /* @__PURE__ */ __name((_cli) => {
|
|
44
|
+
_cli.on("error", this.listener2);
|
|
45
|
+
}, "listener1"));
|
|
46
|
+
__publicField(this, "listener2", /* @__PURE__ */ __name((err) => {
|
|
47
|
+
this.logger.error(err);
|
|
48
|
+
}, "listener2"));
|
|
49
|
+
this.logger = new import_common.Logger(`Postgres][${name}`);
|
|
50
|
+
this.debug = Boolean(process.env[import_constants.CONNEXTION_POSTGRES_DEBUG]) || options?.debug;
|
|
51
|
+
}
|
|
52
|
+
async end(pool) {
|
|
53
|
+
if (!pool) {
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
try {
|
|
57
|
+
await pool.end();
|
|
58
|
+
pool.off("connect", this.listener1);
|
|
59
|
+
pool.off("error", this.listener2);
|
|
60
|
+
} catch (error) {
|
|
61
|
+
this.logger.error(error);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
dispose() {
|
|
65
|
+
if (!this.pool) {
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
const pool = this.pool;
|
|
69
|
+
this.pool = void 0;
|
|
70
|
+
return this.end(pool);
|
|
71
|
+
}
|
|
72
|
+
create(options) {
|
|
73
|
+
this.dispose();
|
|
74
|
+
const pool = new import_pg.Pool(options);
|
|
75
|
+
pool.on("connect", this.listener1);
|
|
76
|
+
pool.on("error", this.listener2);
|
|
77
|
+
this.pool = pool;
|
|
78
|
+
}
|
|
79
|
+
async [(_a = import_constants.ALS, import_constants.GET_CLIENT)]() {
|
|
80
|
+
if (!this.pool) {
|
|
81
|
+
throw new import_errors.PostgresError("pool not found");
|
|
82
|
+
}
|
|
83
|
+
if (!this.debug) {
|
|
84
|
+
const [client2, err2] = await (0, import_utils.plainPromise)(this.pool.connect());
|
|
85
|
+
if (err2) {
|
|
86
|
+
throw new import_errors.PostgresError(err2, err2);
|
|
87
|
+
}
|
|
88
|
+
if (!client2) {
|
|
89
|
+
throw new import_errors.PostgresError("client not found");
|
|
90
|
+
}
|
|
91
|
+
return client2;
|
|
92
|
+
}
|
|
93
|
+
const logger = (0, import_utils.createDebugLogger)(this.logger.debug.bind(this.logger), this.debug);
|
|
94
|
+
const debug = (0, import_utils.debugFactroy)(this.name, (0, import_uid.uid)(21), logger);
|
|
95
|
+
const [client, err] = await (0, import_utils.plainPromise)(debug.pool.connect(this.pool.connect.bind(this.pool))());
|
|
96
|
+
if (err) {
|
|
97
|
+
throw new import_errors.PostgresError(err, err);
|
|
98
|
+
}
|
|
99
|
+
if (!client) {
|
|
100
|
+
throw new import_errors.PostgresError("client not found");
|
|
101
|
+
}
|
|
102
|
+
return new Proxy(client, {
|
|
103
|
+
get(target, prop) {
|
|
104
|
+
if (debug.client[prop]) {
|
|
105
|
+
return debug.client[prop](target[prop].bind(target));
|
|
106
|
+
}
|
|
107
|
+
return target[prop];
|
|
108
|
+
}
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
async query(...rest) {
|
|
112
|
+
if (!rest.length) {
|
|
113
|
+
throw new import_errors.PostgresError(`empty parameters`);
|
|
114
|
+
}
|
|
115
|
+
const store = this[import_constants.ALS].getStore();
|
|
116
|
+
const methodMap = {
|
|
117
|
+
submittable: store ? this.transactionQueryWithSubmittable : this.queryWithSubmittable,
|
|
118
|
+
config: store ? this.transactionQueryWithConfig : this.queryWithConfig
|
|
119
|
+
};
|
|
120
|
+
const method = methodMap[(0, import_utils.isSubmittable)(rest[0]) ? "submittable" : "config"].bind(this);
|
|
121
|
+
return method(...rest);
|
|
122
|
+
}
|
|
123
|
+
async queryWithConfig(...rest) {
|
|
124
|
+
const client = await this[import_constants.GET_CLIENT]();
|
|
125
|
+
let err = void 0;
|
|
126
|
+
try {
|
|
127
|
+
return await client.query(...rest);
|
|
128
|
+
} catch (error) {
|
|
129
|
+
err = new import_errors.PostgresError(error, error);
|
|
130
|
+
throw err;
|
|
131
|
+
} finally {
|
|
132
|
+
client.release(err ?? true);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
async transactionQueryWithConfig(...rest) {
|
|
136
|
+
const store = this[import_constants.ALS].getStore();
|
|
137
|
+
const client = await store.client;
|
|
138
|
+
let err = void 0;
|
|
139
|
+
const { promise, resolve } = Promise.withResolvers();
|
|
140
|
+
store.queries.push(promise);
|
|
141
|
+
try {
|
|
142
|
+
return await client.query(...rest);
|
|
143
|
+
} catch (error) {
|
|
144
|
+
err = new import_errors.PostgresError(error, error);
|
|
145
|
+
throw err;
|
|
146
|
+
} finally {
|
|
147
|
+
resolve(err ?? true);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
async queryWithSubmittable(queryStream) {
|
|
151
|
+
const client = await this[import_constants.GET_CLIENT]();
|
|
152
|
+
let res = void 0;
|
|
153
|
+
let err = void 0;
|
|
154
|
+
try {
|
|
155
|
+
res = await client.query(queryStream);
|
|
156
|
+
return res;
|
|
157
|
+
} catch (error) {
|
|
158
|
+
err = new import_errors.PostgresError(error, error);
|
|
159
|
+
throw err;
|
|
160
|
+
} finally {
|
|
161
|
+
if (res) {
|
|
162
|
+
const onError = /* @__PURE__ */ __name((error) => {
|
|
163
|
+
res.off("end", onEnd);
|
|
164
|
+
client.release(new import_errors.PostgresError(error, error));
|
|
165
|
+
}, "onError");
|
|
166
|
+
const onEnd = /* @__PURE__ */ __name(() => {
|
|
167
|
+
res.off("error", onError);
|
|
168
|
+
client.release(true);
|
|
169
|
+
}, "onEnd");
|
|
170
|
+
res.once("end", onEnd);
|
|
171
|
+
res.once("error", onError);
|
|
172
|
+
} else {
|
|
173
|
+
client.release(err ?? true);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
async transactionQueryWithSubmittable(queryStream) {
|
|
178
|
+
const store = this[import_constants.ALS].getStore();
|
|
179
|
+
const client = await store.client;
|
|
180
|
+
let res = void 0;
|
|
181
|
+
let err = void 0;
|
|
182
|
+
const { promise, resolve } = Promise.withResolvers();
|
|
183
|
+
store.queries.push(promise);
|
|
184
|
+
try {
|
|
185
|
+
res = await client.query(queryStream);
|
|
186
|
+
return res;
|
|
187
|
+
} catch (error) {
|
|
188
|
+
err = new import_errors.PostgresError(error, error);
|
|
189
|
+
throw err;
|
|
190
|
+
} finally {
|
|
191
|
+
if (res) {
|
|
192
|
+
const onError = /* @__PURE__ */ __name((error) => {
|
|
193
|
+
res.off("end", onEnd);
|
|
194
|
+
resolve(new import_errors.PostgresError(error, error));
|
|
195
|
+
}, "onError");
|
|
196
|
+
const onEnd = /* @__PURE__ */ __name(() => {
|
|
197
|
+
res.off("error", onError);
|
|
198
|
+
resolve(true);
|
|
199
|
+
}, "onEnd");
|
|
200
|
+
res.once("end", onEnd);
|
|
201
|
+
res.once("error", onError);
|
|
202
|
+
} else {
|
|
203
|
+
resolve(err ?? true);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
};
|
|
208
|
+
__name(_PostgresInstance, "PostgresInstance");
|
|
209
|
+
let PostgresInstance = _PostgresInstance;
|
|
210
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
211
|
+
0 && (module.exports = {
|
|
212
|
+
PostgresInstance
|
|
213
|
+
});
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { defineConnextionBuilder } from '@nestjs-kitchen/connextion';
|
|
2
|
+
|
|
3
|
+
type Postgres = ReturnType<ReturnType<typeof defineConnextionBuilder<'Postgres', PostgresInstance>>>['Postgres'];
|
|
4
|
+
declare const createTransaction: <T extends string>(Postgres: Postgres) => (...rest: T[]) => (target: any, _propertyKey: string, propertyDescriptor: PropertyDescriptor) => PropertyDescriptor;
|
|
5
|
+
|
|
6
|
+
export { createTransaction };
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
3
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
4
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
5
|
+
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
var transaction_exports = {};
|
|
20
|
+
__export(transaction_exports, {
|
|
21
|
+
createTransaction: () => createTransaction
|
|
22
|
+
});
|
|
23
|
+
module.exports = __toCommonJS(transaction_exports);
|
|
24
|
+
var import_common = require("@nestjs/common");
|
|
25
|
+
var import_constants = require("./constants");
|
|
26
|
+
var import_errors = require("./errors");
|
|
27
|
+
var import_utils = require("./utils");
|
|
28
|
+
const createTransaction = /* @__PURE__ */ __name((Postgres) => {
|
|
29
|
+
const postgresPropName = Symbol("postgres");
|
|
30
|
+
return (...rest) => {
|
|
31
|
+
const injectPostgres = (0, import_common.Inject)(Postgres);
|
|
32
|
+
return (target, _propertyKey, propertyDescriptor) => {
|
|
33
|
+
injectPostgres(target, postgresPropName);
|
|
34
|
+
const originalMethod = propertyDescriptor.value;
|
|
35
|
+
if ((0, import_utils.getTransactionMetdata)(originalMethod)) {
|
|
36
|
+
throw new import_errors.PostgresError("Cannot reapply the same transaction decorator multiple times.");
|
|
37
|
+
}
|
|
38
|
+
(0, import_utils.setTransactionMetdata)(originalMethod);
|
|
39
|
+
propertyDescriptor.value = async function(...args) {
|
|
40
|
+
const that = this;
|
|
41
|
+
const postgres = that[postgresPropName];
|
|
42
|
+
const keys = rest.length ? rest : Object.keys(postgres.instanceTokens);
|
|
43
|
+
const validNames = [];
|
|
44
|
+
const invalidNames = [];
|
|
45
|
+
(0, import_utils.normalizeStrings)(keys).forEach((name) => {
|
|
46
|
+
if (postgres.instanceTokens[name]) {
|
|
47
|
+
validNames.push(name);
|
|
48
|
+
} else {
|
|
49
|
+
invalidNames.push(name);
|
|
50
|
+
}
|
|
51
|
+
});
|
|
52
|
+
if (invalidNames.length) {
|
|
53
|
+
throw new import_errors.PostgresError(`Invalid keys: ${invalidNames.join(", ")}`);
|
|
54
|
+
}
|
|
55
|
+
const list = validNames.map((name) => {
|
|
56
|
+
return {
|
|
57
|
+
name,
|
|
58
|
+
store: {
|
|
59
|
+
client: postgres[name][import_constants.GET_CLIENT](),
|
|
60
|
+
queries: []
|
|
61
|
+
},
|
|
62
|
+
als: postgres[name][import_constants.ALS],
|
|
63
|
+
inited: false
|
|
64
|
+
};
|
|
65
|
+
});
|
|
66
|
+
const initClients = /* @__PURE__ */ __name(async () => {
|
|
67
|
+
for (const ele of list) {
|
|
68
|
+
await ele.store.client;
|
|
69
|
+
ele.inited = true;
|
|
70
|
+
}
|
|
71
|
+
}, "initClients");
|
|
72
|
+
const runWithClients = /* @__PURE__ */ __name(async (fn) => {
|
|
73
|
+
for (const ele of list) {
|
|
74
|
+
if (ele.inited) {
|
|
75
|
+
const client = await ele.store.client;
|
|
76
|
+
await fn(client);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
}, "runWithClients");
|
|
80
|
+
const releaseClients = /* @__PURE__ */ __name(async (err2) => runWithClients((client) => client.release(err2 ?? true)), "releaseClients");
|
|
81
|
+
const [_, initErr] = await (0, import_utils.plainPromise)(initClients());
|
|
82
|
+
if (initErr) {
|
|
83
|
+
await releaseClients();
|
|
84
|
+
throw initErr;
|
|
85
|
+
}
|
|
86
|
+
const executeQueries = list.reduce((next, ele) => () => ele.als.run(ele.store, next), () => originalMethod.apply(that, args));
|
|
87
|
+
const [result, err] = await (0, import_utils.plainPromise)((async () => {
|
|
88
|
+
const [result2, err2] = await (0, import_utils.plainPromise)(
|
|
89
|
+
// Start transaction and execute queries.
|
|
90
|
+
(async () => {
|
|
91
|
+
await runWithClients((client) => client.query("BEGIN"));
|
|
92
|
+
const result3 = await executeQueries();
|
|
93
|
+
const queryResults = await Promise.all(list.flatMap((c) => c.store.queries));
|
|
94
|
+
const queryFailures = queryResults.filter((res) => res !== true);
|
|
95
|
+
if (queryFailures.length) {
|
|
96
|
+
throw queryFailures[0];
|
|
97
|
+
}
|
|
98
|
+
return result3;
|
|
99
|
+
})()
|
|
100
|
+
);
|
|
101
|
+
await runWithClients((client) => client.query(err2 ? "ROLLBACK" : "COMMIT"));
|
|
102
|
+
if (err2) {
|
|
103
|
+
throw err2;
|
|
104
|
+
}
|
|
105
|
+
return result2;
|
|
106
|
+
})());
|
|
107
|
+
await releaseClients(err);
|
|
108
|
+
if (err) {
|
|
109
|
+
throw err;
|
|
110
|
+
}
|
|
111
|
+
return result;
|
|
112
|
+
};
|
|
113
|
+
(0, import_utils.copyMethodMetadata)(originalMethod, propertyDescriptor.value);
|
|
114
|
+
return propertyDescriptor;
|
|
115
|
+
};
|
|
116
|
+
};
|
|
117
|
+
}, "createTransaction");
|
|
118
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
119
|
+
0 && (module.exports = {
|
|
120
|
+
createTransaction
|
|
121
|
+
});
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { PoolClient, PoolConfig } from 'pg';
|
|
2
|
+
|
|
3
|
+
type ALSQueryType = Error | true;
|
|
4
|
+
interface ALSType {
|
|
5
|
+
client: Promise<PoolClient>;
|
|
6
|
+
queries: Promise<ALSQueryType>[];
|
|
7
|
+
}
|
|
8
|
+
type PostgresInstanceOptions = PoolConfig & {
|
|
9
|
+
debug?: boolean | ((data: Record<any, any>) => void);
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
export type { ALSQueryType, ALSType, PostgresInstanceOptions };
|
package/dist/types.js
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
3
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
4
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
5
|
+
var __copyProps = (to, from, except, desc) => {
|
|
6
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
7
|
+
for (let key of __getOwnPropNames(from))
|
|
8
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
9
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
10
|
+
}
|
|
11
|
+
return to;
|
|
12
|
+
};
|
|
13
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
14
|
+
var types_exports = {};
|
|
15
|
+
module.exports = __toCommonJS(types_exports);
|
package/dist/utils.d.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { Submittable, PoolClient } from 'pg';
|
|
2
|
+
|
|
3
|
+
declare const isSubmittable: (val: any) => val is Submittable;
|
|
4
|
+
declare const isObject: (val: any) => val is object;
|
|
5
|
+
declare const normalizeStrings: (strs?: string[]) => string[];
|
|
6
|
+
declare const plainPromise: <T>(promise: Promise<T> | T) => Promise<[T, undefined] | [undefined, any]>;
|
|
7
|
+
declare const truncateString: (str: string, maxLength: number) => string;
|
|
8
|
+
declare const printTable: (logData: Record<string, any>) => string;
|
|
9
|
+
declare const getCurrentDateStr: () => string;
|
|
10
|
+
declare const formatArray: (arr?: any) => string;
|
|
11
|
+
declare const extraceQueryTextAndValues: (...rest: any[]) => [text: string, values: any[]];
|
|
12
|
+
declare const createDebugLogger: (defaultLogger: (...rest: any) => void, customFormater?: Boolean | ((data: Record<any, any>) => void)) => (data: Record<any, any>) => void;
|
|
13
|
+
declare const debugFactroy: (name: string, queryId: string, logger: (data: Record<any, any>) => void) => {
|
|
14
|
+
pool: {
|
|
15
|
+
connect: <T extends () => Promise<PoolClient>>(callback: T) => () => Promise<PoolClient>;
|
|
16
|
+
};
|
|
17
|
+
client: {
|
|
18
|
+
query: <T extends (...rest: unknown[]) => Promise<any>>(callback: T) => (...rest: Parameters<T>) => Promise<any>;
|
|
19
|
+
release: <T extends (...rest: unknown[]) => void>(callback: T) => (...rest: Parameters<T>) => void;
|
|
20
|
+
};
|
|
21
|
+
};
|
|
22
|
+
declare const copyMethodMetadata: (from: any, to: any) => void;
|
|
23
|
+
declare const getTransactionMetdata: (target: any) => any;
|
|
24
|
+
declare const setTransactionMetdata: (target: any) => void;
|
|
25
|
+
|
|
26
|
+
export { copyMethodMetadata, createDebugLogger, debugFactroy, extraceQueryTextAndValues, formatArray, getCurrentDateStr, getTransactionMetdata, isObject, isSubmittable, normalizeStrings, plainPromise, printTable, setTransactionMetdata, truncateString };
|
package/dist/utils.js
ADDED
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
var __create = Object.create;
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
6
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
7
|
+
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
var utils_exports = {};
|
|
30
|
+
__export(utils_exports, {
|
|
31
|
+
copyMethodMetadata: () => copyMethodMetadata,
|
|
32
|
+
createDebugLogger: () => createDebugLogger,
|
|
33
|
+
debugFactroy: () => debugFactroy,
|
|
34
|
+
extraceQueryTextAndValues: () => extraceQueryTextAndValues,
|
|
35
|
+
formatArray: () => formatArray,
|
|
36
|
+
getCurrentDateStr: () => getCurrentDateStr,
|
|
37
|
+
getTransactionMetdata: () => getTransactionMetdata,
|
|
38
|
+
isObject: () => isObject,
|
|
39
|
+
isSubmittable: () => isSubmittable,
|
|
40
|
+
normalizeStrings: () => normalizeStrings,
|
|
41
|
+
plainPromise: () => plainPromise,
|
|
42
|
+
printTable: () => printTable,
|
|
43
|
+
setTransactionMetdata: () => setTransactionMetdata,
|
|
44
|
+
truncateString: () => truncateString
|
|
45
|
+
});
|
|
46
|
+
module.exports = __toCommonJS(utils_exports);
|
|
47
|
+
var import_dayjs = __toESM(require("dayjs"));
|
|
48
|
+
var import_constants = require("./constants");
|
|
49
|
+
const isSubmittable = /* @__PURE__ */ __name((val) => {
|
|
50
|
+
return val && typeof val.submit === "function";
|
|
51
|
+
}, "isSubmittable");
|
|
52
|
+
const isObject = /* @__PURE__ */ __name((val) => {
|
|
53
|
+
return Object.prototype.toString.call(val) === "[object Object]";
|
|
54
|
+
}, "isObject");
|
|
55
|
+
const normalizeStrings = /* @__PURE__ */ __name((strs) => {
|
|
56
|
+
if (!strs) {
|
|
57
|
+
return [];
|
|
58
|
+
}
|
|
59
|
+
return Array.from(new Set(strs.filter(Boolean).map((ele) => ele.trim())));
|
|
60
|
+
}, "normalizeStrings");
|
|
61
|
+
const plainPromise = /* @__PURE__ */ __name(async (promise) => {
|
|
62
|
+
let result = void 0;
|
|
63
|
+
let err = void 0;
|
|
64
|
+
try {
|
|
65
|
+
result = await promise;
|
|
66
|
+
} catch (error) {
|
|
67
|
+
err = error;
|
|
68
|
+
}
|
|
69
|
+
return [
|
|
70
|
+
result,
|
|
71
|
+
err
|
|
72
|
+
];
|
|
73
|
+
}, "plainPromise");
|
|
74
|
+
const truncateString = /* @__PURE__ */ __name((str, maxLength) => {
|
|
75
|
+
if (str.length <= maxLength) {
|
|
76
|
+
return str;
|
|
77
|
+
}
|
|
78
|
+
const truncatedLength = maxLength - 3;
|
|
79
|
+
if (truncatedLength <= 0) {
|
|
80
|
+
return "...";
|
|
81
|
+
}
|
|
82
|
+
return str.slice(0, truncatedLength) + "...";
|
|
83
|
+
}, "truncateString");
|
|
84
|
+
const printTable = /* @__PURE__ */ __name((logData) => {
|
|
85
|
+
const maxKeyLength = import_constants.MAX_LENGTH / 3;
|
|
86
|
+
const maxValueLength = import_constants.MAX_LENGTH;
|
|
87
|
+
const separatorTop = "\u2500".repeat(maxKeyLength + 2) + "\u252C" + "\u2500".repeat(maxValueLength + 2);
|
|
88
|
+
const separatorBottom = "\u2500".repeat(maxKeyLength + 2) + "\u2534" + "\u2500".repeat(maxValueLength + 2);
|
|
89
|
+
const lines = [
|
|
90
|
+
`\u250C${separatorTop}\u2510`,
|
|
91
|
+
...Object.entries(logData).filter(([_, value]) => value).map(([key, value]) => `\u2502 ${key.padEnd(maxKeyLength)} \u2502 ${truncateString(String(value), import_constants.MAX_LENGTH).padEnd(maxValueLength)} \u2502`),
|
|
92
|
+
`\u2514${separatorBottom}\u2518`
|
|
93
|
+
];
|
|
94
|
+
return lines.join("\n");
|
|
95
|
+
}, "printTable");
|
|
96
|
+
const getCurrentDateStr = /* @__PURE__ */ __name(() => {
|
|
97
|
+
return (0, import_dayjs.default)().format(import_constants.DATE_FORMAT);
|
|
98
|
+
}, "getCurrentDateStr");
|
|
99
|
+
const formatArray = /* @__PURE__ */ __name((arr) => {
|
|
100
|
+
return Array.isArray(arr) ? `[${arr.map(String).join(", ")}]` : "null";
|
|
101
|
+
}, "formatArray");
|
|
102
|
+
const extraceQueryTextAndValues = /* @__PURE__ */ __name((...rest) => {
|
|
103
|
+
const [arg0, arg1] = rest;
|
|
104
|
+
if (arg0 && (isSubmittable(arg0) || isObject(arg0))) {
|
|
105
|
+
return [
|
|
106
|
+
arg0.text,
|
|
107
|
+
arg1 ?? arg0.values
|
|
108
|
+
];
|
|
109
|
+
}
|
|
110
|
+
return [
|
|
111
|
+
arg0,
|
|
112
|
+
arg1
|
|
113
|
+
];
|
|
114
|
+
}, "extraceQueryTextAndValues");
|
|
115
|
+
const createDebugLogger = /* @__PURE__ */ __name((defaultLogger, customFormater) => {
|
|
116
|
+
if (typeof customFormater === "function") {
|
|
117
|
+
return (data) => {
|
|
118
|
+
defaultLogger(customFormater(data));
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
return (data) => {
|
|
122
|
+
const firstLine = `Executing Postgres command
|
|
123
|
+
`;
|
|
124
|
+
defaultLogger(firstLine + printTable(data));
|
|
125
|
+
};
|
|
126
|
+
}, "createDebugLogger");
|
|
127
|
+
const debugFactroy = /* @__PURE__ */ __name((name, queryId, logger) => {
|
|
128
|
+
return {
|
|
129
|
+
pool: {
|
|
130
|
+
connect: /* @__PURE__ */ __name((callback) => {
|
|
131
|
+
return async () => {
|
|
132
|
+
const startOn = getCurrentDateStr();
|
|
133
|
+
let err = void 0;
|
|
134
|
+
try {
|
|
135
|
+
return await callback();
|
|
136
|
+
} catch (error) {
|
|
137
|
+
err = error;
|
|
138
|
+
throw err;
|
|
139
|
+
} finally {
|
|
140
|
+
logger({
|
|
141
|
+
Instance: name,
|
|
142
|
+
Client: queryId,
|
|
143
|
+
Type: "Request new client",
|
|
144
|
+
"Started On": startOn,
|
|
145
|
+
"Ended On": getCurrentDateStr(),
|
|
146
|
+
Status: err ? "Failed" : "Successful",
|
|
147
|
+
Error: err
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
};
|
|
151
|
+
}, "connect")
|
|
152
|
+
},
|
|
153
|
+
client: {
|
|
154
|
+
query: /* @__PURE__ */ __name((callback) => {
|
|
155
|
+
return async (...rest) => {
|
|
156
|
+
const [text, values] = extraceQueryTextAndValues(...rest);
|
|
157
|
+
const submittable = isSubmittable(rest[0]);
|
|
158
|
+
const startOn = getCurrentDateStr();
|
|
159
|
+
let err = void 0;
|
|
160
|
+
if (submittable) {
|
|
161
|
+
rest[0].on("end", () => {
|
|
162
|
+
logger({
|
|
163
|
+
Instance: name,
|
|
164
|
+
Client: queryId,
|
|
165
|
+
Type: "Submittable",
|
|
166
|
+
Text: text,
|
|
167
|
+
Values: formatArray(values),
|
|
168
|
+
"Started On": startOn,
|
|
169
|
+
"Ended On": getCurrentDateStr(),
|
|
170
|
+
Status: "Successful"
|
|
171
|
+
});
|
|
172
|
+
});
|
|
173
|
+
rest[0].on("error", (err2) => {
|
|
174
|
+
logger({
|
|
175
|
+
Instance: name,
|
|
176
|
+
Client: queryId,
|
|
177
|
+
Type: "Submittable",
|
|
178
|
+
Text: text,
|
|
179
|
+
Values: formatArray(values),
|
|
180
|
+
"Started On": startOn,
|
|
181
|
+
"Ended On": getCurrentDateStr(),
|
|
182
|
+
Status: "Failed",
|
|
183
|
+
Error: err2
|
|
184
|
+
});
|
|
185
|
+
});
|
|
186
|
+
}
|
|
187
|
+
try {
|
|
188
|
+
return await callback(...rest);
|
|
189
|
+
} catch (error) {
|
|
190
|
+
err = error;
|
|
191
|
+
throw err;
|
|
192
|
+
} finally {
|
|
193
|
+
if (!submittable) {
|
|
194
|
+
logger({
|
|
195
|
+
Instance: name,
|
|
196
|
+
Client: queryId,
|
|
197
|
+
Type: "Query",
|
|
198
|
+
Text: text,
|
|
199
|
+
Values: formatArray(values),
|
|
200
|
+
"Started On": startOn,
|
|
201
|
+
"Ended On": getCurrentDateStr(),
|
|
202
|
+
Status: err ? "Failed" : "Successful",
|
|
203
|
+
Error: err
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
};
|
|
208
|
+
}, "query"),
|
|
209
|
+
release: /* @__PURE__ */ __name((callback) => {
|
|
210
|
+
return (...rest) => {
|
|
211
|
+
const startOn = getCurrentDateStr();
|
|
212
|
+
let err = void 0;
|
|
213
|
+
try {
|
|
214
|
+
return callback(...rest);
|
|
215
|
+
} catch (error) {
|
|
216
|
+
err = error;
|
|
217
|
+
throw err;
|
|
218
|
+
} finally {
|
|
219
|
+
logger({
|
|
220
|
+
Instance: name,
|
|
221
|
+
Client: queryId,
|
|
222
|
+
Type: "Release client",
|
|
223
|
+
"Started On": startOn,
|
|
224
|
+
"Ended On": getCurrentDateStr(),
|
|
225
|
+
Status: err ? "Failed" : "Successful",
|
|
226
|
+
Error: err
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
};
|
|
230
|
+
}, "release")
|
|
231
|
+
}
|
|
232
|
+
};
|
|
233
|
+
}, "debugFactroy");
|
|
234
|
+
const copyMethodMetadata = /* @__PURE__ */ __name((from, to) => {
|
|
235
|
+
const metadataKeys = Reflect.getMetadataKeys(from);
|
|
236
|
+
metadataKeys.map((key) => {
|
|
237
|
+
const value = Reflect.getMetadata(key, from);
|
|
238
|
+
Reflect.defineMetadata(key, value, to);
|
|
239
|
+
});
|
|
240
|
+
}, "copyMethodMetadata");
|
|
241
|
+
const getTransactionMetdata = /* @__PURE__ */ __name((target) => {
|
|
242
|
+
return Reflect.getMetadata(import_constants.TRANSACTION_META, target);
|
|
243
|
+
}, "getTransactionMetdata");
|
|
244
|
+
const setTransactionMetdata = /* @__PURE__ */ __name((target) => {
|
|
245
|
+
return Reflect.defineMetadata(import_constants.TRANSACTION_META, true, target);
|
|
246
|
+
}, "setTransactionMetdata");
|
|
247
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
248
|
+
0 && (module.exports = {
|
|
249
|
+
copyMethodMetadata,
|
|
250
|
+
createDebugLogger,
|
|
251
|
+
debugFactroy,
|
|
252
|
+
extraceQueryTextAndValues,
|
|
253
|
+
formatArray,
|
|
254
|
+
getCurrentDateStr,
|
|
255
|
+
getTransactionMetdata,
|
|
256
|
+
isObject,
|
|
257
|
+
isSubmittable,
|
|
258
|
+
normalizeStrings,
|
|
259
|
+
plainPromise,
|
|
260
|
+
printTable,
|
|
261
|
+
setTransactionMetdata,
|
|
262
|
+
truncateString
|
|
263
|
+
});
|
package/package.json
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@nestjs-kitchen/connextion-postgres",
|
|
3
|
+
"private": false,
|
|
4
|
+
"description": "A flexible module to provide node-postgres interface in NextJS.",
|
|
5
|
+
"version": "1.0.0",
|
|
6
|
+
"homepage": "https://github.com/yikenman/nestjs-kitchen",
|
|
7
|
+
"repository": "https://github.com/yikenman/nestjs-kitchen",
|
|
8
|
+
"author": "yikenman",
|
|
9
|
+
"license": "MIT",
|
|
10
|
+
"exports": {
|
|
11
|
+
".": {
|
|
12
|
+
"require": "./dist/index.js"
|
|
13
|
+
}
|
|
14
|
+
},
|
|
15
|
+
"main": "./dist/index.js",
|
|
16
|
+
"types": "./dist/index.d.ts",
|
|
17
|
+
"files": [
|
|
18
|
+
"dist"
|
|
19
|
+
],
|
|
20
|
+
"dependencies": {
|
|
21
|
+
"dayjs": "^1.11.13",
|
|
22
|
+
"uid": "^2.0.2"
|
|
23
|
+
},
|
|
24
|
+
"devDependencies": {
|
|
25
|
+
"@nestjs/common": "^10.4.12",
|
|
26
|
+
"@nestjs/testing": "^10.4.12",
|
|
27
|
+
"@types/jest": "^29.5.14",
|
|
28
|
+
"@types/node": "^22.10.1",
|
|
29
|
+
"@types/pg": "^8.11.10",
|
|
30
|
+
"@types/supertest": "^6.0.2",
|
|
31
|
+
"jest": "^29.7.0",
|
|
32
|
+
"pg": "^8.13.1",
|
|
33
|
+
"reflect-metadata": "^0.2.1",
|
|
34
|
+
"supertest": "^7.0.0",
|
|
35
|
+
"ts-jest": "^29.1.2",
|
|
36
|
+
"ts-node": "^10.9.2",
|
|
37
|
+
"tsconfig-paths": "^4.2.0",
|
|
38
|
+
"tsup": "^8.3.5",
|
|
39
|
+
"typescript": "^5.7.2",
|
|
40
|
+
"@nestjs-kitchen/connextion": "1.0.0"
|
|
41
|
+
},
|
|
42
|
+
"engines": {
|
|
43
|
+
"node": ">=20.13.0"
|
|
44
|
+
},
|
|
45
|
+
"keywords": [
|
|
46
|
+
"database",
|
|
47
|
+
"module",
|
|
48
|
+
"NextJS",
|
|
49
|
+
"node-postgres",
|
|
50
|
+
"NodeJS",
|
|
51
|
+
"pg",
|
|
52
|
+
"Postgres",
|
|
53
|
+
"SQL"
|
|
54
|
+
],
|
|
55
|
+
"peerDependencies": {
|
|
56
|
+
"@nestjs/common": "^10.4.12",
|
|
57
|
+
"@types/pg": "^8.11.10",
|
|
58
|
+
"pg": "^8.13.1",
|
|
59
|
+
"reflect-metadata": "^0.2.1",
|
|
60
|
+
"@nestjs-kitchen/connextion": "1.0.0"
|
|
61
|
+
},
|
|
62
|
+
"scripts": {
|
|
63
|
+
"build": "tsup",
|
|
64
|
+
"dev": "tsup --watch",
|
|
65
|
+
"test": "jest",
|
|
66
|
+
"test:ci": "jest --coverage",
|
|
67
|
+
"test:cov": "jest --coverage",
|
|
68
|
+
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/jest/bin/jest --runInBand",
|
|
69
|
+
"test:watch": "jest --watch"
|
|
70
|
+
}
|
|
71
|
+
}
|