@faasjs/knex 0.0.2-beta.302 → 0.0.2-beta.320

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.
@@ -0,0 +1,46 @@
1
+ import { Plugin, DeployData, Next, MountData, UseifyPlugin } from '@faasjs/func';
2
+ import { Logger } from '@faasjs/logger';
3
+ import { Knex as Knex$1 } from 'knex';
4
+
5
+ declare type KnexConfig = {
6
+ name?: string;
7
+ config?: Knex$1.Config;
8
+ };
9
+ /**
10
+ * Knex 插件
11
+ */
12
+ declare class Knex implements Plugin {
13
+ readonly type: string;
14
+ readonly name: string;
15
+ config: Knex$1.Config;
16
+ adapter: Knex$1;
17
+ query: Knex$1;
18
+ logger: Logger;
19
+ /**
20
+ * 创建插件实例
21
+ * @param config {object} 配置
22
+ * @param config.name {string} 配置名
23
+ * @param config.config {object} 数据库配置
24
+ */
25
+ constructor(config?: KnexConfig);
26
+ onDeploy(data: DeployData, next: Next): Promise<void>;
27
+ onMount(data: MountData, next: Next): Promise<void>;
28
+ raw<TResult = any>(sql: string, bindings?: Knex$1.RawBinding[] | Knex$1.ValueDict): Promise<Knex$1.Raw<TResult>>;
29
+ transaction<TResult = any>(scope: (trx: Knex$1.Transaction<any, any>) => Promise<TResult> | void, config?: any): Promise<TResult>;
30
+ schema(): Knex$1.SchemaBuilder;
31
+ quit(): Promise<void>;
32
+ }
33
+ declare function useKnex(config?: KnexConfig): Knex & UseifyPlugin;
34
+ declare function query<TName extends Knex$1.TableNames>(table: TName): Knex$1.QueryBuilder<Knex$1.TableType<TName>, {
35
+ _base: Knex$1.ResolveTableType<Knex$1.TableType<TName>, "base">;
36
+ _hasSelection: false;
37
+ _keys: never;
38
+ _aliases: {};
39
+ _single: false;
40
+ _intersectProps: {};
41
+ _unionProps: never;
42
+ }[]>;
43
+ declare function transaction<TResult = any>(scope: (trx: Knex$1.Transaction<any, any>) => Promise<TResult> | void, config?: any): Promise<TResult>;
44
+ declare function raw<TResult = any>(sql: string, bindings?: Knex$1.RawBinding[] | Knex$1.ValueDict): Promise<Knex$1.Raw<TResult>>;
45
+
46
+ export { Knex, KnexConfig, query, raw, transaction, useKnex };
package/dist/index.js ADDED
@@ -0,0 +1,180 @@
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 __markAsModule = (target) => __defProp(target, "__esModule", { value: true });
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __reExport = (target, module2, copyDefault, desc) => {
13
+ if (module2 && typeof module2 === "object" || typeof module2 === "function") {
14
+ for (let key of __getOwnPropNames(module2))
15
+ if (!__hasOwnProp.call(target, key) && (copyDefault || key !== "default"))
16
+ __defProp(target, key, { get: () => module2[key], enumerable: !(desc = __getOwnPropDesc(module2, key)) || desc.enumerable });
17
+ }
18
+ return target;
19
+ };
20
+ var __toESM = (module2, isNodeMode) => {
21
+ return __reExport(__markAsModule(__defProp(module2 != null ? __create(__getProtoOf(module2)) : {}, "default", !isNodeMode && module2 && module2.__esModule ? { get: () => module2.default, enumerable: true } : { value: module2, enumerable: true })), module2);
22
+ };
23
+ var __toCommonJS = /* @__PURE__ */ ((cache) => {
24
+ return (module2, temp) => {
25
+ return cache && cache.get(module2) || (temp = __reExport(__markAsModule({}), module2, 1), cache && cache.set(module2, temp), temp);
26
+ };
27
+ })(typeof WeakMap !== "undefined" ? /* @__PURE__ */ new WeakMap() : 0);
28
+
29
+ // src/index.ts
30
+ var src_exports = {};
31
+ __export(src_exports, {
32
+ Knex: () => Knex,
33
+ query: () => query,
34
+ raw: () => raw,
35
+ transaction: () => transaction,
36
+ useKnex: () => useKnex
37
+ });
38
+ var import_func = require("@faasjs/func");
39
+ var import_logger = require("@faasjs/logger");
40
+ var import_deep_merge = require("@faasjs/deep_merge");
41
+ var import_knex = __toESM(require("knex"));
42
+ var Name = "knex";
43
+ if (!global["FaasJS_Knex"]) {
44
+ global.FaasJS_Knex = {};
45
+ }
46
+ var Knex = class {
47
+ constructor(config) {
48
+ this.type = Name;
49
+ this.name = Name;
50
+ if (config) {
51
+ this.name = config.name || this.type;
52
+ this.config = config.config || Object.create(null);
53
+ } else {
54
+ this.name = this.type;
55
+ this.config = Object.create(null);
56
+ }
57
+ this.logger = new import_logger.Logger(this.name);
58
+ }
59
+ async onDeploy(data, next) {
60
+ const client = data.config.plugins[this.name].config.client;
61
+ if (!client)
62
+ throw Error("[Knex] client required.");
63
+ data.dependencies[client] = "*";
64
+ this.logger.debug("add dependencies: " + client);
65
+ await next();
66
+ }
67
+ async onMount(data, next) {
68
+ var _a;
69
+ if (global.FaasJS_Knex[this.name]) {
70
+ this.config = global.FaasJS_Knex[this.name].config;
71
+ this.adapter = global.FaasJS_Knex[this.name].adapter;
72
+ this.query = this.adapter;
73
+ await next();
74
+ return;
75
+ }
76
+ const prefix = `SECRET_${this.name.toUpperCase()}_`;
77
+ for (let key in process.env)
78
+ if (key.startsWith(prefix)) {
79
+ const value = process.env[key];
80
+ key = key.replace(prefix, "").toLowerCase();
81
+ if (typeof this.config[key] === "undefined")
82
+ if (key.startsWith("connection_")) {
83
+ if (!this.config.connection) {
84
+ this.config.connection = Object.create(null);
85
+ }
86
+ this.config.connection[key.replace("connection_", "")] = value;
87
+ } else
88
+ this.config[key] = value;
89
+ }
90
+ if (data.config.plugins && ((_a = data.config.plugins[this.name]) == null ? void 0 : _a.config))
91
+ this.config = (0, import_deep_merge.deepMerge)(data.config.plugins[this.name].config, this.config);
92
+ this.adapter = (0, import_knex.default)(this.config);
93
+ if (this.config.client === "pg") {
94
+ const pg = require("pg");
95
+ const intTypes = [
96
+ "INT2",
97
+ "INT4",
98
+ "INT8"
99
+ ];
100
+ intTypes.forEach((t) => pg.types.setTypeParser(pg.types.builtins[t], (v) => parseInt(v)));
101
+ const floatTypes = [
102
+ "FLOAT4",
103
+ "FLOAT8",
104
+ "NUMERIC"
105
+ ];
106
+ floatTypes.forEach((t) => pg.types.setTypeParser(pg.types.builtins[t], (v) => parseFloat(v)));
107
+ }
108
+ this.adapter.on("query", ({
109
+ sql,
110
+ __knexQueryUid,
111
+ bindings
112
+ }) => {
113
+ this.logger.time(`Knex${__knexQueryUid}`);
114
+ this.logger.debug("query begin: %s %j", sql, bindings);
115
+ }).on("query-response", (response, {
116
+ sql,
117
+ __knexQueryUid,
118
+ bindings
119
+ }) => {
120
+ this.logger.timeEnd(`Knex${__knexQueryUid}`, "query done: %s %j %j", sql, bindings, response);
121
+ }).on("query-error", (_, {
122
+ __knexQueryUid,
123
+ sql,
124
+ bindings
125
+ }) => {
126
+ this.logger.timeEnd(`Knex${__knexQueryUid}`, "query failed: %s %j", sql, bindings);
127
+ });
128
+ this.query = this.adapter;
129
+ this.logger.debug("connected");
130
+ global.FaasJS_Knex[this.name] = this;
131
+ await next();
132
+ }
133
+ async raw(sql, bindings = []) {
134
+ if (!this.adapter)
135
+ throw Error("[Knex] Client not inited.");
136
+ return this.adapter.raw(sql, bindings);
137
+ }
138
+ async transaction(scope, config) {
139
+ if (!this.adapter)
140
+ throw Error("[Knex] Client not inited.");
141
+ return this.adapter.transaction(scope, config);
142
+ }
143
+ schema() {
144
+ if (!this.adapter)
145
+ throw Error("[Knex] Client not inited.");
146
+ return this.adapter.schema;
147
+ }
148
+ async quit() {
149
+ try {
150
+ await global.FaasJS_Knex[this.name].adapter.destroy();
151
+ delete global.FaasJS_Knex[this.name];
152
+ } catch (error) {
153
+ console.error(error);
154
+ }
155
+ }
156
+ };
157
+ function useKnex(config) {
158
+ const name = (config == null ? void 0 : config.name) || Name;
159
+ if (global.FaasJS_Knex[name])
160
+ return (0, import_func.usePlugin)(global.FaasJS_Knex[name]);
161
+ return (0, import_func.usePlugin)(new Knex(config));
162
+ }
163
+ function query(table) {
164
+ return useKnex().query(table);
165
+ }
166
+ async function transaction(scope, config) {
167
+ return useKnex().transaction(scope, config);
168
+ }
169
+ async function raw(sql, bindings = []) {
170
+ return useKnex().raw(sql, bindings);
171
+ }
172
+ module.exports = __toCommonJS(src_exports);
173
+ // Annotate the CommonJS export names for ESM import in node:
174
+ 0 && (module.exports = {
175
+ Knex,
176
+ query,
177
+ raw,
178
+ transaction,
179
+ useKnex
180
+ });
package/dist/index.mjs ADDED
@@ -0,0 +1,152 @@
1
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
2
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
3
+ }) : x)(function(x) {
4
+ if (typeof require !== "undefined")
5
+ return require.apply(this, arguments);
6
+ throw new Error('Dynamic require of "' + x + '" is not supported');
7
+ });
8
+
9
+ // src/index.ts
10
+ import {
11
+ usePlugin
12
+ } from "@faasjs/func";
13
+ import { Logger } from "@faasjs/logger";
14
+ import { deepMerge } from "@faasjs/deep_merge";
15
+ import knex from "knex";
16
+ var Name = "knex";
17
+ if (!global["FaasJS_Knex"]) {
18
+ global.FaasJS_Knex = {};
19
+ }
20
+ var Knex = class {
21
+ constructor(config) {
22
+ this.type = Name;
23
+ this.name = Name;
24
+ if (config) {
25
+ this.name = config.name || this.type;
26
+ this.config = config.config || Object.create(null);
27
+ } else {
28
+ this.name = this.type;
29
+ this.config = Object.create(null);
30
+ }
31
+ this.logger = new Logger(this.name);
32
+ }
33
+ async onDeploy(data, next) {
34
+ const client = data.config.plugins[this.name].config.client;
35
+ if (!client)
36
+ throw Error("[Knex] client required.");
37
+ data.dependencies[client] = "*";
38
+ this.logger.debug("add dependencies: " + client);
39
+ await next();
40
+ }
41
+ async onMount(data, next) {
42
+ var _a;
43
+ if (global.FaasJS_Knex[this.name]) {
44
+ this.config = global.FaasJS_Knex[this.name].config;
45
+ this.adapter = global.FaasJS_Knex[this.name].adapter;
46
+ this.query = this.adapter;
47
+ await next();
48
+ return;
49
+ }
50
+ const prefix = `SECRET_${this.name.toUpperCase()}_`;
51
+ for (let key in process.env)
52
+ if (key.startsWith(prefix)) {
53
+ const value = process.env[key];
54
+ key = key.replace(prefix, "").toLowerCase();
55
+ if (typeof this.config[key] === "undefined")
56
+ if (key.startsWith("connection_")) {
57
+ if (!this.config.connection) {
58
+ this.config.connection = Object.create(null);
59
+ }
60
+ this.config.connection[key.replace("connection_", "")] = value;
61
+ } else
62
+ this.config[key] = value;
63
+ }
64
+ if (data.config.plugins && ((_a = data.config.plugins[this.name]) == null ? void 0 : _a.config))
65
+ this.config = deepMerge(data.config.plugins[this.name].config, this.config);
66
+ this.adapter = knex(this.config);
67
+ if (this.config.client === "pg") {
68
+ const pg = __require("pg");
69
+ const intTypes = [
70
+ "INT2",
71
+ "INT4",
72
+ "INT8"
73
+ ];
74
+ intTypes.forEach((t) => pg.types.setTypeParser(pg.types.builtins[t], (v) => parseInt(v)));
75
+ const floatTypes = [
76
+ "FLOAT4",
77
+ "FLOAT8",
78
+ "NUMERIC"
79
+ ];
80
+ floatTypes.forEach((t) => pg.types.setTypeParser(pg.types.builtins[t], (v) => parseFloat(v)));
81
+ }
82
+ this.adapter.on("query", ({
83
+ sql,
84
+ __knexQueryUid,
85
+ bindings
86
+ }) => {
87
+ this.logger.time(`Knex${__knexQueryUid}`);
88
+ this.logger.debug("query begin: %s %j", sql, bindings);
89
+ }).on("query-response", (response, {
90
+ sql,
91
+ __knexQueryUid,
92
+ bindings
93
+ }) => {
94
+ this.logger.timeEnd(`Knex${__knexQueryUid}`, "query done: %s %j %j", sql, bindings, response);
95
+ }).on("query-error", (_, {
96
+ __knexQueryUid,
97
+ sql,
98
+ bindings
99
+ }) => {
100
+ this.logger.timeEnd(`Knex${__knexQueryUid}`, "query failed: %s %j", sql, bindings);
101
+ });
102
+ this.query = this.adapter;
103
+ this.logger.debug("connected");
104
+ global.FaasJS_Knex[this.name] = this;
105
+ await next();
106
+ }
107
+ async raw(sql, bindings = []) {
108
+ if (!this.adapter)
109
+ throw Error("[Knex] Client not inited.");
110
+ return this.adapter.raw(sql, bindings);
111
+ }
112
+ async transaction(scope, config) {
113
+ if (!this.adapter)
114
+ throw Error("[Knex] Client not inited.");
115
+ return this.adapter.transaction(scope, config);
116
+ }
117
+ schema() {
118
+ if (!this.adapter)
119
+ throw Error("[Knex] Client not inited.");
120
+ return this.adapter.schema;
121
+ }
122
+ async quit() {
123
+ try {
124
+ await global.FaasJS_Knex[this.name].adapter.destroy();
125
+ delete global.FaasJS_Knex[this.name];
126
+ } catch (error) {
127
+ console.error(error);
128
+ }
129
+ }
130
+ };
131
+ function useKnex(config) {
132
+ const name = (config == null ? void 0 : config.name) || Name;
133
+ if (global.FaasJS_Knex[name])
134
+ return usePlugin(global.FaasJS_Knex[name]);
135
+ return usePlugin(new Knex(config));
136
+ }
137
+ function query(table) {
138
+ return useKnex().query(table);
139
+ }
140
+ async function transaction(scope, config) {
141
+ return useKnex().transaction(scope, config);
142
+ }
143
+ async function raw(sql, bindings = []) {
144
+ return useKnex().raw(sql, bindings);
145
+ }
146
+ export {
147
+ Knex,
148
+ query,
149
+ raw,
150
+ transaction,
151
+ useKnex
152
+ };
package/package.json CHANGED
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "name": "@faasjs/knex",
3
- "version": "0.0.2-beta.302",
3
+ "version": "0.0.2-beta.320",
4
4
  "license": "MIT",
