@axiosleo/orm-mysql 0.0.1

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/.eslintrc ADDED
@@ -0,0 +1,114 @@
1
+ {
2
+ "rules": {
3
+ "indent": [
4
+ 2,
5
+ 2,
6
+ {
7
+ "SwitchCase": 1
8
+ }
9
+ ],
10
+ "quotes": [
11
+ 2,
12
+ "single"
13
+ ],
14
+ "linebreak-style": [
15
+ 2,
16
+ "unix"
17
+ ],
18
+ "semi": [
19
+ 2,
20
+ "always"
21
+ ],
22
+ "strict": [
23
+ 2,
24
+ "global"
25
+ ],
26
+ "curly": 2,
27
+ "eqeqeq": 2,
28
+ "no-eval": 2,
29
+ "guard-for-in": 2,
30
+ "no-caller": 2,
31
+ "no-else-return": 2,
32
+ "no-eq-null": 2,
33
+ "no-extend-native": 2,
34
+ "no-extra-bind": 2,
35
+ "no-floating-decimal": 2,
36
+ "no-implied-eval": 2,
37
+ "no-labels": 2,
38
+ "no-with": 2,
39
+ "no-loop-func": 2,
40
+ "no-native-reassign": 2,
41
+ "no-redeclare": [
42
+ 2,
43
+ {
44
+ "builtinGlobals": true
45
+ }
46
+ ],
47
+ "no-delete-var": 2,
48
+ "no-shadow-restricted-names": 2,
49
+ "no-undef-init": 2,
50
+ "no-use-before-define": 2,
51
+ "no-unused-vars": [
52
+ 2,
53
+ {
54
+ "args": "none"
55
+ }
56
+ ],
57
+ "no-undefined": 2,
58
+ "no-undef": 2,
59
+ "global-require": 0,
60
+ "no-console": 2,
61
+ "key-spacing": [
62
+ 2,
63
+ {
64
+ "beforeColon": false,
65
+ "afterColon": true
66
+ }
67
+ ],
68
+ "eol-last": [
69
+ 2,
70
+ "always"
71
+ ],
72
+ "no-inner-declarations": [
73
+ 1
74
+ ],
75
+ "no-case-declarations": [
76
+ 1
77
+ ],
78
+ "no-multiple-empty-lines": [
79
+ 2,
80
+ {
81
+ "max": 1,
82
+ "maxBOF": 1
83
+ }
84
+ ],
85
+ "space-in-parens": [
86
+ 2,
87
+ "never"
88
+ ],
89
+ "no-multi-spaces": [
90
+ 2,
91
+ {
92
+ "ignoreEOLComments": true
93
+ }
94
+ ]
95
+ },
96
+ "env": {
97
+ "es6": true,
98
+ "node": true,
99
+ "browser": true
100
+ },
101
+ "globals": {
102
+ "describe": true,
103
+ "it": true,
104
+ "before": true,
105
+ "after": true,
106
+ "beforeEach": true
107
+ },
108
+ "parserOptions": {
109
+ "ecmaVersion": 2018,
110
+ "sourceType": "script",
111
+ "ecmaFeatures": {}
112
+ },
113
+ "extends": "eslint:recommended"
114
+ }
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022 AxiosLeo
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,2 @@
1
+ # node-orm-mysql
2
+ MySQL ORM tool
package/index.d.ts ADDED
@@ -0,0 +1,120 @@
1
+ import {
2
+ OkPacket,
3
+ Connection,
4
+ QueryOptions,
5
+ RowDataPacket,
6
+ ConnectionOptions
7
+ } from 'mysql2';
8
+
9
+ type Clients = {
10
+ [key: string]: Connection
11
+ }
12
+
13
+ type ConditionValueType = null | string | number | boolean | Date | Array<string | number | boolean | Date>;
14
+
15
+ type OptType = '=' | '!=' | '>' | '<' | '>=' | '<=' | 'LIKE'
16
+ | 'NOT LIKE' | 'IN' | 'NOT IN' | 'BETWEEN' | 'NOT BETWEEN' | 'IS' | 'IS NOT' | 'REGEXP' | 'NOT REGEXP'
17
+ | 'AND' | 'OR' | 'GROUP' | 'like' | 'not like' | 'in' | 'not in' | 'between' | 'not between' | 'is' | 'is not' | 'regexp' | 'not regexp' | 'group';
18
+
19
+ interface WhereOptions {
20
+ key: string | null;
21
+ opt: OptType;
22
+ value: ConditionValueType | WhereOptions[];
23
+ }
24
+
25
+ interface OrderByOptions {
26
+ sortField: string,
27
+ sortOrder: 'asc' | 'desc'
28
+ }
29
+
30
+ type OperatorType = 'select' | 'find' | 'insert' | 'update' | 'delete' | 'count';
31
+
32
+ interface JoinOption {
33
+ table: string;
34
+ alias: string;
35
+ on: string;
36
+ type: 'left' | 'right' | 'inner';
37
+ }
38
+
39
+ interface TableOption {
40
+ tableName: string;
41
+ alias: string | null;
42
+ }
43
+
44
+ interface QueryOperatorOptions {
45
+ sql: string;
46
+ values: any[];
47
+ conditions: WhereOptions[];
48
+ attrs?: string[] | null;
49
+ orders: OrderByOptions[];
50
+ pageLimit?: number;
51
+ pageOffset?: number;
52
+ tables: TableOption[];
53
+ operator: OperatorType | null;
54
+ data: any | null;
55
+ groupField: string[];
56
+ joins: JoinOption[]
57
+ }
58
+
59
+ export declare class QueryOperator {
60
+ conn: Connection;
61
+ options: QueryOperatorOptions
62
+
63
+ constructor(conn: Connection, table: TableOption);
64
+
65
+ table(tableName: string, alias: string | null): this;
66
+
67
+ limit(limit: number): this;
68
+
69
+ offset(offset: number): this;
70
+
71
+ where(key: string | null, value: ConditionValueType | WhereOptions[], opt?: OptType): this;
72
+
73
+ whereConditions(...condition: WhereOptions[]): this;
74
+
75
+ orWhere(key: string | null, opt: OptType, value: ConditionValueType | WhereOptions[]): this;
76
+
77
+ andWhere(key: string | null, opt: OptType, value: ConditionValueType | WhereOptions[]): this;
78
+
79
+ attr(...attr: string[]): this;
80
+
81
+ orderBy(sortField: string, sortOrder: 'asc' | 'desc'): this;
82
+
83
+ groupBy(...groupField: string[]): this;
84
+
85
+ page(limit: number, offset?: number): this;
86
+
87
+ set(data: any): this;
88
+
89
+ join(table: string, alias: string, on: string, type: 'left' | 'right' | 'inner'): this;
90
+
91
+ buildSql(operator: OperatorType): { sql: string, values: any[] };
92
+
93
+ exec(): Promise<any | undefined | RowDataPacket[] | RowDataPacket | OkPacket>;
94
+
95
+ select<T>(): Promise<T[]>;
96
+
97
+ find<T>(): Promise<T>;
98
+
99
+ update(data?: any): Promise<OkPacket>;
100
+
101
+ insert(data?: any): Promise<OkPacket>;
102
+
103
+ count(): Promise<number>;
104
+ }
105
+
106
+ export declare class QueryHandler {
107
+ conn: Connection;
108
+
109
+ constructor(conn: Connection);
110
+
111
+ table(table: string, alias?: string | null): QueryOperator;
112
+
113
+ query(options: QueryOptions): Promise<any>;
114
+
115
+ upsert(tableName: string, obj: any, condition: WhereOptions[]): Promise<OkPacket>;
116
+ }
117
+
118
+ export function createClient(options: ConnectionOptions): Connection;
119
+
120
+ export function getClient(name: string): Connection;
package/index.js ADDED
@@ -0,0 +1,16 @@
1
+ 'use strict';
2
+
3
+ const {
4
+ QueryHandler,
5
+ QueryOperator
6
+ } = require('./src/query');
7
+
8
+ const { createClient, getClient } = require('./src/client');
9
+
10
+ module.exports = {
11
+ QueryHandler,
12
+ QueryOperator,
13
+
14
+ getClient,
15
+ createClient
16
+ };
package/package.json ADDED
@@ -0,0 +1,50 @@
1
+ {
2
+ "name": "@axiosleo/orm-mysql",
3
+ "version": "0.0.1",
4
+ "description": "MySQL ORM tool",
5
+ "keywords": [
6
+ "mysql",
7
+ "orm"
8
+ ],
9
+ "author": "AxiosLeo",
10
+ "directories": {
11
+ "lib": "src"
12
+ },
13
+ "scripts": {
14
+ "lint": "tsc ./index.d.ts && eslint --fix src/",
15
+ "test": "mocha --reporter spec --timeout 3000 tests/*.tests.js",
16
+ "test-cov": "nyc -r=lcov -r=html -r=text -r=json mocha -t 10000 -R spec tests/*.tests.js",
17
+ "ci": "npm run lint && npm run test-cov",
18
+ "clear": "rm -rf ./nyc_output ./coverage"
19
+ },
20
+ "license": "MIT",
21
+ "dependencies": {
22
+ "@axiosleo/cli-tool": "^1.4.11",
23
+ "mysql2": "^2.3.3",
24
+ "validatorjs": "^3.22.1"
25
+ },
26
+ "repository": {
27
+ "type": "git",
28
+ "url": "https://github.com/AxiosLeo/node-orm-mysql"
29
+ },
30
+ "devDependencies": {
31
+ "@types/node": "^15.12.1",
32
+ "chai": "^4.2.0",
33
+ "chai-as-promised": "^7.1.1",
34
+ "eslint": "^7.0",
35
+ "expect.js": "^0.3.1",
36
+ "has-flag": "^4.0.0",
37
+ "mm": "^3.2.0",
38
+ "mocha": "^9.1.3",
39
+ "mocha-sinon": "^2.1.2",
40
+ "pre-commit": "^1.2.2",
41
+ "sinon": "^9.0.2",
42
+ "typescript": "^4.3.2"
43
+ },
44
+ "pre-commit": {
45
+ "silent": false,
46
+ "run": [
47
+ "lint"
48
+ ]
49
+ }
50
+ }
package/src/builder.js ADDED
@@ -0,0 +1,169 @@
1
+ 'use strict';
2
+
3
+ const is = require('@axiosleo/cli-tool/src/helper/is');
4
+
5
+ const _buildFieldKey = (key) => {
6
+ if (!key) {
7
+ return '';
8
+ }
9
+ return key.split('.').map((k) => `\`${k}\``).join('.');
10
+ };
11
+
12
+ const _buildContidion = (conditions, prefix) => {
13
+ const values = [];
14
+ let sql = typeof prefix === 'undefined' ? ' WHERE ' : '';
15
+ if (conditions.length) {
16
+ sql += `${conditions.map((c) => {
17
+ if (c.key === null && c.value === null) {
18
+ return ` ${c.opt} `;
19
+ }
20
+ if (c.value === null) {
21
+ return c.opt === '=' ? `ISNULL(${_buildFieldKey(c.key)})` : `!ISNULL(${_buildFieldKey(c.key)})`;
22
+ }
23
+ const opt = c.opt.toLowerCase();
24
+ if (opt === 'in' && Array.isArray(c.value)) {
25
+ values.push(c.value.join(','));
26
+ return `${_buildFieldKey(c.key)} IN (?)`;
27
+ } else if (opt === 'group' && Array.isArray(c.value)) {
28
+ const res = _buildContidion(c.value, '');
29
+ values.push(...res.values);
30
+ return `(${res.sql})`;
31
+ }
32
+ values.push(c.value);
33
+ return `${_buildFieldKey(c.key)} ${c.opt} ?`;
34
+ }).join('')}`;
35
+ }
36
+ return {
37
+ sql,
38
+ values
39
+ };
40
+ };
41
+
42
+ const _buildValues = (obj) => {
43
+ const fields = [];
44
+ const values = [];
45
+ Object.keys(obj).forEach((key) => {
46
+ fields.push(`${key}`);
47
+ if (obj[key] === null) {
48
+ values.push('NULL');
49
+ return;
50
+ }
51
+ if (Array.isArray(obj[key]) || is.object(obj[key])) {
52
+ values.push(JSON.stringify(obj[key]));
53
+ } else {
54
+ values.push(obj[key]);
55
+ }
56
+ });
57
+ return { fields, values };
58
+ };
59
+
60
+ const _buldPagenation = (limit, offset) => {
61
+ let sql = '';
62
+ if (limit) {
63
+ sql += ` LIMIT ${limit}`;
64
+ }
65
+ if (offset) {
66
+ sql += ` OFFSET ${offset}`;
67
+ }
68
+ return sql;
69
+ };
70
+
71
+ const _buildTables = (tables) => {
72
+ return tables.map((t) => {
73
+ if (t.alias) {
74
+ return `\`${t.tableName}\` AS \`${t.alias}\``;
75
+ }
76
+ return `\`${t.tableName}\``;
77
+ }).join(' , ');
78
+ };
79
+
80
+ const _buildOrders = (orders = []) => {
81
+ const sql = ' ORDER BY ' + orders.map((o) => {
82
+ return `\`${o.sortField}\` ${o.sortOrder}`;
83
+ }).join(',');
84
+ return sql;
85
+ };
86
+
87
+ const _buildJoins = (joins = []) => {
88
+ return joins.map((j) => {
89
+ switch (j.type) {
90
+ case 'left':
91
+ return ` LEFT JOIN \`${j.table}\` AS \`${j.alias}\` ON ${j.on}`;
92
+ case 'inner':
93
+ return ` INNER JOIN \`${j.table}\` AS \`${j.alias}\` ON ${j.on}`;
94
+ case 'right':
95
+ return ` RIGHT JOIN \`${j.table}\` AS \`${j.alias}\` ON ${j.on}`;
96
+ }
97
+ }).join(' ');
98
+ };
99
+
100
+ const buildSql = (options) => {
101
+ let sql = options.sql;
102
+ let values = options.values;
103
+ switch (options.operator) {
104
+ case 'find': {
105
+ options.pageLimit = 1;
106
+ options.pageOffset = 0;
107
+ }
108
+ // eslint-disable-next-line no-fallthrough
109
+ case 'select': {
110
+ sql = `SELECT ${options.attrs ? options.attrs.map((a) => _buildFieldKey(a)).join(',') : '*'} FROM ${_buildTables(options.tables)}`;
111
+ sql += _buildJoins(options.joins);
112
+ const res = _buildContidion(options.conditions);
113
+ sql += res.sql;
114
+ values = options.values.concat(res.values);
115
+ sql += options.orders.length > 0 ? _buildOrders(options.orders) : '';
116
+ sql += _buldPagenation(options.pageLimit, options.pageOffset);
117
+ if (options.groupField.length) {
118
+ sql += ` GROUP BY ${options.groupField.join(',')}`;
119
+ }
120
+ break;
121
+ }
122
+ case 'insert': {
123
+ const buildValueRes = _buildValues(options.data);
124
+ sql = `INSERT INTO ${_buildTables(options.tables)}(${buildValueRes.fields.map((f) => _buildFieldKey(f))}) VALUES (${buildValueRes.fields.map(() => '?').join(',')})`;
125
+ values = values.concat(buildValueRes.values);
126
+ break;
127
+ }
128
+ case 'update': {
129
+ const buildValueRes = _buildValues(options.data);
130
+ sql = `UPDATE ${_buildTables(options.tables)} SET ${buildValueRes.fields.map(f => `${_buildFieldKey(f)} = ?`).join(',')}`;
131
+ values = values.concat(values);
132
+ const buildConditionRes = _buildContidion(options.conditions);
133
+ sql += buildConditionRes.sql;
134
+ values = values.concat(buildConditionRes.values);
135
+ break;
136
+ }
137
+ case 'delete': {
138
+ sql = `DELETE FROM ${_buildTables(options.tables)}`;
139
+ if (!options.conditions.length) {
140
+ throw new Error('At least one where condition is required for delete operation');
141
+ }
142
+ const buildConditionRes = _buildContidion(options.conditions);
143
+ sql += buildConditionRes.sql;
144
+ values = values.concat(buildConditionRes.values);
145
+ break;
146
+ }
147
+ case 'count': {
148
+ sql = `SELECT COUNT(*) AS count FROM ${_buildTables(options.tables)}`;
149
+ const buildConditionRes = _buildContidion(options.conditions);
150
+ sql += buildConditionRes.sql;
151
+ values = values.concat(buildConditionRes.values);
152
+ if (options.groupField.length) {
153
+ sql += ` GROUP BY ${options.groupField.join(',')}`;
154
+ }
155
+ break;
156
+ }
157
+ default:
158
+ throw new Error('Invalid operator: ' + options.operator);
159
+ }
160
+
161
+ return {
162
+ sql,
163
+ values: values
164
+ };
165
+ };
166
+
167
+ module.exports = {
168
+ buildSql
169
+ };
package/src/client.js ADDED
@@ -0,0 +1,50 @@
1
+ 'use strict';
2
+
3
+ const mysql = require('mysql2');
4
+ const { validate } = require('./utils');
5
+
6
+ const clients = {};
7
+
8
+ /**
9
+ * initialize client
10
+ * @param {mysql.ConnectionOptions} options
11
+ * @returns {mysql.Connection}
12
+ */
13
+ const createClient = (options) => {
14
+ validate(options, {
15
+ name: 'string',
16
+ host: 'required|string',
17
+ user: 'required|string',
18
+ password: 'required|string',
19
+ port: 'required|integer',
20
+ database: 'required|string',
21
+ });
22
+ const key = options.name ? options.name :
23
+ `${options.host}:${options.port}:${options.user}:${options.password}:${options.database}`;
24
+ if (clients[key]) {
25
+ return clients[key];
26
+ }
27
+ clients[key] = mysql.createConnection(options);
28
+ clients[key].connect();
29
+ return clients[key];
30
+ };
31
+
32
+ /**
33
+ * get client
34
+ * @param {*} name
35
+ * @returns {mysql.Connection}
36
+ */
37
+ const getClient = (name) => {
38
+ if (!name) {
39
+ throw new Error('name is required');
40
+ }
41
+ if (!clients[name]) {
42
+ throw new Error(`client ${name} not found`);
43
+ }
44
+ return clients[name];
45
+ };
46
+
47
+ module.exports = {
48
+ getClient,
49
+ createClient
50
+ };
package/src/query.js ADDED
@@ -0,0 +1,231 @@
1
+ 'use strict';
2
+
3
+ const { buildSql } = require('./builder');
4
+
5
+ const query = async (conn, options) => {
6
+ return new Promise((resolve, reject) => {
7
+ conn.query(options, (err, result) => {
8
+ if (err) {
9
+ reject(err);
10
+ } else {
11
+ resolve(result);
12
+ }
13
+ });
14
+ });
15
+ };
16
+
17
+ class QueryOperator {
18
+ /**
19
+ *
20
+ * @param {*} conn
21
+ * @param {TableOption} table
22
+ */
23
+ constructor(conn, table) {
24
+ this.conn = conn;
25
+ this.options = {
26
+ sql: '',
27
+ values: [],
28
+ conditions: [],
29
+ orders: [],
30
+ tables: [],
31
+ operator: null,
32
+ data: null,
33
+ groupField: [],
34
+ };
35
+ this.options.tables.push(table);
36
+ }
37
+
38
+ table(tableName, alias) {
39
+ this.options.tables.push({ tableName, alias });
40
+ return this;
41
+ }
42
+
43
+ limit(limit) {
44
+ this.options.pageLimit = limit;
45
+ return this;
46
+ }
47
+
48
+ offset(offset) {
49
+ this.options.pageOffset = offset;
50
+ return this;
51
+ }
52
+
53
+ where(key, value, opt = '=') {
54
+ if (this.options.conditions.length) {
55
+ this.options.conditions.push({ key: null, opt: 'AND', value: null });
56
+ }
57
+ this.options.conditions.push({
58
+ key, opt, value,
59
+ });
60
+ return this;
61
+ }
62
+
63
+ whereConditions(...condition) {
64
+ if (this.options.conditions.length) {
65
+ this.options.conditions.push({ key: null, opt: 'AND', value: null });
66
+ }
67
+ condition.forEach((c) => {
68
+ this.options.conditions.push(c);
69
+ });
70
+ return this;
71
+ }
72
+
73
+ orWhere(key, opt, value) {
74
+ if (!this.options.conditions.length) {
75
+ throw new Error('At least one where condition is required');
76
+ }
77
+ this.options.conditions.push({
78
+ key: null,
79
+ opt: 'OR',
80
+ value: null
81
+ }, { key, opt, value });
82
+ return this;
83
+ }
84
+
85
+ andWhere(key, opt, value) {
86
+ if (!this.options.conditions.length) {
87
+ throw new Error('At least one where condition is required');
88
+ }
89
+ this.options.conditions.push({
90
+ key: null,
91
+ opt: 'AND',
92
+ value: null
93
+ }, { key, opt, value });
94
+ return this;
95
+ }
96
+
97
+ attr(...attr) {
98
+ if (!this.options.attrs) {
99
+ this.options.attrs = [];
100
+ }
101
+ this.options.attrs.push(...attr);
102
+ return this;
103
+ }
104
+
105
+ orderBy(sortField, sortOrder) {
106
+ this.options.orders.push({ sortField, sortOrder });
107
+ return this;
108
+ }
109
+
110
+ groupBy(...groupField) {
111
+ this.options.groupField.push(...groupField);
112
+ return this;
113
+ }
114
+
115
+ page(limit, offset = 0) {
116
+ this.options.pageLimit = limit;
117
+ this.options.pageOffset = offset;
118
+ return this;
119
+ }
120
+
121
+ set(data) {
122
+ if (!this.options.data) {
123
+ this.options.data = {};
124
+ }
125
+ Object.assign(this.options.data, data);
126
+ return this;
127
+ }
128
+
129
+ join(table, alias, on, type) {
130
+ this.options.joins.push({ table, alias, on, type });
131
+ return this;
132
+ }
133
+
134
+ buildSql(operator) {
135
+ this.options.operator = operator;
136
+ return buildSql(this.options);
137
+ }
138
+
139
+ async exec() {
140
+ if (!this.options.operator) {
141
+ throw new Error('Invalid operator: ' + this.options.operator);
142
+ }
143
+ const { sql, values } = this.buildSql(this.options.operator);
144
+ const options = {
145
+ sql, values
146
+ };
147
+ switch (this.options.operator) {
148
+ case 'find': {
149
+ const res = await query(this.conn, options);
150
+ return res[0];
151
+ }
152
+ case 'count': {
153
+ const [res] = await query(this.conn, options);
154
+ return res.count;
155
+ }
156
+ default:
157
+ return query(this.conn, options);
158
+ }
159
+ }
160
+
161
+ async select() {
162
+ this.options.operator = 'select';
163
+ return await this.exec();
164
+ }
165
+
166
+ async find() {
167
+ this.options.operator = 'find';
168
+ const [res] = await this.exec();
169
+ return res;
170
+ }
171
+
172
+ async update(data) {
173
+ this.options.operator = 'update';
174
+ if (data) {
175
+ this.set(data);
176
+ }
177
+ return await this.exec();
178
+ }
179
+
180
+ async insert(data) {
181
+ this.options.operator = 'insert';
182
+ if (data) {
183
+ this.set(data);
184
+ }
185
+ return await this.exec();
186
+ }
187
+
188
+ async count() {
189
+ this.options.operator = 'count';
190
+ const res = await this.exec();
191
+ return res;
192
+ }
193
+ }
194
+
195
+ class QueryHandler {
196
+ constructor(conn) {
197
+ this.conn = conn;
198
+ }
199
+
200
+ async query(options) {
201
+ return new Promise((resolve, reject) => {
202
+ this.conn.query(options, (err, result) => {
203
+ if (err) {
204
+ reject(err);
205
+ } else {
206
+ resolve(result);
207
+ }
208
+ });
209
+ });
210
+ }
211
+
212
+ table(table, alias = null) {
213
+ return new QueryOperator(this.conn, {
214
+ tableName: table,
215
+ alias
216
+ });
217
+ }
218
+
219
+ async upsert(tableName, obj, condition = []) {
220
+ const [row] = await this.table(tableName).whereConditions(...condition).select();
221
+ if (row) {
222
+ return await this.table(tableName).update(obj);
223
+ }
224
+ return await this.table(tableName).insert(obj);
225
+ }
226
+ }
227
+
228
+ module.exports = {
229
+ QueryOperator,
230
+ QueryHandler
231
+ };
package/src/utils.js ADDED
@@ -0,0 +1,17 @@
1
+ 'use strict';
2
+
3
+ const Validator = require('validatorjs');
4
+
5
+ const validate = (obj, rules) => {
6
+ let validation = new Validator(obj, rules);
7
+ validation.check();
8
+ if (validation.fails()) {
9
+ const errors = validation.errors.all();
10
+ const keys = Object.keys(errors);
11
+ throw new Error(`${keys[0]}: ${errors[keys[0]]}`);
12
+ }
13
+ };
14
+
15
+ module.exports = {
16
+ validate
17
+ };