@rdyl/node-mysql 0.0.2 → 0.0.4

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/dist/meta.js CHANGED
@@ -1,113 +1,201 @@
1
1
  "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __generator = (this && this.__generator) || function (thisArg, body) {
12
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
13
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
+ function verb(n) { return function (v) { return step([n, v]); }; }
15
+ function step(op) {
16
+ if (f) throw new TypeError("Generator is already executing.");
17
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
18
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
+ if (y = 0, t) op = [op[0] & 2, t.value];
20
+ switch (op[0]) {
21
+ case 0: case 1: t = op; break;
22
+ case 4: _.label++; return { value: op[1], done: false };
23
+ case 5: _.label++; y = op[1]; op = [0]; continue;
24
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
+ default:
26
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
+ if (t[2]) _.ops.pop();
31
+ _.trys.pop(); continue;
32
+ }
33
+ op = body.call(thisArg, _);
34
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
+ }
37
+ };
2
38
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ConditionKey = exports.SortKey = exports.RelationKey = exports.Options = exports.Condition = void 0;
39
+ exports.DbSchema = void 0;
40
+ var helper_1 = require("./helper");
4
41
  var utils_1 = require("./utils");
5
- var Condition = /** @class */ (function () {
6
- function Condition(props) {
7
- this.field = props.field;
8
- this.value = props.value;
9
- this.condition = props.condition || ConditionKey.eq;
10
- this.relation = props.relation || RelationKey.and;
42
+ /**
43
+ * @description
44
+ * 使用$toMap时 不返回的字段名前面需要加$
45
+ */
46
+ var DbSchema = /** @class */ (function () {
47
+ function DbSchema($table, $mapExFields) {
48
+ if ($mapExFields === void 0) { $mapExFields = []; }
49
+ this.$table = $table;
50
+ this.$mapExFields = $mapExFields;
51
+ this.id = '';
52
+ this.createTime = utils_1.Parser.easyDate();
53
+ this.updateTime = utils_1.Parser.easyDate();
11
54
  }
12
- Object.defineProperty(Condition.prototype, "_valueSql", {
55
+ Object.defineProperty(DbSchema.prototype, "$toJson", {
13
56
  get: function () {
14
- var target = '';
15
- var _a = this, condition = _a.condition, value = _a.value;
16
- if (condition == ConditionKey.include) {
17
- if (Array.isArray(value) && value.length > 0) {
18
- target = utils_1.MysqlParser.toValuesOf(value);
57
+ var _this = this;
58
+ return Object.keys(this).reduce(function (obj, key) {
59
+ if (!key.startsWith('$') &&
60
+ Object.prototype.hasOwnProperty.call(_this, key)) {
61
+ // @ts-ignore
62
+ obj[key] = _this[key];
19
63
  }
20
- }
21
- else if (condition == ConditionKey.area) {
22
- if (Array.isArray(value) && value.length > 0) {
23
- target = "".concat(value[0], " AND ").concat(value[1]);
24
- }
25
- }
26
- else {
27
- target = utils_1.MysqlParser.valueTypeOf(value);
28
- }
29
- return target;
64
+ return obj;
65
+ }, {});
30
66
  },
31
67
  enumerable: false,
32
68
  configurable: true
33
69
  });
34
- Object.defineProperty(Condition.prototype, "result", {
70
+ Object.defineProperty(DbSchema.prototype, "$toMap", {
35
71
  get: function () {
36
- var target = '';
37
- var _a = this, condition = _a.condition, field = _a.field;
38
- if (this._valueSql) {
39
- if (condition == ConditionKey.not) {
40
- target += 'NOT ';
41
- }
42
- target += "".concat(field, " ").concat(condition, " ").concat(this._valueSql);
43
- }
44
- return target;
72
+ var _this = this;
73
+ var target = this.$toJson;
74
+ return Object.fromEntries(Object.keys(target)
75
+ .filter(function (k) { return !_this.$mapExFields.includes(k); })
76
+ .map(function (k) {
77
+ return [k, target[k]];
78
+ }));
45
79
  },
46
80
  enumerable: false,
47
81
  configurable: true
48
82
  });
49
- Condition.prototype.connect = function (prev) {
50
- var _a = this, relation = _a.relation, result = _a.result;
51
- if (!prev) {
52
- return result;
53
- }
54
- if (!result) {
55
- return prev;
56
- }
57
- return "".concat(prev, " ").concat(relation, " ").concat(result);
58
- };
59
- return Condition;
60
- }());
61
- exports.Condition = Condition;
62
- var Options = /** @class */ (function () {
63
- function Options() {
64
- this.limit = 0;
65
- this.skip = 0;
66
- // 排序
67
- this.sort = {};
68
- }
69
- Object.defineProperty(Options.prototype, "result", {
83
+ Object.defineProperty(DbSchema.prototype, "$fields", {
70
84
  get: function () {
71
- var target = '';
72
- var _a = this, sort = _a.sort, limit = _a.limit, skip = _a.skip;
73
- if (Object.keys(sort).length > 0) {
74
- var items_1 = [];
75
- Object.keys(sort).forEach(function (name, v) {
76
- items_1.push("".concat(name, " ").concat(v));
77
- });
78
- target += "ORDER BY ".concat(items_1.join('), '));
79
- }
80
- if (limit > 0) {
81
- target += "\nLIMIT ".concat(limit, " OFFSET ").concat(skip);
82
- }
83
- return target;
85
+ return Object.keys(this.$toJson);
84
86
  },
85
87
  enumerable: false,
86
88
  configurable: true
87
89
  });
88
- return Options;
90
+ DbSchema.prototype.$formJson = function (json) {
91
+ var _this = this;
92
+ Object.keys(json).forEach(function (k) {
93
+ if (Object.prototype.hasOwnProperty.call(_this, k)) {
94
+ // @ts-ignore
95
+ _this[k] = json[k];
96
+ }
97
+ });
98
+ };
99
+ DbSchema.prototype.$get = function () {
100
+ return __awaiter(this, void 0, void 0, function () {
101
+ var selector, res;
102
+ return __generator(this, function (_a) {
103
+ switch (_a.label) {
104
+ case 0:
105
+ selector = new helper_1.MysqlSelector(this.$table, this.$mapExFields);
106
+ return [4 /*yield*/, selector.getById(this.id)];
107
+ case 1:
108
+ res = _a.sent();
109
+ if (res) {
110
+ this.$formJson(res);
111
+ return [2 /*return*/, this];
112
+ }
113
+ return [2 /*return*/, null];
114
+ }
115
+ });
116
+ });
117
+ };
118
+ DbSchema.prototype.$insert = function (uniqueKey) {
119
+ return __awaiter(this, void 0, void 0, function () {
120
+ var inserter, existing, res;
121
+ return __generator(this, function (_a) {
122
+ switch (_a.label) {
123
+ case 0:
124
+ inserter = new helper_1.MysqlInserter(this.$table, this.$fields);
125
+ inserter.push(this.$toJson);
126
+ if (!uniqueKey) return [3 /*break*/, 2];
127
+ return [4 /*yield*/, global.mysqlPool.query("SELECT 1 FROM ".concat(this.$table, " WHERE ").concat(uniqueKey, " = ? LIMIT 1"), [this.$toJson[uniqueKey]])];
128
+ case 1:
129
+ existing = (_a.sent())[0];
130
+ // @ts-ignore
131
+ if (existing && existing.length > 0) {
132
+ return [2 /*return*/, 'exist'];
133
+ }
134
+ _a.label = 2;
135
+ case 2: return [4 /*yield*/, inserter.result()];
136
+ case 3:
137
+ res = _a.sent();
138
+ if (res.filter(function (e) { return e !== -1; }).length > 0) {
139
+ this.id = res[0];
140
+ return [2 /*return*/, 'ok'];
141
+ }
142
+ else {
143
+ return [2 /*return*/, 'fail'];
144
+ }
145
+ return [2 /*return*/];
146
+ }
147
+ });
148
+ });
149
+ };
150
+ DbSchema.prototype.$remove = function () {
151
+ return __awaiter(this, void 0, void 0, function () {
152
+ var deleter, user;
153
+ return __generator(this, function (_a) {
154
+ switch (_a.label) {
155
+ case 0:
156
+ deleter = new helper_1.MysqlDeleter(this.$table);
157
+ return [4 /*yield*/, this.$get()];
158
+ case 1:
159
+ user = _a.sent();
160
+ if (!user) return [3 /*break*/, 3];
161
+ return [4 /*yield*/, deleter.removeById(this.id)];
162
+ case 2: return [2 /*return*/, _a.sent()];
163
+ case 3: return [2 /*return*/, 'exist'];
164
+ }
165
+ });
166
+ });
167
+ };
168
+ DbSchema.prototype.$update = function (maps) {
169
+ return __awaiter(this, void 0, void 0, function () {
170
+ var updater, user, values, affected;
171
+ return __generator(this, function (_a) {
172
+ switch (_a.label) {
173
+ case 0:
174
+ updater = new helper_1.MysqlUpdater(this.$table);
175
+ return [4 /*yield*/, this.$get()];
176
+ case 1:
177
+ user = _a.sent();
178
+ if (!user) return [3 /*break*/, 3];
179
+ values = Object.fromEntries(Object.keys(maps)
180
+ .filter(function (n) { return !['id', 'createTime', 'updateTime'].includes(n); })
181
+ .map(function (k) { return [k, maps[k]]; }));
182
+ updater.setFields(values);
183
+ updater.select({
184
+ field: 'id',
185
+ value: user.id,
186
+ });
187
+ return [4 /*yield*/, updater.result()];
188
+ case 2:
189
+ affected = _a.sent();
190
+ if (affected > 0) {
191
+ return [2 /*return*/, 'ok'];
192
+ }
193
+ return [2 /*return*/, 'fail'];
194
+ case 3: return [2 /*return*/, 'exist'];
195
+ }
196
+ });
197
+ });
198
+ };
199
+ return DbSchema;
89
200
  }());
90
- exports.Options = Options;
91
- var RelationKey;
92
- (function (RelationKey) {
93
- RelationKey["and"] = "AND";
94
- RelationKey["or"] = "OR";
95
- })(RelationKey || (exports.RelationKey = RelationKey = {}));
96
- var SortKey;
97
- (function (SortKey) {
98
- SortKey["asc"] = "ASC";
99
- SortKey["desc"] = "DESC";
100
- })(SortKey || (exports.SortKey = SortKey = {}));
101
- var ConditionKey;
102
- (function (ConditionKey) {
103
- ConditionKey["eq"] = "=";
104
- ConditionKey["ne"] = "!=";
105
- ConditionKey["gt"] = ">";
106
- ConditionKey["gte"] = ">=";
107
- ConditionKey["lt"] = "<";
108
- ConditionKey["lte"] = "<=";
109
- ConditionKey["like"] = "LIKE";
110
- ConditionKey["include"] = "IN";
111
- ConditionKey["area"] = "BETWEEN";
112
- ConditionKey["not"] = "=";
113
- })(ConditionKey || (exports.ConditionKey = ConditionKey = {}));
201
+ exports.DbSchema = DbSchema;
package/dist/utils.js CHANGED
@@ -1,21 +1,48 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.MysqlParser = void 0;
4
- var MysqlParser = /** @class */ (function () {
5
- function MysqlParser() {
6
- }
7
- MysqlParser.valueTypeOf = function (v) {
8
- if (typeof v === 'string')
9
- return "'".concat(v, "'");
10
- return "".concat(v);
11
- };
12
- MysqlParser.toValuesOf = function (values) {
3
+ exports.Parser = void 0;
4
+ exports.Parser = {
5
+ easyDate: function (date, format) {
6
+ if (date === void 0) { date = new Date(); }
7
+ if (format === void 0) { format = 'YYYY-MM-DD HH:mm:ss'; }
8
+ var pad = function (num) { return num.toString().padStart(2, '0'); };
9
+ var year = date.getFullYear();
10
+ var month = pad(date.getMonth() + 1);
11
+ var day = pad(date.getDate());
12
+ var hours = pad(date.getHours());
13
+ var minutes = pad(date.getMinutes());
14
+ var seconds = pad(date.getSeconds());
15
+ return format
16
+ .replace('YYYY', year.toString())
17
+ .replace('MM', month)
18
+ .replace('DD', day)
19
+ .replace('HH', hours)
20
+ .replace('mm', minutes)
21
+ .replace('ss', seconds);
22
+ },
23
+ toDbName: function (str) {
24
+ return str.replace(/[A-Z]/g, function (letter) { return "_".concat(letter.toLowerCase()); });
25
+ },
26
+ toFieldName: function (str) {
27
+ var words = str.split(/[-_\s]+/);
28
+ if (!words.length)
29
+ return '';
30
+ var firstWord = words[0].toLowerCase();
31
+ var restWords = words
32
+ .slice(1)
33
+ .map(function (word) { return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase(); });
34
+ return firstWord + restWords.join('');
35
+ },
36
+ toValuesOf: function (values) {
13
37
  var items = [];
14
38
  for (var v in values) {
15
- items.push(MysqlParser.valueTypeOf(v));
39
+ items.push(exports.Parser.valueTypeOf(v));
16
40
  }
17
41
  return "(".concat(items.join(', '), ")");
18
- };
19
- return MysqlParser;
20
- }());
21
- exports.MysqlParser = MysqlParser;
42
+ },
43
+ valueTypeOf: function (v) {
44
+ if (typeof v === 'string')
45
+ return "'".concat(v, "'");
46
+ return "".concat(v);
47
+ },
48
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rdyl/node-mysql",
3
- "version": "0.0.2",
3
+ "version": "0.0.4",
4
4
  "license": "MIT",
5
5
  "main": "dist/index.js",
6
6
  "types": "types/index.d.ts",
@@ -18,7 +18,7 @@
18
18
  "build": "tsc && copyfiles -u 1 src/**/*.d.ts src/*.d.ts types && npm run changelog && git add CHANGELOG.md"
19
19
  },
20
20
  "dependencies": {
21
- "mysql": "^2.18.1"
21
+ "mysql2": "^3.14.0"
22
22
  },
23
23
  "devDependencies": {
24
24
  "@commitlint/cli": "^19.6.1",
@@ -28,4 +28,4 @@
28
28
  "copyfiles": "^2.4.1",
29
29
  "typescript": "^5.6.3"
30
30
  }
31
- }
31
+ }
@@ -0,0 +1,79 @@
1
+ import { SortKey, SelectOption, OptionsType } from './interface';
2
+ declare class BaseHelper {
3
+ _tableName: string;
4
+ constructor(_tableName: string);
5
+ selects: SelectOption[];
6
+ options: OptionsType;
7
+ get selectStat(): {
8
+ sql: string;
9
+ values: unknown[];
10
+ };
11
+ get optionStat(): {
12
+ sql: string;
13
+ };
14
+ select(opts: SelectOption): this;
15
+ limit(n: number): this;
16
+ skip(n: number): this;
17
+ sort(field: string, v: SortKey): this;
18
+ }
19
+ /** @description 查询数据 */
20
+ export declare class MysqlSelector extends BaseHelper {
21
+ exFields: string[];
22
+ constructor(t: string, exFields?: string[]);
23
+ get sql(): string;
24
+ get countSql(): string;
25
+ total(): Promise<any>;
26
+ /** @查询结果 */
27
+ result(): Promise<{
28
+ [k: string]: any;
29
+ }[]>;
30
+ /** @根据id查询 */
31
+ getById(value: number | string): Promise<{
32
+ [k: string]: any;
33
+ } | null>;
34
+ paged(param: {
35
+ page: number;
36
+ pageSize: number;
37
+ }): Promise<{
38
+ page: number;
39
+ pageSize: number;
40
+ records: {
41
+ [k: string]: any;
42
+ }[];
43
+ total: any;
44
+ }>;
45
+ }
46
+ /** @description 插入数据 */
47
+ export declare class MysqlInserter extends BaseHelper {
48
+ values: Array<unknown[]>;
49
+ fields: string[];
50
+ constructor(t: string, fields?: string[]);
51
+ get sql(): string;
52
+ push(...arr: Record<string, unknown>[]): void;
53
+ result(): Promise<number[]>;
54
+ }
55
+ /** @description 删除数据 */
56
+ export declare class MysqlDeleter extends BaseHelper {
57
+ constructor(t: string);
58
+ get sql(): string;
59
+ /** @查询结果 */
60
+ result(): Promise<any>;
61
+ /** @根据id删除 */
62
+ removeById(value: number | string): Promise<"ok" | "fail">;
63
+ }
64
+ /** @description 更新数据 */
65
+ export declare class MysqlUpdater extends BaseHelper {
66
+ exFields: string[];
67
+ constructor(t: string, exFields?: string[]);
68
+ updateFields: Record<string, unknown>;
69
+ get updateStat(): {
70
+ sql: string;
71
+ values: unknown[];
72
+ };
73
+ get sql(): string;
74
+ setField(field: string, v: unknown): this;
75
+ setFields(values: Record<string, unknown>): this;
76
+ /** @查询结果 */
77
+ result(): Promise<any>;
78
+ }
79
+ export {};
package/types/index.d.ts CHANGED
@@ -1,3 +1,6 @@
1
- export * from "./selector";
2
- export * from "./meta";
3
- export * from "./utils";
1
+ import mysql from 'mysql2/promise';
2
+ export declare function setup(opts: mysql.PoolOptions): void;
3
+ export * from './helper';
4
+ export * from './meta';
5
+ export * from './interface';
6
+ export * from './utils';
@@ -0,0 +1,40 @@
1
+ export declare const RelationMaps: {
2
+ and: string;
3
+ or: string;
4
+ };
5
+ export type RelationKey = keyof typeof RelationMaps;
6
+ export declare const SortMaps: {
7
+ asc: string;
8
+ desc: string;
9
+ };
10
+ export type SortKey = keyof typeof SortMaps;
11
+ export declare const ConditionMaps: {
12
+ eq: string;
13
+ ne: string;
14
+ gt: string;
15
+ gte: string;
16
+ lt: string;
17
+ lte: string;
18
+ like: string;
19
+ include: string;
20
+ area: string;
21
+ not: string;
22
+ };
23
+ export type ConditionKey = keyof typeof ConditionMaps;
24
+ export interface SelectOption {
25
+ field: string;
26
+ value: unknown;
27
+ relation?: RelationKey;
28
+ condition?: ConditionKey;
29
+ }
30
+ export interface OptionsType {
31
+ limit?: number;
32
+ skip?: number;
33
+ sort: Record<string, SortKey>;
34
+ }
35
+ export interface DbBaseType {
36
+ id: number | string;
37
+ createTime: string;
38
+ updateTime: string;
39
+ }
40
+ export type DbResultStat = 'exist' | 'ok' | 'fail';
package/types/meta.d.ts CHANGED
@@ -1,42 +1,23 @@
1
- export declare class Condition {
2
- relation: RelationKey;
3
- field: string;
4
- value: unknown;
5
- condition: ConditionKey;
6
- constructor(props: ConditionProps);
7
- get _valueSql(): string;
8
- get result(): string;
9
- connect(prev: string): string;
10
- }
11
- export declare class Options {
12
- limit: number;
13
- skip: number;
14
- sort: Record<string, SortKey>;
15
- get result(): string;
16
- }
17
- export declare enum RelationKey {
18
- and = "AND",
19
- or = "OR"
20
- }
21
- export declare enum SortKey {
22
- asc = "ASC",
23
- desc = "DESC"
24
- }
25
- export declare enum ConditionKey {
26
- eq = "=",
27
- ne = "!=",
28
- gt = ">",
29
- gte = ">=",
30
- lt = "<",
31
- lte = "<=",
32
- like = "LIKE",
33
- include = "IN",
34
- area = "BETWEEN",// 范围
35
- not = "="
36
- }
37
- export interface ConditionProps {
38
- field: string;
39
- value: unknown;
40
- relation?: RelationKey;
41
- condition?: ConditionKey;
1
+ import { DbBaseType, DbResultStat } from './interface';
2
+ /**
3
+ * @description
4
+ * 使用$toMap时 不返回的字段名前面需要加$
5
+ */
6
+ export declare class DbSchema implements DbBaseType {
7
+ $table: string;
8
+ $mapExFields: string[];
9
+ id: number | string;
10
+ createTime: string;
11
+ updateTime: string;
12
+ constructor($table: string, $mapExFields?: string[]);
13
+ get $toJson(): Record<string, any>;
14
+ get $toMap(): {
15
+ [k: string]: any;
16
+ };
17
+ get $fields(): string[];
18
+ $formJson(json: Record<string, unknown>): void;
19
+ $get(): Promise<this | null>;
20
+ $insert(uniqueKey?: string): Promise<DbResultStat>;
21
+ $remove(): Promise<DbResultStat>;
22
+ $update(maps: Record<string, unknown>): Promise<DbResultStat>;
42
23
  }
package/types/utils.d.ts CHANGED
@@ -1,4 +1,7 @@
1
- export declare class MysqlParser {
2
- static valueTypeOf(v: unknown): string;
3
- static toValuesOf(values: unknown[]): string;
4
- }
1
+ export declare const Parser: {
2
+ easyDate(date?: Date, format?: string): string;
3
+ toDbName(str: string): string;
4
+ toFieldName(str: string): string;
5
+ toValuesOf(values: unknown[]): string;
6
+ valueTypeOf(v: unknown): string;
7
+ };