5
- "main": "lib/index.js",
6
- "types": "lib/index.d.ts",
7
- "module": "lib/index.es.js",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "module": "dist/index.mjs",
8
8
  "homepage": "https://faasjs.com/doc/knex.html",
9
9
  "repository": {
10
10
  "type": "git",
@@ -16,33 +16,30 @@
16
16
  },
17
17
  "funding": "https://github.com/sponsors/faasjs",
18
18
  "scripts": {
19
- "prepack": "rm -rf ./lib && rollup -c && mv lib/*/src/* lib/"
19
+ "build": "rm -rf ./dist && tsup-node src/index.ts --format esm,cjs --dts"
20
20
  },
21
21
  "files": [
22
- "lib"
22
+ "dist"
23
23
  ],
24
24
  "peerDependencies": {
25
- "@faasjs/deep_merge": "^0.0.2-beta.244",
26
- "@faasjs/logger": "^0.0.2-beta.243",
25
+ "@faasjs/deep_merge": "^0.0.2-beta.320",
26
+ "@faasjs/func": "^0.0.2-beta.320",
27
+ "@faasjs/logger": "^0.0.2-beta.320",
27
28
  "knex": "*"
28
29
  },
29
30
  "devDependencies": {
30
- "@faasjs/func": "^0.0.2-beta.302",
31
- "@types/debug": "*",
32
- "@types/jest": "*",
33
31
  "@types/mysql": "*",
34
32
  "@types/node": "*",
35
33
  "@types/pg": "*",
36
34
  "@types/sqlite3": "*",
37
35
  "mysql": "*",
38
36
  "pg": "*",
39
- "rollup": "*",
40
- "rollup-plugin-typescript2": "*",
41
37
  "sqlite3": "*",
38
+ "tsup": "*",
42
39
  "typescript": "*"
43
40
  },
