tspace-mysql 1.1.2 → 1.1.3

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/cli/index.js CHANGED
@@ -3,37 +3,36 @@
3
3
  var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  return (mod && mod.__esModule) ? mod : { "default": mod };
5
5
  };
6
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o;
7
6
  Object.defineProperty(exports, "__esModule", { value: true });
8
- var fs_1 = __importDefault(require("fs"));
9
- var make_1 = __importDefault(require("./models/make"));
10
- var make_2 = __importDefault(require("./tables/make"));
11
- var make_3 = __importDefault(require("./migrate/make"));
12
- var commands = {
7
+ const fs_1 = __importDefault(require("fs"));
8
+ const make_1 = __importDefault(require("./models/make"));
9
+ const make_2 = __importDefault(require("./tables/make"));
10
+ const make_3 = __importDefault(require("./migrate/make"));
11
+ const commands = {
13
12
  'make:model': make_1.default,
14
13
  'make:table': make_2.default,
15
14
  'make:migration': make_2.default,
16
15
  'migrate': make_3.default
17
16
  };
18
17
  try {
19
- var name = (_c = (_b = (_a = process.argv.slice(2)) === null || _a === void 0 ? void 0 : _a.find(function (data) {
20
- return data === null || data === void 0 ? void 0 : data.includes('--name=');
21
- })) === null || _b === void 0 ? void 0 : _b.replace('--name=', '')) !== null && _c !== void 0 ? _c : null;
22
- var migrate = (_e = (_d = process.argv.slice(2)) === null || _d === void 0 ? void 0 : _d.includes('--m')) !== null && _e !== void 0 ? _e : false;
23
- var dir = (_h = (_g = (_f = process.argv.slice(2)) === null || _f === void 0 ? void 0 : _f.find(function (data) {
24
- return data === null || data === void 0 ? void 0 : data.includes('--dir=');
25
- })) === null || _g === void 0 ? void 0 : _g.replace('--dir=', '/')) !== null && _h !== void 0 ? _h : null;
26
- var type = (_l = (_k = (_j = process.argv.slice(2)) === null || _j === void 0 ? void 0 : _j.find(function (data) {
27
- return data === null || data === void 0 ? void 0 : data.includes('--type=');
28
- })) === null || _k === void 0 ? void 0 : _k.replace('--type=', '.')) !== null && _l !== void 0 ? _l : '.ts';
18
+ const name = process.argv.slice(2)?.find(data => {
19
+ return data?.includes('--name=');
20
+ })?.replace('--name=', '') ?? null;
21
+ const migrate = process.argv.slice(2)?.includes('--m') ?? false;
22
+ const dir = process.argv.slice(2)?.find(data => {
23
+ return data?.includes('--dir=');
24
+ })?.replace('--dir=', '/') ?? null;
25
+ let type = process.argv.slice(2)?.find(data => {
26
+ return data?.includes('--type=');
27
+ })?.replace('--type=', '.') ?? '.ts';
29
28
  type = ['.js', '.ts'].includes(type) ? type : '.ts';
30
- var file = (_o = (_m = process.argv.slice(3)) === null || _m === void 0 ? void 0 : _m.shift()) !== null && _o !== void 0 ? _o : '';
31
- var cmd = {
32
- name: name,
33
- file: file,
34
- dir: dir,
35
- migrate: migrate,
36
- type: type,
29
+ const file = process.argv.slice(3)?.shift() ?? '';
30
+ const cmd = {
31
+ name,
32
+ file,
33
+ dir,
34
+ migrate,
35
+ type,
37
36
  cwd: process.cwd(),
38
37
  fs: fs_1.default,
39
38
  npm: 'tspace-mysql'
@@ -41,5 +40,5 @@ try {
41
40
  commands[process.argv[2]](cmd);
42
41
  }
43
42
  catch (err) {
44
- console.log("readme https://www.npmjs.com/package/tspace-mysql");
43
+ console.log(`readme https://www.npmjs.com/package/tspace-mysql`);
45
44
  }
@@ -1,52 +1,29 @@
1
1
  "use strict";
2
- var __values = (this && this.__values) || function(o) {
3
- var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
4
- if (m) return m.call(o);
5
- if (o && typeof o.length === "number") return {
6
- next: function () {
7
- if (o && i >= o.length) o = void 0;
8
- return { value: o && o[i++], done: !o };
9
- }
10
- };
11
- throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
12
- };
13
2
  Object.defineProperty(exports, "__esModule", { value: true });
14
- var child_process_1 = require("child_process");
15
- exports.default = (function (formCommand) {
16
- var e_1, _a;
17
- var _b, _c, _d;
18
- var type = formCommand.type, dir = formCommand.dir, cwd = formCommand.cwd, fs = formCommand.fs;
3
+ const child_process_1 = require("child_process");
4
+ exports.default = (formCommand) => {
5
+ const { type, dir, cwd, fs } = formCommand;
19
6
  try {
20
7
  if (dir == null)
21
8
  throw new Error('Not found directory');
22
- var path = "".concat(cwd, "/").concat(dir);
23
- var files = (_b = fs.readdirSync(path)) !== null && _b !== void 0 ? _b : [];
24
- if (!(files === null || files === void 0 ? void 0 : files.length))
9
+ const path = `${cwd}/${dir}`;
10
+ const files = fs.readdirSync(path) ?? [];
11
+ if (!files?.length)
25
12
  console.log('this folder is empty');
26
- var cmd = type === '.js' ? 'node' : 'ts-node';
27
- try {
28
- for (var files_1 = __values(files), files_1_1 = files_1.next(); !files_1_1.done; files_1_1 = files_1.next()) {
29
- var _file = files_1_1.value;
30
- var run = (0, child_process_1.exec)("".concat(cmd, " ").concat(path, "/").concat(_file));
31
- (_c = run === null || run === void 0 ? void 0 : run.stdout) === null || _c === void 0 ? void 0 : _c.on('data', function (data) {
32
- if (data)
33
- console.log(data);
34
- });
35
- (_d = run === null || run === void 0 ? void 0 : run.stderr) === null || _d === void 0 ? void 0 : _d.on('data', function (err) {
36
- if (err)
37
- console.error(err);
38
- });
39
- }
40
- }
41
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
42
- finally {
43
- try {
44
- if (files_1_1 && !files_1_1.done && (_a = files_1.return)) _a.call(files_1);
45
- }
46
- finally { if (e_1) throw e_1.error; }
13
+ const cmd = type === '.js' ? 'node' : 'ts-node';
14
+ for (const _file of files) {
15
+ const run = (0, child_process_1.exec)(`${cmd} ${path}/${_file}`);
16
+ run?.stdout?.on('data', (data) => {
17
+ if (data)
18
+ console.log(data);
19
+ });
20
+ run?.stderr?.on('data', (err) => {
21
+ if (err)
22
+ console.error(err);
23
+ });
47
24
  }
48
25
  }
49
26
  catch (err) {
50
27
  console.log(err.message);
51
28
  }
52
- });
29
+ };
@@ -3,33 +3,33 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- var model_1 = __importDefault(require("./model"));
7
- var table_1 = __importDefault(require("../tables/table"));
8
- var pluralize_1 = __importDefault(require("pluralize"));
9
- exports.default = (function (formCommand) {
10
- var file = formCommand.file, migrate = formCommand.migrate, dir = formCommand.dir, type = formCommand.type, cwd = formCommand.cwd, fs = formCommand.fs, npm = formCommand.npm;
6
+ const model_1 = __importDefault(require("./model"));
7
+ const table_1 = __importDefault(require("../tables/table"));
8
+ const pluralize_1 = __importDefault(require("pluralize"));
9
+ exports.default = (formCommand) => {
10
+ const { file, migrate, dir, type, cwd, fs, npm } = formCommand;
11
11
  if (dir) {
12
12
  try {
13
- fs.accessSync(cwd + "/".concat(dir), fs.F_OK, {
13
+ fs.accessSync(cwd + `/${dir}`, fs.F_OK, {
14
14
  recursive: true
15
15
  });
16
16
  }
17
17
  catch (e) {
18
- fs.mkdirSync(cwd + "/".concat(dir), {
18
+ fs.mkdirSync(cwd + `/${dir}`, {
19
19
  recursive: true
20
20
  });
21
21
  }
22
22
  }
23
- var model = dir ? "".concat(cwd, "/").concat(dir, "/").concat(file).concat(type) : "".concat(cwd, "/").concat(file).concat(type);
24
- var data = (0, model_1.default)(file, npm);
25
- fs.writeFile(model, data, function (err) {
23
+ const model = dir ? `${cwd}/${dir}/${file}${type}` : `${cwd}/${file}${type}`;
24
+ const data = (0, model_1.default)(file, npm);
25
+ fs.writeFile(model, data, (err) => {
26
26
  if (err)
27
27
  throw err.message;
28
28
  });
29
- console.log("Model : '".concat(file, "' created successfully"));
29
+ console.log(`Model : '${file}' created successfully`);
30
30
  if (migrate) {
31
- var tableName = (0, pluralize_1.default)(file.replace(/([A-Z])/g, function (str) { return '_' + str.toLowerCase(); }).slice(1));
32
- var folder = dir ? "".concat(dir, "/Migrations") : "/Migrations";
31
+ const tableName = (0, pluralize_1.default)(file.replace(/([A-Z])/g, (str) => '_' + str.toLowerCase()).slice(1));
32
+ const folder = dir ? `${dir}/Migrations` : `/Migrations`;
33
33
  try {
34
34
  fs.accessSync(cwd + folder, fs.F_OK, {
35
35
  recursive: true
@@ -40,12 +40,12 @@ exports.default = (function (formCommand) {
40
40
  recursive: true
41
41
  });
42
42
  }
43
- var folderMigrate = "".concat(cwd, "/").concat(folder, "/create_").concat(tableName, "_table").concat(type);
44
- var table = (0, table_1.default)(tableName, npm);
45
- fs.writeFile(folderMigrate, table, function (err) {
43
+ const folderMigrate = `${cwd}/${folder}/create_${tableName}_table${type}`;
44
+ const table = (0, table_1.default)(tableName, npm);
45
+ fs.writeFile(folderMigrate, table, (err) => {
46
46
  if (err)
47
47
  throw err;
48
48
  });
49
- console.log("Migration : '".concat(tableName, "' created successfully"));
49
+ console.log(`Migration : '${tableName}' created successfully`);
50
50
  }
51
- });
51
+ };
@@ -1,6 +1,31 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- var Model = function (model, npm) {
4
- return "import { Model } from '".concat(npm, "'\nclass ").concat(model, " extends Model {\n constructor(){\n super()\n this.useUUID()\n this.useTimestamp()\n }\n}\nexport { ").concat(model, " }\nexport default ").concat(model, "\n");
3
+ const Model = (model, npm) => {
4
+ return `import { Model } from '${npm}'
5
+ class ${model} extends Model {
6
+ constructor(){
7
+ super()
8
+ /**
9
+ *
10
+ * Assign setting global in your model
11
+ * @useMethod
12
+ *
13
+ * this.useDebug() // => runing a uuid (universally unique identifier) when insert new data
14
+ * this.usePrimaryKey('id') // => runing a uuid (universally unique identifier) when insert new data
15
+ * this.useTimestamp({ createdAt : 'created_at' , updatedAt : 'updated_at' }) // runing a timestamp when insert or update
16
+ * this.useSoftDelete()
17
+ * this.useDisableSoftDeleteInRelations()
18
+ * this.useTable('Users')
19
+ * this.useTableSingular()
20
+ * this.useTablePlural()
21
+ * this.usePattern('snake_case')
22
+ * this.useUUID('uuid')
23
+ * this.useRegistry()
24
+ */
25
+ }
26
+ }
27
+ export { ${model} }
28
+ export default ${model}
29
+ `;
5
30
  };
6
31
  exports.default = Model;
@@ -3,24 +3,24 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- var table_1 = __importDefault(require("./table"));
7
- exports.default = (function (formCommand) {
8
- var file = formCommand.file, type = formCommand.type, cwd = formCommand.cwd, dir = formCommand.dir, fs = formCommand.fs, npm = formCommand.npm;
6
+ const table_1 = __importDefault(require("./table"));
7
+ exports.default = (formCommand) => {
8
+ const { file, type, cwd, dir, fs, npm } = formCommand;
9
9
  try {
10
- fs.accessSync(cwd + "/".concat(file), fs.F_OK, {
10
+ fs.accessSync(cwd + `/${file}`, fs.F_OK, {
11
11
  recursive: true
12
12
  });
13
13
  }
14
14
  catch (e) {
15
- fs.mkdirSync(cwd + "/".concat(file), {
15
+ fs.mkdirSync(cwd + `/${file}`, {
16
16
  recursive: true
17
17
  });
18
18
  }
19
- var folderMigrate = dir ? "".concat(cwd, "/").concat(dir, "/create_").concat(file, "_table").concat(type) : "".concat(cwd, "/create_").concat(file, "_table").concat(type);
20
- var table = (0, table_1.default)(file, npm);
21
- fs.writeFile(folderMigrate, table, function (err) {
19
+ const folderMigrate = dir ? `${cwd}/${dir}/create_${file}_table${type}` : `${cwd}/create_${file}_table${type}`;
20
+ const table = (0, table_1.default)(file, npm);
21
+ fs.writeFile(folderMigrate, table, (err) => {
22
22
  if (err)
23
23
  console.log(err.message);
24
24
  });
25
- console.log("Migration : ".concat(file, " created successfully"));
26
- });
25
+ console.log(`Migration : ${file} created successfully`);
26
+ };
@@ -1,6 +1,26 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
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 uuid : new Blueprint().varchar(50),\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");
3
+ const Table = (table, npm) => {
4
+ return `import { Schema , Blueprint , DB } from '${npm}'
5
+ (async () => {
6
+ await new Schema().table('${table}',{
7
+ id : new Blueprint().int().notNull().primary().autoIncrement(),
8
+ uuid : new Blueprint().varchar(50),
9
+ name : new Blueprint().varchar(120).default('my name'),
10
+ email : new Blueprint().varchar(120).unique(),
11
+ email_verify : new Blueprint().tinyInt(),
12
+ password : new Blueprint().varchar(120),
13
+ birthdate : new Blueprint().date(),
14
+ created_at : new Blueprint().null().timestamp(),
15
+ updated_at : new Blueprint().null().timestamp()
16
+ })
17
+
18
+ /**
19
+ *
20
+ * @Faker data
21
+ * await new DB().table('${table}').faker(5)
22
+ */
23
+ })()
24
+ `;
5
25
  };
6
26
  exports.default = Table;
@@ -4,5 +4,11 @@ declare const env: Readonly<{
4
4
  DB_USERNAME: string | undefined;
5
5
  DB_PASSWORD: string | undefined;
6
6
  DB_DATABASE: string | undefined;
7
+ TSPACE_MYSQL_HOST: string | undefined;
8
+ TSPACE_MYSQL_PORT: string | undefined;
9
+ TSPACE_MYSQL_USERNAME: string | undefined;
10
+ TSPACE_MYSQL_PASSWORD: string | undefined;
11
+ TSPACE_MYSQL_DATABASE: string | undefined;
7
12
  }>;
13
+ export { env };
8
14
  export default env;
@@ -3,14 +3,14 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- var dotenv_1 = __importDefault(require("dotenv"));
7
- var path_1 = __importDefault(require("path"));
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 envWithoutEnviroment = path_1.default.join(path_1.default.resolve(), '.env');
13
- var envWithEnviroment = path_1.default.join(path_1.default.resolve(), ".env.".concat(NODE_ENV));
6
+ exports.env = void 0;
7
+ const dotenv_1 = __importDefault(require("dotenv"));
8
+ const path_1 = __importDefault(require("path"));
9
+ const fs_1 = __importDefault(require("fs"));
10
+ const environment = () => {
11
+ const NODE_ENV = process.env?.NODE_ENV;
12
+ const envWithoutEnviroment = path_1.default.join(path_1.default.resolve(), '.env');
13
+ const envWithEnviroment = path_1.default.join(path_1.default.resolve(), `.env.${NODE_ENV}`);
14
14
  if (NODE_ENV == null)
15
15
  return envWithoutEnviroment;
16
16
  if (fs_1.default.existsSync(envWithEnviroment))
@@ -18,11 +18,17 @@ var environment = function () {
18
18
  return envWithoutEnviroment;
19
19
  };
20
20
  dotenv_1.default.config({ path: environment() });
21
- var env = Object.freeze({
21
+ const env = Object.freeze({
22
22
  DB_HOST: process.env.DB_HOST,
23
23
  DB_PORT: process.env.DB_PORT,
24
24
  DB_USERNAME: process.env.DB_USERNAME,
25
25
  DB_PASSWORD: process.env.DB_PASSWORD,
26
- DB_DATABASE: process.env.DB_DATABASE
26
+ DB_DATABASE: process.env.DB_DATABASE,
27
+ TSPACE_MYSQL_HOST: process.env.TSPACE_MYSQL_HOST,
28
+ TSPACE_MYSQL_PORT: process.env.TSPACE_MYSQL_PORT,
29
+ TSPACE_MYSQL_USERNAME: process.env.TSPACE_MYSQL_USERNAME,
30
+ TSPACE_MYSQL_PASSWORD: process.env.TSPACE_MYSQL_PASSWORD,
31
+ TSPACE_MYSQL_DATABASE: process.env.TSPACE_MYSQL_DATABASE
27
32
  });
33
+ exports.env = env;
28
34
  exports.default = env;
@@ -1,7 +1,19 @@
1
- interface Connection {
1
+ export interface PoolCallback {
2
+ query: (sql: string, callback: (err: any, result: any) => void) => void;
3
+ release: () => void;
4
+ }
5
+ export interface ConnectionTransaction {
6
+ query: (sql: string) => Promise<any[]>;
7
+ startTransaction: () => Promise<any[]>;
8
+ commit: () => Promise<any[]>;
9
+ rollback: () => Promise<any[]>;
10
+ }
11
+ export interface Connection {
2
12
  query: (sql: string) => Promise<any[]>;
13
+ connection: () => Promise<ConnectionTransaction>;
3
14
  }
4
- interface Options {
15
+ export interface Options {
16
+ [key: string]: any;
5
17
  connectionLimit?: number;
6
18
  dateStrings?: boolean;
7
19
  waitForConnections?: boolean;
@@ -12,16 +24,25 @@ interface Options {
12
24
  user: string;
13
25
  password: string;
14
26
  }
15
- declare class PoolConnection {
16
- [x: string]: any;
27
+ export declare class PoolConnection {
17
28
  private OPTIONS;
18
29
  constructor(options?: Options);
19
- private _pool;
20
- private _messageError;
21
- connection(): Connection;
30
+ /**
31
+ *
32
+ * Set a options connection pool
33
+ * @return {this} this
34
+ */
22
35
  options(options: Options): this;
36
+ /**
37
+ *
38
+ * Get a connection pool
39
+ * @return {Connection} Connection
40
+ */
41
+ connection(): Connection;
42
+ private _defaultOptions;
43
+ private _getJsonOptions;
44
+ private _messageError;
23
45
  }
24
46
  declare const Pool: Connection;
25
47
  export { Pool };
26
- export { PoolConnection };
27
48
  export default Pool;
@@ -1,79 +1,135 @@
1
1
  "use strict";
2
- var __assign = (this && this.__assign) || function () {
3
- __assign = Object.assign || function(t) {
4
- for (var s, i = 1, n = arguments.length; i < n; i++) {
5
- s = arguments[i];
6
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
- t[p] = s[p];
8
- }
9
- return t;
10
- };
11
- return __assign.apply(this, arguments);
12
- };
13
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
14
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
15
4
  };
16
5
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.PoolConnection = exports.Pool = void 0;
18
- var mysql_1 = require("mysql");
19
- var env_1 = __importDefault(require("../config/env"));
20
- var PoolConnection = /** @class */ (function () {
21
- function PoolConnection(options) {
22
- this.OPTIONS = new Map(Object.entries({
23
- connectionLimit: 10,
24
- dateStrings: true,
25
- waitForConnections: false,
26
- charset: 'utf8mb4',
27
- host: String(env_1.default.DB_HOST),
28
- port: Number.isNaN(Number(env_1.default.DB_PORT))
29
- ? 3306
30
- : Number(env_1.default.DB_PORT),
31
- database: String(env_1.default.DB_DATABASE),
32
- user: String(env_1.default.DB_USERNAME),
33
- password: String(env_1.default.DB_PASSWORD)
34
- }));
6
+ exports.Pool = exports.PoolConnection = void 0;
7
+ const fs_1 = __importDefault(require("fs"));
8
+ const path_1 = __importDefault(require("path"));
9
+ const env_1 = require("../config/env");
10
+ const mysql_1 = require("mysql");
11
+ class PoolConnection {
12
+ OPTIONS = this._getJsonOptions();
13
+ constructor(options) {
35
14
  if (options) {
36
- this.OPTIONS = new Map(Object.entries(__assign(__assign({}, Object.fromEntries(this.OPTIONS)), JSON.parse(JSON.stringify(options)))));
15
+ this.OPTIONS = new Map(Object.entries({
16
+ ...Object.fromEntries(this.OPTIONS),
17
+ ...JSON.parse(JSON.stringify(options))
18
+ }));
37
19
  }
38
20
  }
39
- PoolConnection.prototype._pool = function () {
40
- return (0, mysql_1.createPool)(Object.fromEntries(this.OPTIONS));
41
- };
42
- PoolConnection.prototype._messageError = function () {
43
- console.log("\u001B[1m\u001B[31m\n Connection lost to database ! \u001B[0m\n ------------------------------- \u001B[33m\n DB_HOST : ".concat(this.OPTIONS.get('host'), " \n DB_PORT : ").concat(this.OPTIONS.get('port'), " \n DB_DATABASE : ").concat(this.OPTIONS.get('database'), " \n DB_USERNAME : ").concat(this.OPTIONS.get('user'), " \n DB_PASSWORD : ").concat(this.OPTIONS.get('password'), " \u001B[0m \n -------------------------------\n "));
44
- return;
45
- };
46
- PoolConnection.prototype.connection = function () {
47
- var _this = this;
48
- var pool = this._pool();
49
- pool.getConnection(function (err, connection) {
21
+ /**
22
+ *
23
+ * Set a options connection pool
24
+ * @return {this} this
25
+ */
26
+ options(options) {
27
+ this.OPTIONS = new Map(Object.entries(options));
28
+ return this;
29
+ }
30
+ /**
31
+ *
32
+ * Get a connection pool
33
+ * @return {Connection} Connection
34
+ */
35
+ connection() {
36
+ const pool = (0, mysql_1.createPool)(Object.fromEntries(this.OPTIONS));
37
+ pool.getConnection((err, connection) => {
50
38
  if (err) {
51
- _this._messageError();
52
- return process.exit();
39
+ const message = this._messageError.bind(this);
40
+ process.nextTick(() => {
41
+ console.log(message());
42
+ return process.exit();
43
+ });
53
44
  }
54
45
  if (connection)
55
46
  connection.release();
56
- return;
57
47
  });
58
48
  return {
59
- query: function (sql) {
60
- return new Promise(function (resolve, reject) {
61
- pool.query(sql, function (err, results) {
49
+ query: (sql) => {
50
+ return new Promise((resolve, reject) => {
51
+ pool.query(sql, (err, results) => {
62
52
  if (err)
63
53
  return reject(err);
64
54
  return resolve(results);
65
55
  });
66
56
  });
57
+ },
58
+ connection: () => {
59
+ return new Promise((resolve, reject) => {
60
+ pool.getConnection((err, connection) => {
61
+ if (err)
62
+ return reject(err);
63
+ const query = (sql) => {
64
+ return new Promise((resolve, reject) => {
65
+ connection.query(sql, (err, result) => {
66
+ if (err)
67
+ return reject(err);
68
+ return resolve(result);
69
+ });
70
+ });
71
+ };
72
+ const startTransaction = () => query('START TRANSACTION');
73
+ const commit = () => query('COMMIT');
74
+ const rollback = () => query('ROLLBACK');
75
+ return resolve({
76
+ query,
77
+ startTransaction,
78
+ commit,
79
+ rollback
80
+ });
81
+ });
82
+ });
67
83
  }
68
84
  };
69
- };
70
- PoolConnection.prototype.options = function (options) {
71
- this.OPTIONS = new Map(Object.entries(options));
72
- return this;
73
- };
74
- return PoolConnection;
75
- }());
85
+ }
86
+ _defaultOptions() {
87
+ return new Map(Object.entries({
88
+ connectionLimit: 10,
89
+ dateStrings: true,
90
+ connectTimeout: 1000 * 30,
91
+ acquireTimeout: 1000 * 30,
92
+ waitForConnections: false,
93
+ charset: 'utf8mb4',
94
+ host: String(env_1.env.DB_HOST ?? env_1.env.TSPACE_MYSQL_HOST),
95
+ port: Number.isNaN(Number(env_1.env.DB_PORT ?? env_1.env.TSPACE_MYSQL_PORT))
96
+ ? 3306
97
+ : Number(env_1.env.DB_PORT ?? env_1.env.TSPACE_MYSQL_PORT),
98
+ database: String(env_1.env.DB_DATABASE ?? env_1.env.TSPACE_MYSQL_DATABASE),
99
+ user: String(env_1.env.DB_USERNAME ?? env_1.env.TSPACE_MYSQL_USERNAME),
100
+ password: String(env_1.env.DB_PASSWORD ?? env_1.env.TSPACE_MYSQL_PASSWORD)
101
+ }));
102
+ }
103
+ _getJsonOptions() {
104
+ try {
105
+ const jsonPath = path_1.default.join(path_1.default.resolve(), 'tspace-mysql.json');
106
+ const jsonOptionsExists = fs_1.default.existsSync(jsonPath);
107
+ if (jsonOptionsExists) {
108
+ const jsonOptions = fs_1.default.readFileSync(jsonPath, 'utf8');
109
+ const options = JSON.parse(jsonOptions);
110
+ return new Map(Object.entries(options));
111
+ }
112
+ return this._defaultOptions();
113
+ }
114
+ catch (e) {
115
+ return this._defaultOptions();
116
+ }
117
+ }
118
+ _messageError() {
119
+ return `
120
+ \x1b[1m\x1b[31m
121
+ Connection lost to database ! \x1b[0m
122
+ --------------------------------- \x1b[33m
123
+ DB_HOST : ${this.OPTIONS.get('host')}
124
+ DB_PORT : ${this.OPTIONS.get('port')}
125
+ DB_DATABASE : ${this.OPTIONS.get('database')}
126
+ DB_USERNAME : ${this.OPTIONS.get('user')}
127
+ DB_PASSWORD : ${this.OPTIONS.get('password')} \x1b[0m
128
+ ---------------------------------
129
+ `;
130
+ }
131
+ }
76
132
  exports.PoolConnection = PoolConnection;
77
- var Pool = new PoolConnection().connection();
133
+ const Pool = new PoolConnection().connection();
78
134
  exports.Pool = Pool;
79
135
  exports.default = Pool;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- var constant = {
3
+ const constant = {
4
4
  ID: 'ID',
5
5
  SHOW: 'SHOW',
6
6
  FIELDS: 'FIELDS',
@@ -43,6 +43,10 @@ var constant = {
43
43
  NOT: 'NOT',
44
44
  DUPLICATE: 'DUPLICATE',
45
45
  KEY: 'KEY',
46
+ WHEN: 'WHEN',
47
+ THEN: 'THEN',
48
+ ELSE: 'ELSE',
49
+ END: 'END',
46
50
  WHERE_NOT_EXISTS: 'WHERE NOT EXISTS',
47
51
  EXISTS: 'EXISTS',
48
52
  VALUES: 'VALUES',
@@ -100,10 +104,6 @@ var constant = {
100
104
  PER_PAGE: 1
101
105
  },
102
106
  MODEL: {
103
- TRANSACTION: { query: [{
104
- table: '',
105
- id: ''
106
- }] },
107
107
  PRIMARY_KEY: 'id',
108
108
  SELECT: '',
109
109
  DELETE: '',
@@ -132,6 +132,7 @@ var constant = {
132
132
  DEBUG: false,
133
133
  UUID: false,
134
134
  SOFT_DELETE: false,
135
+ SOFT_DELETE_FORMAT: 'deleted_at',
135
136
  SOFT_DELETE_RELATIONS: false,
136
137
  RELATION: [],
137
138
  WITH: [],
@@ -148,3 +149,4 @@ var constant = {
148
149
  }
149
150
  };
150
151
  exports.default = Object.freeze(constant);
152
+ // export default constant