tspace-mysql 1.0.3 → 1.0.6

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/README.md CHANGED
@@ -131,12 +131,14 @@ import Post from '../Post'
131
131
  import Comment from '../Comment'
132
132
  import User from '../User'
133
133
 
134
+ /**
134
135
  Folder directory example
135
136
  - App
136
137
  - Model
137
138
  Post.ts
138
139
  User.ts
139
140
  Comment.ts
141
+ */
140
142
 
141
143
  (async () => {
142
144
  const users = await new User()
@@ -147,9 +149,11 @@ Folder directory example
147
149
 
148
150
  console.log(users)
149
151
  })()
150
- ```
151
- *User.ts
152
- ```js
152
+
153
+ /**
154
+ *
155
+ * User.ts
156
+ */
153
157
  import { Model } from 'tspace-mysql'
154
158
  class User extends Model {
155
159
  constructor(){
@@ -159,10 +163,10 @@ class User extends Model {
159
163
  }
160
164
  }
161
165
  export default User
162
- ```
163
-
164
- *Post.ts
165
- ```js
166
+ /**
167
+ *
168
+ * Post.ts
169
+ */
166
170
  import { Model } from 'tspace-mysql'
167
171
 
168
172
  class Post extends Model {
@@ -173,10 +177,12 @@ class Post extends Model {
173
177
  }
174
178
  }
175
179
  export default Post
176
- ```
177
180
 
178
- *Comment.ts
179
- ```js
181
+ /**
182
+ *
183
+ * Comment.ts
184
+ */
185
+
180
186
  import { Model } from 'tspace-mysql'
181
187
 
182
188
  class Comment extends Model {
@@ -209,7 +215,7 @@ select(column1 ,column2 ,...N)
209
215
  except(column1 ,column2 ,...N)
210
216
  only(column1 ,column2 ,...N)
211
217
  hidden(column1 ,column2 ,...N)
212
- join (primary key , table.foreign key)
218
+ join(primary key , table.foreign key)
213
219
  rightJoin (primary key , table.foreign key)
214
220
  leftJoin (primary key , table.foreign key)
215
221
  limit (limit)
@@ -219,13 +225,10 @@ latest (column)
219
225
  oldest (column)
220
226
  groupBy (column)
221
227
 
222
- insert(objects)
223
228
  create(objects)
224
229
  createMultiple(array objects)
225
230
  update (objects)
226
- insertNotExists(objects)
227
231
  createNotExists(objects)
228
- updateOrInsert (objects)
229
232
  updateOrCreate (objects)
230
233
  /**
231
234
  * relationship
@@ -326,6 +329,8 @@ import { Schema , Blueprint , DB } from 'tspace-mysql'
326
329
  email : new Blueprint().varchar(255).unique(),
327
330
  email_verify : new Blueprint().tinyInt(),
328
331
  password : new Blueprint().varchar(255),
332
+ created_at : new Blueprint().null().timestamp(),
333
+ updated_at : new Blueprint().null().timestamp()
329
334
  })
330
335
  /**
331
336
  *
@@ -334,7 +339,7 @@ import { Schema , Blueprint , DB } from 'tspace-mysql'
334
339
  */
335
340
  })()
336
341
  ```
337
- tspace-mysql migrate Migrations --dir=App/Models
342
+ tspace-mysql migrate --dir=App/Models/Migrations
338
343
  /* migrate all table in folder into database */
339
344
  ```js
340
345
  * Blueprint method