44
41
  "engines": {
45
42
  "npm": ">=8.0.0"
46
43
  },
47
- "gitHead": "b53fb35a91369afd0185fb555d98e5c9d90b54bd"
44
+ "gitHead": "4a9f699171ad7e20d922e68b74418d1ec5b7d016"
48
45
  }
package/lib/index.d.ts DELETED
@@ -1,43 +0,0 @@
1
- import { Plugin, Next, DeployData, MountData, UseifyPlugin } from '@faasjs/func';
2
- import { Logger } from '@faasjs/logger';
3
- import { Knex as K } from 'knex';
4
- export declare type KnexConfig = {
5
- name?: string;
6
- config?: K.Config;
7
- };
8
- /**
9
- * Knex 插件
10
- */
11
- export declare class Knex implements Plugin {
12
- readonly type: string;
13
- readonly name: string;
14
- config: K.Config;
15
- adapter: K;
16
- query: K;
17
- logger: Logger;
18
- /**
19
- * 创建插件实例
20
- * @param config {object} 配置
21
- * @param config.name {string} 配置名
22
- * @param config.config {object} 数据库配置
23
- */
24
- constructor(config?: KnexConfig);
25
- onDeploy(data: DeployData, next: Next): Promise<void>;
26
- onMount(data: MountData, next: Next): Promise<void>;
27
- raw<TResult = any>(sql: string, bindings?: K.RawBinding[] | K.ValueDict): Promise<K.Raw<TResult>>;
28
- transaction<TResult = any>(scope: (trx: K.Transaction<any, any>) => Promise<TResult> | void, config?: any): Promise<TResult>;
29
- schema(): K.SchemaBuilder;
30
- quit(): Promise<void>;
31
- }
32
- export declare function useKnex(config?: KnexConfig): Knex & UseifyPlugin;
33
- export declare function query<TName extends K.TableNames>(table: TName): K.QueryBuilder<K.TableType<TName>, {
34
- _base: K.ResolveTableType<K.TableType<TName>, "base">;
35
- _hasSelection: false;
36
- _keys: never;
37
- _aliases: {};
38
- _single: false;
39
- _intersectProps: {};
40
- _unionProps: never;
41
- }[]>;
42
- export declare function transaction<TResult = any>(scope: (trx: K.Transaction<any, any>) => Promise<TResult> | void, config?: any): Promise<TResult>;
43
- export declare function raw<TResult = any>(sql: string, bindings?: K.RawBinding[] | K.ValueDict): Promise<K.Raw<TResult>>;
package/lib/index.es.js DELETED
@@ -1,141 +0,0 @@
1
- import { usePlugin } from '@faasjs/func';
2
- import { Logger } from '@faasjs/logger';
3
- import { deepMerge } from '@faasjs/deep_merge';
4
- import knex from 'knex';
5
-
6
- const Name = 'knex';
7
- if (!global['FaasJS_Knex']) {
8
- global.FaasJS_Knex = {};
9
- }
10
- /**
11
- * Knex 插件
12
- */
13
- class Knex {
14
- /**
15
- * 创建插件实例
16
- * @param config {object} 配置
17
- * @param config.name {string} 配置名
18
- * @param config.config {object} 数据库配置
19
- */
20
- constructor(config) {
21
- this.type = Name;
22
- this.name = Name;
23
- if (config) {
24
- this.name = config.name || this.type;
25
- this.config = (config.config) || Object.create(null);
26
- }
27
- else {
28
- this.name = this.type;
29
- this.config = Object.create(null);
30
- }
31
- this.logger = new Logger(this.name);
32
- }
33
- async onDeploy(data, next) {
34
- const client = data.config.plugins[this.name].config.client;
35
- if (!client)
36
- throw Error('[Knex] client required.');
37
- data.dependencies[client] = '*';
38
- this.logger.debug('add dependencies: ' + client);
39
- await next();
40
- }
41
- async onMount(data, next) {
42
- var _a;
43
- if (global.FaasJS_Knex[this.name]) {
44
- this.config = global.FaasJS_Knex[this.name].config;
45
- this.adapter = global.FaasJS_Knex[this.name].adapter;
46
- this.query = this.adapter;
47
- await next();
48
- return;
49
- }
50
- const prefix = `SECRET_${this.name.toUpperCase()}_`;
51
- for (let key in process.env)
52
- if (key.startsWith(prefix)) {
53
- const value = process.env[key];
54
- key = key.replace(prefix, '').toLowerCase();
55
- if (typeof this.config[key] === 'undefined')
56
- if (key.startsWith('connection_')) {
57
- if (!this.config.connection) {
58
- this.config.connection = Object.create(null);
59
- }
60
- this.config.connection[key.replace('connection_', '')] = value;
61
- }
62
- else
63
- this.config[key] = value;
64
- }
65
- if (data.config.plugins && ((_a = data.config.plugins[this.name]) === null || _a === void 0 ? void 0 : _a.config))
66
- this.config = deepMerge(data.config.plugins[this.name].config, this.config);
67
- this.adapter = knex(this.config);
68
- if (this.config.client === 'pg') {
69
- // eslint-disable-next-line @typescript-eslint/no-var-requires
70
- const pg = require('pg');
71
- const intTypes = [
72
- 'INT2',
73
- 'INT4',
74
- 'INT8'
75
- ];
76
- intTypes.forEach(t => pg.types.setTypeParser(pg.types.builtins[t], (v) => parseInt(v)));
77
- const floatTypes = [
78
- 'FLOAT4',
79
- 'FLOAT8',
80
- 'NUMERIC'
81
- ];
82
- floatTypes.forEach(t => pg.types.setTypeParser(pg.types.builtins[t], (v) => parseFloat(v)));
83
- }
84
- this.adapter
85
- .on('query', ({ sql, __knexQueryUid, bindings }) => {
86
- this.logger.time(`Knex${__knexQueryUid}`);
87
- this.logger.debug('query begin: %s %j', sql, bindings);
88
- })
89
- .on('query-response', (response, { sql, __knexQueryUid, bindings }) => {
90
- this.logger.timeEnd(`Knex${__knexQueryUid}`, 'query done: %s %j %j', sql, bindings, response);
91
- })
92
- .on('query-error', (_, { __knexQueryUid, sql, bindings }) => {
93
- this.logger.timeEnd(`Knex${__knexQueryUid}`, 'query failed: %s %j', sql, bindings);
94
- });
95
- this.query = this.adapter;
96
- this.logger.debug('connected');
97
- global.FaasJS_Knex[this.name] = this;
98
- await next();
99
- }
100
- async raw(sql, bindings = []) {
101
- if (!this.adapter)
102
- throw Error('[Knex] Client not inited.');
103
- return this.adapter.raw(sql, bindings);
104
- }
105
- async transaction(scope, config) {
106
- if (!this.adapter)
107
- throw Error('[Knex] Client not inited.');
108
- return this.adapter.transaction(scope, config);
109
- }
110
- schema() {
111
- if (!this.adapter)
112
- throw Error('[Knex] Client not inited.');
113
- return this.adapter.schema;
114
- }
115
- async quit() {
116
- try {
117
- await global.FaasJS_Knex[this.name].adapter.destroy();
118
- delete global.FaasJS_Knex[this.name];
119
- }
120
- catch (error) {
121
- console.error(error);
122
- }
123
- }
124
- }
125
- function useKnex(config) {
126
- const name = (config === null || config === void 0 ? void 0 : config.name) || Name;
127
- if (global.FaasJS_Knex[name])
128
- return usePlugin(global.FaasJS_Knex[name]);
129
- return usePlugin(new Knex(config));
130
- }
131
- function query(table) {
132
- return useKnex().query(table);
133
- }
134
- async function transaction(scope, config) {
135
- return useKnex().transaction(scope, config);
136
- }
137
- async function raw(sql, bindings = []) {
138
- return useKnex().raw(sql, bindings);
139
- }
140
-
141
- export { Knex, query, raw, transaction, useKnex };
package/lib/index.js DELETED
@@ -1,153 +0,0 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- var func = require('@faasjs/func');
6
- var logger = require('@faasjs/logger');
7
- var deep_merge = require('@faasjs/deep_merge');
8
- var knex = require('knex');
9
-
10
- function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
11
-
12
- var knex__default = /*#__PURE__*/_interopDefaultLegacy(knex);
13
-
14
- const Name = 'knex';
15
- if (!global['FaasJS_Knex']) {
16
- global.FaasJS_Knex = {};
17
- }
18
- /**
19
- * Knex 插件
20
- */
21
- class Knex {
22
- /**
23
- * 创建插件实例
24
- * @param config {object} 配置
25
- * @param config.name {string} 配置名
26
- * @param config.config {object} 数据库配置
27
- */
28
- constructor(config) {
29
- this.type = Name;
30
- this.name = Name;
31
- if (config) {
32
- this.name = config.name || this.type;
33
- this.config = (config.config) || Object.create(null);
34
- }
35
- else {
36
- this.name = this.type;
37
- this.config = Object.create(null);
38
- }
39
- this.logger = new logger.Logger(this.name);
40
- }
41
- async onDeploy(data, next) {
42
- const client = data.config.plugins[this.name].config.client;
43
- if (!client)
44
- throw Error('[Knex] client required.');
45
- data.dependencies[client] = '*';
46
- this.logger.debug('add dependencies: ' + client);
47
- await next();
48
- }
49
- async onMount(data, next) {
50
- var _a;
51
- if (global.FaasJS_Knex[this.name]) {
52
- this.config = global.FaasJS_Knex[this.name].config;
53
- this.adapter = global.FaasJS_Knex[this.name].adapter;
54
- this.query = this.adapter;
55
- await next();
56
- return;
57
- }
58
- const prefix = `SECRET_${this.name.toUpperCase()}_`;
59
- for (let key in process.env)
60
- if (key.startsWith(prefix)) {
61
- const value = process.env[key];
62
- key = key.replace(prefix, '').toLowerCase();
63
- if (typeof this.config[key] === 'undefined')
64
- if (key.startsWith('connection_')) {
65
- if (!this.config.connection) {
66
- this.config.connection = Object.create(null);
67
- }
68
- this.config.connection[key.replace('connection_', '')] = value;
69
- }
70
- else
71
- this.config[key] = value;
72
- }
73
- if (data.config.plugins && ((_a = data.config.plugins[this.name]) === null || _a === void 0 ? void 0 : _a.config))
74
- this.config = deep_merge.deepMerge(data.config.plugins[this.name].config, this.config);
75
- this.adapter = knex__default["default"](this.config);
76
- if (this.config.client === 'pg') {
77
- // eslint-disable-next-line @typescript-eslint/no-var-requires
78
- const pg = require('pg');
79
- const intTypes = [
80
- 'INT2',
81
- 'INT4',
82
- 'INT8'
83
- ];
84
- intTypes.forEach(t => pg.types.setTypeParser(pg.types.builtins[t], (v) => parseInt(v)));
85
- const floatTypes = [
86
- 'FLOAT4',
87
- 'FLOAT8',
88
- 'NUMERIC'
89
- ];
90
- floatTypes.forEach(t => pg.types.setTypeParser(pg.types.builtins[t], (v) => parseFloat(v)));
91
- }
92
- this.adapter
93
- .on('query', ({ sql, __knexQueryUid, bindings }) => {
94
- this.logger.time(`Knex${__knexQueryUid}`);
95
- this.logger.debug('query begin: %s %j', sql, bindings);
96
- })
97
- .on('query-response', (response, { sql, __knexQueryUid, bindings }) => {
98
- this.logger.timeEnd(`Knex${__knexQueryUid}`, 'query done: %s %j %j', sql, bindings, response);
99
- })
100
- .on('query-error', (_, { __knexQueryUid, sql, bindings }) => {
101
- this.logger.timeEnd(`Knex${__knexQueryUid}`, 'query failed: %s %j', sql, bindings);
102
- });
103
- this.query = this.adapter;
104
- this.logger.debug('connected');
105
- global.FaasJS_Knex[this.name] = this;
106
- await next();
107
- }
108
- async raw(sql, bindings = []) {
109
- if (!this.adapter)
110
- throw Error('[Knex] Client not inited.');
111
- return this.adapter.raw(sql, bindings);
112
- }
113
- async transaction(scope, config) {
114
- if (!this.adapter)
115
- throw Error('[Knex] Client not inited.');
116
- return this.adapter.transaction(scope, config);
117
- }
118
- schema() {
119
- if (!this.adapter)
120
- throw Error('[Knex] Client not inited.');
121
- return this.adapter.schema;
122
- }
123
- async quit() {
124
- try {
125
- await global.FaasJS_Knex[this.name].adapter.destroy();
126
- delete global.FaasJS_Knex[this.name];
127
- }
128
- catch (error) {
129
- console.error(error);
130
- }
131
- }
132
- }
133
- function useKnex(config) {
134
- const name = (config === null || config === void 0 ? void 0 : config.name) || Name;
135
- if (global.FaasJS_Knex[name])
136
- return func.usePlugin(global.FaasJS_Knex[name]);
137
- return func.usePlugin(new Knex(config));
138
- }
139
- function query(table) {
140
- return useKnex().query(table);
141
- }
142
- async function transaction(scope, config) {
143
- return useKnex().transaction(scope, config);
144
- }
145
- async function raw(sql, bindings = []) {
146
- return useKnex().raw(sql, bindings);
147
- }
148
-
149
- exports.Knex = Knex;
150
- exports.query = query;
151
- exports.raw = raw;
152
- exports.transaction = transaction;
153
- exports.useKnex = useKnex;