package/dist/cli/index.js CHANGED
@@ -19,8 +19,6 @@ try {
19
19
  var name = (_c = (_b = (_a = process.argv.slice(2)) === null || _a === void 0 ? void 0 : _a.find(function (data) { return data === null || data === void 0 ? void 0 : data.includes('--name='); })) === null || _b === void 0 ? void 0 : _b.replace('--name=', '')) !== null && _c !== void 0 ? _c : null;
20
20
  var migrate = (_e = (_d = process.argv.slice(2)) === null || _d === void 0 ? void 0 : _d.includes('--m')) !== null && _e !== void 0 ? _e : false;
21
21
  var dir = (_h = (_g = (_f = process.argv.slice(2)) === null || _f === void 0 ? void 0 : _f.find(function (data) { return data === null || data === void 0 ? void 0 : data.includes('--dir='); })) === null || _g === void 0 ? void 0 : _g.replace('--dir=', '/')) !== null && _h !== void 0 ? _h : null;
22
- // const migrateFolder = process.argv.slice(2)?.find(data => data?.includes('--f='))?.replace('--f=','/') ?? null
23
- // const type = process.argv.slice(2)?.includes('--js') ?? false ? '.js' : '.ts'
24
22
  var type = (_l = (_k = (_j = process.argv.slice(2)) === null || _j === void 0 ? void 0 : _j.find(function (data) { return data === null || data === void 0 ? void 0 : data.includes('--type='); })) === null || _k === void 0 ? void 0 : _k.replace('--type=', '.')) !== null && _l !== void 0 ? _l : '.ts';
25
23
  type = ['.js', '.ts'].includes(type) ? type : '.ts';
26
24
  var file = (_o = (_m = process.argv.slice(3)) === null || _m === void 0 ? void 0 : _m.shift()) !== null && _o !== void 0 ? _o : '';
@@ -37,5 +35,5 @@ try {
37
35
  commands[process.argv[2]](cmd);
38
36
  }
39
37
  catch (err) {
40
- console.log("\n use make:model <folder/...folder/model name> --m\n use make:table <folder/folder/...folder> --name=<name>\n use migrate <folder/folder/...folder> \n");
38
+ console.log("readme https://www.npmjs.com/package/tspace-mysql");
41
39
  }
@@ -15,20 +15,11 @@ var child_process_1 = require("child_process");
15
15
  exports.default = (function (_ref) {
16
16
  var e_1, _a;
17
17
  var _b, _c, _d;
18
- var file = _ref.file, type = _ref.type, dir = _ref.dir, cwd = _ref.cwd, fs = _ref.fs;
19
- var folder = file;
18
+ var type = _ref.type, dir = _ref.dir, cwd = _ref.cwd, fs = _ref.fs;
20
19
  try {
21
- fs.accessSync(cwd + "/".concat(folder), fs.F_OK, {
22
- recursive: true
23
- });
24
- }
25
- catch (e) {
26
- fs.mkdirSync(cwd + "/".concat(folder), {
27
- recursive: true
28
- });
29
- }
30
- try {
31
- var path = dir ? "".concat(cwd, "/").concat(dir, "/").concat(folder) : "".concat(cwd, "/").concat(folder);
20
+ if (dir == null)
21
+ throw new Error('Not found directory');
22
+ var path = "".concat(cwd, "/").concat(dir);
32
23
  var files = (_b = fs.readdirSync(path)) !== null && _b !== void 0 ? _b : [];
33
24
  if (!(files === null || files === void 0 ? void 0 : files.length))
34
25
  console.log('this folder is empty');
@@ -54,7 +45,6 @@ exports.default = (function (_ref) {
54
45
  }
55
46
  finally { if (e_1) throw e_1.error; }
56
47
  }
57
- process.exit(0);
58
48
  }
59
49
  catch (err) {
60
50
  console.log(err.message);
@@ -8,17 +8,19 @@ var table_1 = __importDefault(require("../tables/table"));
8
8
  var pluralize_1 = __importDefault(require("pluralize"));
9
9
  exports.default = (function (_ref) {
10
10
  var file = _ref.file, migrate = _ref.migrate, dir = _ref.dir, type = _ref.type, cwd = _ref.cwd, fs = _ref.fs, npm = _ref.npm;
11
- try {
12
- fs.accessSync(cwd + "/".concat(file), fs.F_OK, {
13
- recursive: true
14
- });
15
- }
16
- catch (e) {
17
- fs.mkdirSync(cwd + "/".concat(file), {
18
- recursive: true
19
- });
11
+ if (dir) {
12
+ try {
13
+ fs.accessSync(cwd + "/".concat(dir), fs.F_OK, {
14
+ recursive: true
15
+ });
16
+ }
17
+ catch (e) {
18
+ fs.mkdirSync(cwd + "/".concat(dir), {
19
+ recursive: true
20
+ });
21
+ }
20
22
  }
21
- var model = dir ? "".concat(cwd, "/").concat(dir, "/").concat(file).concat(type) : "".concat(cwd, "/").concat(file, "/").concat(file).concat(type);
23
+ var model = dir ? "".concat(cwd, "/").concat(dir, "/").concat(file).concat(type) : "".concat(cwd, "/").concat(file).concat(type);
22
24
  var data = (0, model_1.default)(file, npm);
23
25
  fs.writeFile(model, data, function (err) {
24
26
  if (err)
@@ -1,4 +1,4 @@
1
1
  declare const _default: (_ref: {
2
2
  [x: string]: any;
3
- }) => never;
3
+ }) => void;
4
4
  export default _default;
@@ -5,11 +5,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  var table_1 = __importDefault(require("./table"));
7
7
  exports.default = (function (_ref) {
8
- var file = _ref.file, name = _ref.name, type = _ref.type, cwd = _ref.cwd, dir = _ref.dir, fs = _ref.fs, npm = _ref.npm;
9
- if (name == null) {
10
- console.log("use ".concat(npm, " make:table FOLDER/FOLDER --name=tableName"));
11
- process.exit(0);
12
- }
8
+ var file = _ref.file, type = _ref.type, cwd = _ref.cwd, dir = _ref.dir, fs = _ref.fs, npm = _ref.npm;
13
9
  try {
14
10
  fs.accessSync(cwd + "/".concat(file), fs.F_OK, {
15
11
  recursive: true
@@ -21,11 +17,10 @@ exports.default = (function (_ref) {
21
17
  });
22
18
  }
23
19
  var folderMigrate = dir ? "".concat(cwd, "/").concat(dir, "/create_").concat(file, "_table").concat(type) : "".concat(cwd, "/create_").concat(file, "_table").concat(type);
24
- var table = (0, table_1.default)(name, npm);
20
+ var table = (0, table_1.default)(file, npm);
25
21
  fs.writeFile(folderMigrate, table, function (err) {
26
22
  if (err)
27
23
  console.log(err.message);
28
24
  });
29
- console.log("Migration : ".concat(name, " created successfully"));
30
- process.exit(0);
25
+ console.log("Migration : ".concat(file, " created successfully"));
31
26
  });
@@ -1,2 +1,2 @@
1
- declare const Table: (model: string, npm: string) => string;
1
+ declare const Table: (table: string, npm: string) => string;
2
2
  export default Table;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- var Table = function (model, npm) {
4
- return "import { Schema , Blueprint , DB } from '".concat(npm, "'\n(async () => {\n await new Schema().table('").concat(model, "',{ \n id : new Blueprint().int().notNull().primary().autoIncrement(),\n name : new Blueprint().varchar(120).default('my name'),\n email : new Blueprint().varchar(120).unique(),\n email_verify : new Blueprint().tinyInt(),\n password : new Blueprint().varchar(120),\n birthdate : new Blueprint().date(),\n created_at : new Blueprint().null().timestamp(),\n updated_at : new Blueprint().null().timestamp()\n })\n\n /**\n * \n * @Faker data\n * await new DB().table('").concat(model, "').faker(5)\n */\n})()\n");
3
+ var Table = function (table, npm) {
4
+ return "import { Schema , Blueprint , DB } from '".concat(npm, "'\n(async () => {\n await new Schema().table('").concat(table, "',{ \n id : new Blueprint().int().notNull().primary().autoIncrement(),\n name : new Blueprint().varchar(120).default('my name'),\n email : new Blueprint().varchar(120).unique(),\n email_verify : new Blueprint().tinyInt(),\n password : new Blueprint().varchar(120),\n birthdate : new Blueprint().date(),\n created_at : new Blueprint().null().timestamp(),\n updated_at : new Blueprint().null().timestamp()\n })\n\n /**\n * \n * @Faker data\n * await new DB().table('").concat(table, "').faker(5)\n */\n})()\n");
5
5
  };
6
6
  exports.default = Table;
@@ -2,15 +2,26 @@
2
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
- var _a;
6
5
  Object.defineProperty(exports, "__esModule", { value: true });
7
6
  var dotenv_1 = __importDefault(require("dotenv"));
8
7
  var path_1 = __importDefault(require("path"));
9
- var NODE_ENV = (_a = process.env) === null || _a === void 0 ? void 0 : _a.NODE_ENV;
10
- var pathEnv = path_1.default.join(path_1.default.resolve(), ".env.".concat(NODE_ENV));
11
- if (NODE_ENV == null)
12
- pathEnv = path_1.default.join(path_1.default.resolve(), ".env");
13
- dotenv_1.default.config({ path: pathEnv });
8
+ var fs_1 = __importDefault(require("fs"));
9
+ var environment = function () {
10
+ var _a;
11
+ var NODE_ENV = (_a = process.env) === null || _a === void 0 ? void 0 : _a.NODE_ENV;
12
+ var dotenvWithoutEnviroment = path_1.default.join(path_1.default.resolve(), ".env");
13
+ var dotenWithEnviroment = path_1.default.join(path_1.default.resolve(), ".env.".concat(NODE_ENV));
14
+ if (NODE_ENV == null) {
15
+ if (fs_1.default.existsSync(dotenvWithoutEnviroment))
16
+ return dotenvWithoutEnviroment;
17
+ if (fs_1.default.existsSync(dotenWithEnviroment))
18
+ return dotenWithEnviroment;
19
+ }
20
+ if (fs_1.default.existsSync(dotenWithEnviroment))
21
+ return dotenWithEnviroment;
22
+ return dotenvWithoutEnviroment;
23
+ };
24
+ dotenv_1.default.config({ path: environment() });
14
25
  var env = Object.freeze({
15
26
  DB_HOST: process.env.DB_HOST,
16
27
  DB_PORT: process.env.DB_PORT,
@@ -227,6 +227,7 @@ var DB = /** @class */ (function (_super) {
227
227
  HAVING: '',
228
228
  TABLE_NAME: '',
229
229
  HIDDEN: [],
230
+ UUID: false,
230
231
  DEBUG: false
231
232
  };
232
233
  return {
@@ -5,7 +5,7 @@ declare class Database extends AbstractDatabase {
5
5
  distinct(column?: string): this;
6
6
  select(...params: string[]): this;
7
7
  chunk(chunk: number): this;
8
- when(value: string | number | undefined | null, cb: Function): this;
8
+ when(value: string | number | undefined | null | Boolean, cb: Function): this;
9
9
  whereRaw(query: string): this;
10
10
  where(column: string, operator?: any, value?: any): this;
11
11
  whereId(id: number): this;
@@ -1171,19 +1171,18 @@ var Model = /** @class */ (function (_super) {
1171
1171
  }
1172
1172
  return dataParents;
1173
1173
  };
1174
- Model.prototype._relation = function (parentData, relation) {
1174
+ Model.prototype._relation = function (parents, relation) {
1175
1175
  return __awaiter(this, void 0, void 0, function () {
1176
- var _a, pk, fk, pkId, dataPerentId, query, childData;
1176
+ var _a, pk, fk, pkId, dataPerentId, query, childs;
1177
1177
  return __generator(this, function (_b) {
1178
1178
  switch (_b.label) {
1179
1179
  case 0:
1180
1180
  if (!Object.keys(relation).length)
1181
1181
  return [2 /*return*/, []];
1182
1182
  _a = this._valueInRelation(relation), pk = _a.pk, fk = _a.fk;
1183
- pkId = parentData.map(function (dataPerent) { return dataPerent[pk]; }).filter(function (data) { return data != null; });
1183
+ pkId = parents.map(function (parent) { return parent[pk]; }).filter(function (data) { return data != null; });
1184
1184
  dataPerentId = Array.from(new Set(pkId)) || [];
1185
- if (!dataPerentId.length && !this.$db.get('WITH_EXISTS'))
1186
- throw new Error("can't relationship without primary or foreign key");
1185
+ // if(!dataPerentId.length && !this.$db.get('WITH_EXISTS')) throw new Error("can't relationship without primary or foreign key")
1187
1186
  if (!dataPerentId.length && this.$db.get('WITH_EXISTS'))
1188
1187
  return [2 /*return*/, []];
1189
1188
  return [4 /*yield*/, relation.query];
@@ -1193,8 +1192,8 @@ var Model = /** @class */ (function (_super) {
1193
1192
  throw new Error("unknow callback queries in [relation : ".concat(relation.name, "]"));
1194
1193
  return [4 /*yield*/, query.whereIn(fk, dataPerentId).debug(this.$db.get('DEBUG')).get()];
1195
1194
  case 2:
1196
- childData = _b.sent();
1197
- return [2 /*return*/, childData];
1195
+ childs = _b.sent();
1196
+ return [2 /*return*/, childs];
1198
1197
  }
1199
1198
  });
1200
1199
  });
@@ -1226,7 +1225,7 @@ var Model = /** @class */ (function (_super) {
1226
1225
  dataChilds_1 = _e.sent();
1227
1226
  otherId = dataChilds_1.map(function (sub) { return sub[otherFk_1]; }).filter(function (data) { return data != null; });
1228
1227
  otherArrId = Array.from(new Set(otherId)) || [];
1229
- return [4 /*yield*/, modelOther.whereIn(otherPk_1, otherArrId).get()];
1228
+ return [4 /*yield*/, this._queryStatementModel(modelOther.whereIn(otherPk_1, otherArrId).toSQL())];
1230
1229
  case 2:
1231
1230
  otherdataChilds_1 = _e.sent();
1232
1231
  dataChilds_1.forEach(function (sub) {
@@ -1313,14 +1312,14 @@ var Model = /** @class */ (function (_super) {
1313
1312
  return __generator(this, function (_b) {
1314
1313
  switch (_b.label) {
1315
1314
  case 0:
1316
- currentPage = this.$db.get('PAGE');
1315
+ currentPage = +(this.$db.get('PAGE'));
1317
1316
  this.select("".concat(this.$utils().constants('COUNT'), "(*) ").concat(this.$utils().constants('AS'), " total"));
1318
1317
  sql = this._getSQLModel();
1319
1318
  return [4 /*yield*/, this._queryStatementModel(sql)];
1320
1319
  case 1:
1321
1320
  res = _b.sent();
1322
1321
  total = (res === null || res === void 0 ? void 0 : res.shift().total) || 0;
1323
- limit = this.$db.get('PER_PAGE');
1322
+ limit = +(this.$db.get('PER_PAGE'));
1324
1323
  lastPage = Math.ceil(total / limit) || 0;
1325
1324
  lastPage = lastPage > 1 ? lastPage : 1;
1326
1325
  nextPage = currentPage + 1;
@@ -1897,7 +1896,7 @@ var Model = /** @class */ (function (_super) {
1897
1896
  var _a;
1898
1897
  if (transaction === void 0) { transaction = { query: [{ table: '', id: '' }] }; }
1899
1898
  return __awaiter(this, void 0, void 0, function () {
1900
- var attributes, query_1, query, _b;
1899
+ var attributes, query, query, _b;
1901
1900
  return __generator(this, function (_c) {
1902
1901
  switch (_c.label) {
1903
1902
  case 0:
@@ -1905,14 +1904,15 @@ var Model = /** @class */ (function (_super) {
1905
1904
  attributes = this.$attributes;
1906
1905
  if ((_a = Object.keys(attributes)) === null || _a === void 0 ? void 0 : _a.length) {
1907
1906
  if (this.$db.get('WHERE')) {
1908
- query_1 = this._queryUpdateModel(attributes);
1909
- this.$db.set('UPDATE', "".concat(this.$utils().constants('UPDATE'), " ").concat(this.$db.get('TABLE_NAME'), " ").concat(query_1));
1907
+ query = this._queryUpdateModel(attributes);
1908
+ this.$db.set('UPDATE', "".concat(this.$utils().constants('UPDATE'), " ").concat(this.$db.get('TABLE_NAME'), " ").concat(query));
1910
1909
  this.$db.set('SAVE', 'UPDATE');
1911
- return [2 /*return*/];
1912
1910
  }
1913
- query = this._queryInsertModel(attributes);
1914
- this.$db.set('INSERT', "".concat(this.$utils().constants('INSERT'), " ").concat(this.$db.get('TABLE_NAME'), " ").concat(query));
1915
- this.$db.set('SAVE', 'INSERT');
1911
+ else {
1912
+ query = this._queryInsertModel(attributes);
1913
+ this.$db.set('INSERT', "".concat(this.$utils().constants('INSERT'), " ").concat(this.$db.get('TABLE_NAME'), " ").concat(query));
1914
+ this.$db.set('SAVE', 'INSERT');
1915
+ }
1916
1916
  }
1917
1917
  _b = this.$db.get('SAVE');
1918
1918
  switch (_b) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tspace-mysql",
3
- "version": "1.0.3",
3
+ "version": "1.0.6",
4
4
  "description": "mysql query builder object relational mapping",
5
5
  "main": "dist/lib/index.js",
6
6
  "types": "dist/lib/index.d.ts",
@@ -38,6 +38,10 @@
38
38
  },
39
39
  "homepage": "https://github.com/thanathip41",
40
40
  "scripts": {
41
+ "start" : "ts-node ./test/index.ts",
42
+ "prod" : "set NODE_ENV=production&& ts-node ./test/index.ts",
43
+ "dev" : "set NODE_ENV=development&& ts-node ./test/index.ts",
44
+ "test" : "set NODE_ENV=test&& ts-node ./test/index.ts",
41
45
  "build": "tsc",
42
46
  "prepare": "npm run build"
43
47
  },