chyz 2.0.0-rc.29 → 2.0.0-rc.30

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.
Files changed (116) hide show
  1. package/BaseChyz.d.ts +62 -62
  2. package/BaseChyz.js +488 -489
  3. package/base/ActionFilter.d.ts +32 -32
  4. package/base/ActionFilter.js +82 -82
  5. package/base/BadRequestHttpException.d.ts +5 -5
  6. package/base/BadRequestHttpException.js +17 -17
  7. package/base/BaseError.d.ts +31 -31
  8. package/base/BaseError.js +47 -47
  9. package/base/Behavior.d.ts +3 -3
  10. package/base/Behavior.js +7 -7
  11. package/base/CBaseObject.d.ts +4 -4
  12. package/base/CBaseObject.js +16 -16
  13. package/base/CEvents.d.ts +12 -12
  14. package/base/CEvents.js +24 -24
  15. package/base/CRequest.d.ts +1 -1
  16. package/base/CRequest.js +10 -10
  17. package/base/CWebController.d.ts +43 -43
  18. package/base/CWebController.js +81 -81
  19. package/base/Component.d.ts +20 -20
  20. package/base/Component.js +57 -57
  21. package/base/Configurable.d.ts +2 -2
  22. package/base/Configurable.js +8 -8
  23. package/base/DataErrorDbException.d.ts +5 -5
  24. package/base/DataErrorDbException.js +17 -17
  25. package/base/DbConnection.d.ts +12 -12
  26. package/base/DbConnection.js +53 -53
  27. package/base/ForbiddenHttpException.d.ts +4 -4
  28. package/base/ForbiddenHttpException.js +16 -16
  29. package/base/InvalidArgumentException.d.ts +5 -5
  30. package/base/InvalidArgumentException.js +17 -17
  31. package/base/InvalidConfigException.d.ts +5 -5
  32. package/base/InvalidConfigException.js +17 -17
  33. package/base/Logs.d.ts +21 -21
  34. package/base/Logs.js +57 -57
  35. package/base/Model.d.ts +298 -298
  36. package/base/Model.js +509 -509
  37. package/base/ModelManager.d.ts +1 -1
  38. package/base/ModelManager.js +19 -19
  39. package/base/NotFoundHttpException.d.ts +5 -5
  40. package/base/NotFoundHttpException.js +17 -17
  41. package/base/RestClient.d.ts +6 -6
  42. package/base/RestClient.js +25 -25
  43. package/base/UnauthorizedHttpException.d.ts +5 -5
  44. package/base/UnauthorizedHttpException.js +17 -17
  45. package/base/ValidationHttpException.d.ts +5 -5
  46. package/base/ValidationHttpException.js +17 -17
  47. package/base/db/Exception.d.ts +6 -6
  48. package/base/db/Exception.js +15 -15
  49. package/base/index.d.ts +19 -19
  50. package/base/index.js +41 -41
  51. package/decorator/Middleware.d.ts +3 -3
  52. package/decorator/Middleware.js +11 -11
  53. package/decorator/controller.d.ts +2 -2
  54. package/decorator/controller.js +24 -24
  55. package/decorator/delete.d.ts +2 -2
  56. package/decorator/delete.js +36 -36
  57. package/decorator/enums/ControllerDecoratorParams.d.ts +5 -5
  58. package/decorator/enums/ControllerDecoratorParams.js +9 -9
  59. package/decorator/get.d.ts +2 -2
  60. package/decorator/get.js +36 -36
  61. package/decorator/index.d.ts +5 -5
  62. package/decorator/index.js +13 -13
  63. package/decorator/post.d.ts +2 -2
  64. package/decorator/post.js +36 -36
  65. package/decorator/put.d.ts +2 -2
  66. package/decorator/put.js +36 -36
  67. package/filters/AccessControl.d.ts +12 -12
  68. package/filters/AccessControl.js +83 -83
  69. package/filters/AccessRule.d.ts +82 -82
  70. package/filters/AccessRule.js +136 -136
  71. package/filters/auth/AuthInterface.d.ts +25 -25
  72. package/filters/auth/AuthInterface.js +2 -2
  73. package/filters/auth/AuthMethod.d.ts +37 -37
  74. package/filters/auth/AuthMethod.js +82 -82
  75. package/filters/auth/HttpBasicAuth.d.ts +22 -22
  76. package/filters/auth/HttpBasicAuth.js +72 -72
  77. package/filters/auth/HttpBearerAuth.d.ts +17 -17
  78. package/filters/auth/HttpBearerAuth.js +32 -32
  79. package/filters/auth/HttpHeaderAuth.d.ts +14 -14
  80. package/filters/auth/HttpHeaderAuth.js +57 -57
  81. package/filters/auth/JwtHttpBearerAuth.d.ts +20 -20
  82. package/filters/auth/JwtHttpBearerAuth.js +87 -87
  83. package/filters/auth/KeyCloakHttpBearerAuth.d.ts +22 -22
  84. package/filters/auth/KeyCloakHttpBearerAuth.js +116 -116
  85. package/filters/auth/index.d.ts +4 -4
  86. package/filters/auth/index.js +11 -11
  87. package/filters/index.d.ts +2 -2
  88. package/filters/index.js +7 -7
  89. package/index.d.ts +21 -21
  90. package/index.js +61 -61
  91. package/model/RouteDefinition.d.ts +6 -6
  92. package/model/RouteDefinition.js +8 -8
  93. package/package.json +9 -11
  94. package/rbac/AuthAssignment.d.ts +18 -18
  95. package/rbac/AuthAssignment.js +44 -44
  96. package/rbac/AuthItem.d.ts +26 -26
  97. package/rbac/AuthItem.js +51 -51
  98. package/rbac/AuthItemChild.d.ts +18 -18
  99. package/rbac/AuthItemChild.js +43 -43
  100. package/rbac/AuthManager.d.ts +111 -111
  101. package/rbac/AuthManager.js +357 -357
  102. package/requiments/Glob.d.ts +2 -2
  103. package/requiments/Glob.js +10 -10
  104. package/requiments/ReflectUtil.js +24 -24
  105. package/requiments/Utils.d.ts +8 -8
  106. package/requiments/Utils.js +125 -125
  107. package/validators/BooleanValidator.js +1 -1
  108. package/validators/CompareValidator.js +1 -1
  109. package/validators/DateValidator.js +1 -1
  110. package/validators/EmailValidator.js +1 -1
  111. package/validators/Validator.d.ts +17 -17
  112. package/validators/Validator.js +27 -27
  113. package/web/IdentityInterface.d.ts +54 -54
  114. package/web/IdentityInterface.js +8 -8
  115. package/web/WebUser.d.ts +71 -71
  116. package/web/WebUser.js +165 -165
package/base/Model.js CHANGED
@@ -1,509 +1,509 @@
1
- "use strict";
2
- /*
3
- * Copyright (c) 2021. Chy Bilgisayar Bilisim
4
- * Author: Cihan Ozturk
5
- * E-mail: cihan@chy.com.tr
6
- * Github:https://github.com/cihan53/
7
- */
8
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
9
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
10
- return new (P || (P = Promise))(function (resolve, reject) {
11
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
12
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
13
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
14
- step((generator = generator.apply(thisArg, _arguments || [])).next());
15
- });
16
- };
17
- var __importDefault = (this && this.__importDefault) || function (mod) {
18
- return (mod && mod.__esModule) ? mod : { "default": mod };
19
- };
20
- Object.defineProperty(exports, "__esModule", { value: true });
21
- exports.Model = exports.NOW = exports.DataTypes = void 0;
22
- const BaseChyz_1 = __importDefault(require("../BaseChyz"));
23
- const Utils_1 = require("../requiments/Utils");
24
- const Component_1 = require("./Component");
25
- const InvalidConfigException_1 = require("./InvalidConfigException");
26
- const sequelize_1 = require("sequelize");
27
- const Exception_1 = require("./db/Exception");
28
- var sequelize_2 = require("sequelize");
29
- Object.defineProperty(exports, "DataTypes", { enumerable: true, get: function () { return sequelize_2.DataTypes; } });
30
- Object.defineProperty(exports, "NOW", { enumerable: true, get: function () { return sequelize_2.NOW; } });
31
- /**
32
- * ValidateMe.init({
33
- bar: {
34
- type: Sequelize.STRING,
35
- validate: {
36
- is: ["^[a-z]+$",'i'], // will only allow letters
37
- is: /^[a-z]+$/i, // same as the previous example using real RegExp
38
- not: ["[a-z]",'i'], // will not allow letters
39
- isEmail: true, // checks for email format (foo@bar.com)
40
- isUrl: true, // checks for url format (http://foo.com)
41
- isIP: true, // checks for IPv4 (129.89.23.1) or IPv6 format
42
- isIPv4: true, // checks for IPv4 (129.89.23.1)
43
- isIPv6: true, // checks for IPv6 format
44
- isAlpha: true, // will only allow letters
45
- isAlphanumeric: true, // will only allow alphanumeric characters, so "_abc" will fail
46
- isNumeric: true, // will only allow numbers
47
- isInt: true, // checks for valid integers
48
- isFloat: true, // checks for valid floating point numbers
49
- isDecimal: true, // checks for any numbers
50
- isLowercase: true, // checks for lowercase
51
- isUppercase: true, // checks for uppercase
52
- notNull: true, // won't allow null
53
- isNull: true, // only allows null
54
- notEmpty: true, // don't allow empty strings
55
- equals: 'specific value', // only allow a specific value
56
- contains: 'foo', // force specific substrings
57
- notIn: [['foo', 'bar']], // check the value is not one of these
58
- isIn: [['foo', 'bar']], // check the value is one of these
59
- notContains: 'bar', // don't allow specific substrings
60
- len: [2,10], // only allow values with length between 2 and 10
61
- isUUID: 4, // only allow uuids
62
- isDate: true, // only allow date strings
63
- isAfter: "2011-11-05", // only allow date strings after a specific date
64
- isBefore: "2011-11-05", // only allow date strings before a specific date
65
- max: 23, // only allow values <= 23
66
- min: 23, // only allow values >= 23
67
- isCreditCard: true, // check for valid credit card numbers
68
-
69
- // Examples of custom validators:
70
- isEven(value) {
71
- if (parseInt(value) % 2 !== 0) {
72
- throw new Error('Only even values are allowed!');
73
- }
74
- }
75
- isGreaterThanOtherField(value) {
76
- if (parseInt(value) <= parseInt(this.otherField)) {
77
- throw new Error('Bar must be greater than otherField.');
78
- }
79
- }
80
- }
81
- }
82
- }, { sequelize });
83
- */
84
- class Model extends Component_1.Component {
85
- constructor(sequelize) {
86
- super();
87
- this._attributes = {};
88
- this._errors = {};
89
- this._tableName = this.alias();
90
- BaseChyz_1.default.debug("Model constructor", this._tableName);
91
- // this._sequelize = BaseChyz.getComponent("db").db;
92
- if (sequelize != null)
93
- this._provider = sequelize;
94
- else
95
- this._provider = this.getDb();
96
- if (!Utils_1.Utils.isEmpty(this.attributes())) {
97
- this._model = this._provider.define(this._tableName, this.attributes(), {
98
- tableName: this.tableName(),
99
- timestamps: false,
100
- createdAt: false,
101
- updateAt: false
102
- });
103
- }
104
- else {
105
- throw new InvalidConfigException_1.InvalidConfigException(BaseChyz_1.default.t("Invalid model configuration, is not emty attributes"));
106
- }
107
- // this.init();
108
- }
109
- /**
110
- * Returns the database connection used by this AR class.
111
- * By default, the "db" application component is used as the database connection.
112
- * You may override this method if you want to use a different database connection.
113
- * @return Connection the database connection used by this AR class.
114
- */
115
- getDb() {
116
- return BaseChyz_1.default.getComponent("db").db;
117
- }
118
- getDbConnection() {
119
- return BaseChyz_1.default.getComponent("db");
120
- }
121
- get provider() {
122
- return this._provider;
123
- }
124
- set provider(value) {
125
- this._provider = value;
126
- }
127
- /**
128
- *
129
- */
130
- get errors() {
131
- return this._errors;
132
- }
133
- set errors(value) {
134
- this._errors = value;
135
- }
136
- init() {
137
- BaseChyz_1.default.debug("Model init....", this.constructor.name);
138
- /**
139
- * init buraya
140
- */
141
- BaseChyz_1.default.debug("Relation init....", this.constructor.name);
142
- for (const relation of this.relations()) {
143
- let m = relation.model;
144
- if (relation.type == "hasOne") {
145
- // @ts-ignore
146
- delete relation.model;
147
- this.model().hasOne(m, relation);
148
- }
149
- //
150
- if (relation.type == "hasMany") {
151
- // @ts-ignore
152
- delete relation.model;
153
- this.model().hasMany(m, relation);
154
- }
155
- if (relation.type == "belongsTo") {
156
- // @ts-ignore
157
- delete relation.model;
158
- this.model().belongsTo(m, relation);
159
- }
160
- if (relation.type == "belongsToMany") {
161
- // @ts-ignore
162
- delete relation.model;
163
- this.model().belongsToMany(m, relation);
164
- }
165
- }
166
- }
167
- alias() {
168
- return this.constructor.name;
169
- }
170
- tableName() {
171
- return this._tableName;
172
- }
173
- formName() {
174
- return this.constructor.name;
175
- }
176
- rules() {
177
- return [];
178
- }
179
- setModel(value) {
180
- this._model = value;
181
- }
182
- model() {
183
- return this._model;
184
- }
185
- save(params = {}, options = {}) {
186
- return __awaiter(this, void 0, void 0, function* () {
187
- this.errors = {};
188
- // now instantiate an object
189
- let p = Object.assign(params, this._attributes);
190
- let result;
191
- try {
192
- result = yield this.model().create(p, options);
193
- }
194
- catch (e) {
195
- BaseChyz_1.default.debug(`Model[${this.constructor.name}].create`, e);
196
- if (e instanceof sequelize_1.ValidationError) {
197
- let validationErrorItems = e.errors;
198
- validationErrorItems.forEach(({ message, path }) => {
199
- // @ts-ignore
200
- this._errors[path] = message;
201
- });
202
- return false;
203
- }
204
- else if (e instanceof sequelize_1.DatabaseError) {
205
- }
206
- else if (e instanceof sequelize_1.TimeoutError) {
207
- }
208
- else if (e instanceof sequelize_1.UniqueConstraintError) {
209
- }
210
- else if (e instanceof sequelize_1.ForeignKeyConstraintError) {
211
- }
212
- else if (e instanceof sequelize_1.ExclusionConstraintError) {
213
- }
214
- throw new Exception_1.Exception(e.message, this.errors, e.code);
215
- }
216
- return result;
217
- });
218
- }
219
- bulkCreate(params = {}, options = {}) {
220
- return __awaiter(this, void 0, void 0, function* () {
221
- this.errors = {};
222
- // now instantiate an object
223
- let p = Object.assign(params, this._attributes);
224
- let result;
225
- try {
226
- result = yield this.model().bulkCreate(p, options);
227
- }
228
- catch (e) {
229
- BaseChyz_1.default.debug(`Model[${this.constructor.name}].bulkCreate`, e);
230
- if (e instanceof sequelize_1.ValidationError) {
231
- let validationErrorItems = e.errors;
232
- validationErrorItems.forEach(({ message, path }) => {
233
- // @ts-ignore
234
- this._errors[path] = message;
235
- });
236
- return false;
237
- }
238
- else if (e instanceof sequelize_1.DatabaseError) {
239
- }
240
- else if (e instanceof sequelize_1.TimeoutError) {
241
- }
242
- else if (e instanceof sequelize_1.UniqueConstraintError) {
243
- }
244
- else if (e instanceof sequelize_1.ForeignKeyConstraintError) {
245
- }
246
- else if (e instanceof sequelize_1.ExclusionConstraintError) {
247
- }
248
- throw new Exception_1.Exception(e.message, this.errors, e.code);
249
- }
250
- return result;
251
- });
252
- }
253
- update(params = {}, options = {}) {
254
- this.errors = {};
255
- let p = Object.assign(params, this._attributes);
256
- return this.model().update(p, options);
257
- }
258
- delete(params = {}, options = {}) {
259
- this.errors = {};
260
- let p = Object.assign(params, this._attributes);
261
- return this.model().destroy(p, options);
262
- }
263
- /**
264
- * As there are often use cases in which it is just easier to execute raw / already prepared SQL queries, you can use the sequelize.query method.
265
- *
266
- * By default the function will return two arguments - a results array, and an object containing metadata (such as amount of affected rows, etc). Note that since this is a raw query, the metadata are dialect specific. Some dialects return the metadata "within" the results object (as properties on an array). However, two arguments will always be returned, but for MSSQL and MySQL it will be two references to the same object.
267
- *
268
- * const [results, metadata] = await sequelize.query("UPDATE users SET y = 42 WHERE x = 12");
269
- * // Results will be an empty array and metadata will contain the number of affected rows.
270
- *
271
- * In cases where you don't need to access the metadata you can pass in a query type to tell sequelize how to format the results. For example, for a simple select query you could do:
272
- *
273
- * const { QueryTypes } = require('@sequelize/core');
274
- * const users = await sequelize.query("SELECT * FROM `users`", { type: QueryTypes.SELECT });
275
- * // We didn't need to destructure the result here - the results were returned directly
276
- *
277
- * Several other query types are available. Peek into the source for details.
278
- *
279
- * A second option is the model. If you pass a model the returned data will be instances of that model.
280
- *
281
- * // Callee is the model definition. This allows you to easily map a query to a predefined model
282
- * const projects = await sequelize.query('SELECT * FROM projects', {
283
- * model: Projects,
284
- * mapToModel: true // pass true here if you have any mapped fields
285
- * });
286
- * // Each element of `projects` is now an instance of Project
287
- *
288
- * See more options in the query API reference. Some examples:
289
- * ``
290
- * const { QueryTypes } = require('@sequelize/core');
291
- * await sequelize.query('SELECT 1', {
292
- * // A function (or false) for logging your queries
293
- * // Will get called for every SQL query that gets sent
294
- * // to the server.
295
- * logging: console.log,
296
- *
297
- * // If plain is true, then sequelize will only return the first
298
- * // record of the result set. In case of false it will return all records.
299
- * plain: false,
300
- *
301
- * // Set this to true if you don't have a model definition for your query.
302
- * raw: false,
303
- *
304
- * // The type of query you are executing. The query type affects how results are formatted before they are passed back.
305
- * type: QueryTypes.SELECT
306
- * });
307
- *``
308
- * // Note the second argument being null!
309
- * // Even if we declared a callee here, the raw: true would
310
- * // supersede and return a raw object.
311
- * console.log(await sequelize.query('SELECT * FROM projects', { raw: true }));
312
- *
313
- * ##"Dotted" attributes and the nest option
314
- *
315
- * If an attribute name of the table contains dots, the resulting objects can become nested objects by setting the nest: true option. This is achieved with dottie.js under the hood. See below:
316
- *
317
- * Without nest: true:
318
- * ``
319
- * const { QueryTypes } = require('@sequelize/core');
320
- * const records = await sequelize.query('select 1 as `foo.bar.baz`', {
321
- * type: QueryTypes.SELECT
322
- * });
323
- * console.log(JSON.stringify(records[0], null, 2));
324
- *
325
- * {
326
- * "foo.bar.baz": 1
327
- * }
328
- *
329
- * With nest: true:
330
- *
331
- * const { QueryTypes } = require('@sequelize/core');
332
- * const records = await sequelize.query('select 1 as `foo.bar.baz`', {
333
- * nest: true,
334
- * type: QueryTypes.SELECT
335
- * });
336
- * console.log(JSON.stringify(records[0], null, 2));
337
- *
338
- * {
339
- * "foo": {
340
- * "bar": {
341
- * "baz": 1
342
- * }
343
- * }
344
- * }
345
- * ``
346
- * ##Replacements
347
- *
348
- * Replacements in a query can be done in two different ways, either using named parameters (starting with :), or unnamed, represented by a ?. Replacements are passed in the options object.
349
- *
350
- * If an array is passed, ? will be replaced in the order that they appear in the array
351
- * If an object is passed, :key will be replaced with the keys from that object. If the object contains keys not found in the query or vice versa, an exception will be thrown.
352
- * ``
353
- * const { QueryTypes } = require('@sequelize/core');
354
- *
355
- * await sequelize.query(
356
- * 'SELECT * FROM projects WHERE status = ?',
357
- * {
358
- * replacements: ['active'],
359
- * type: QueryTypes.SELECT
360
- * }
361
- * );
362
- *
363
- * await sequelize.query(
364
- * 'SELECT * FROM projects WHERE status = :status',
365
- * {
366
- * replacements: { status: 'active' },
367
- * type: QueryTypes.SELECT
368
- * }
369
- * );
370
- * ``
371
- * Array replacements will automatically be handled, the following query searches for projects where the status matches an array of values.
372
- * ``
373
- * const { QueryTypes } = require('@sequelize/core');
374
- *
375
- * await sequelize.query(
376
- * 'SELECT * FROM projects WHERE status IN(:status)',
377
- * {
378
- * replacements: { status: ['active', 'inactive'] },
379
- * type: QueryTypes.SELECT
380
- * }
381
- * );
382
- * ``
383
- * To use the wildcard operator %, append it to your replacement. The following query matches users with names that start with 'ben'.
384
- * ``
385
- * const { QueryTypes } = require('@sequelize/core');
386
- *
387
- * await sequelize.query(
388
- * 'SELECT * FROM users WHERE name LIKE :search_name',
389
- * {
390
- * replacements: { search_name: 'ben%' },
391
- * type: QueryTypes.SELECT
392
- * }
393
- * ); ``
394
- *
395
- * ##Bind Parameter
396
- *
397
- * Bind parameters are like replacements. Except replacements are escaped and inserted into the query by sequelize before the query is sent to the database, while bind parameters are sent to the database outside the SQL query text. A query can have either bind parameters or replacements. Bind parameters are referred to by either $1, $2, ... (numeric) or $key (alpha-numeric). This is independent of the dialect.
398
- *
399
- * If an array is passed, $1 is bound to the 1st element in the array (bind[0])
400
- * If an object is passed, $key is bound to object['key']. Each key must begin with a non-numeric char. $1 is not a valid key, even if object['1'] exists.
401
- * In either case $$ can be used to escape a literal $ sign.
402
- *
403
- * The array or object must contain all bound values or Sequelize will throw an exception. This applies even to cases in which the database may ignore the bound parameter.
404
- *
405
- * The database may add further restrictions to this. Bind parameters cannot be SQL keywords, nor table or column names. They are also ignored in quoted text or data. In PostgreSQL it may also be needed to typecast them, if the type cannot be inferred from the context $1::varchar.
406
- *``
407
- * const { QueryTypes } = require('@sequelize/core');
408
- *
409
- * await sequelize.query(
410
- * 'SELECT *, "text with literal $$1 and literal $$status" as t FROM projects WHERE status = $1',
411
- * {
412
- * bind: ['active'],
413
- * type: QueryTypes.SELECT
414
- * }
415
- * ); ``
416
- *
417
- * `` await sequelize.query(
418
- * 'SELECT *, "text with literal $$1 and literal $$status" as t FROM projects WHERE status = $status',
419
- * {
420
- * bind: { status: 'active' },
421
- * type: QueryTypes.SELECT
422
- * }
423
- * );``
424
- * @param query
425
- */
426
- rawQuery(query, options = { type: sequelize_1.QueryTypes.SELECT, nest: true }) {
427
- return __awaiter(this, void 0, void 0, function* () {
428
- this.errors = {};
429
- return yield this.model().query(query, options);
430
- });
431
- }
432
- /**
433
- *
434
- * @param args
435
- */
436
- findOne(...args) {
437
- return this._model.findOne(...arguments);
438
- }
439
- /**
440
- *
441
- * @param args
442
- */
443
- findAll(...args) {
444
- return this._model.findAll(...arguments);
445
- }
446
- /**
447
- * return {count : number , rows: any}
448
- * @param args
449
- */
450
- findAndCountAll(...args) {
451
- return this._model.findAndCountAll(...arguments);
452
- }
453
- validate() {
454
- }
455
- /**
456
- *
457
- * @param data
458
- * @param formName
459
- */
460
- load(data, formName = null) {
461
- let scope = formName === null ? this.formName() : formName;
462
- if (scope === '' && !Utils_1.Utils.isEmpty(data)) {
463
- this.setAttribute(data);
464
- return true;
465
- }
466
- else if (data[scope]) {
467
- this.setAttribute(data[scope]);
468
- return true;
469
- }
470
- return false;
471
- }
472
- bulkLoad(data, formName = null) {
473
- let scope = formName === null ? this.formName() : formName;
474
- if (scope === '' && !Utils_1.Utils.isEmpty(data)) {
475
- this.setAttribute(data);
476
- return true;
477
- }
478
- else if (data[scope]) {
479
- this.setAttribute(data[scope]);
480
- return true;
481
- }
482
- return false;
483
- }
484
- setAttribute(values, safeOnly = true) {
485
- if (values instanceof Object) {
486
- let attributes = this.attributes();
487
- for (const valueKey in values) {
488
- if (Object.keys(attributes).indexOf(valueKey) != -1) {
489
- // @ts-ignore
490
- BaseChyz_1.default.debug("Model[" + this.formName() + "] attributes value set ", valueKey, values[valueKey]);
491
- this._attributes[valueKey] = values[valueKey];
492
- }
493
- }
494
- }
495
- }
496
- attributes() {
497
- return {};
498
- }
499
- /**
500
- * relation return array
501
- * [
502
- *
503
- * ]
504
- */
505
- relations() {
506
- return [];
507
- }
508
- }
509
- exports.Model = Model;
1
+ "use strict";
2
+ /*
3
+ * Copyright (c) 2021. Chy Bilgisayar Bilisim
4
+ * Author: Cihan Ozturk
5
+ * E-mail: cihan@chy.com.tr
6
+ * Github:https://github.com/cihan53/
7
+ */
8
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
9
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
10
+ return new (P || (P = Promise))(function (resolve, reject) {
11
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
12
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
13
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
14
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
15
+ });
16
+ };
17
+ var __importDefault = (this && this.__importDefault) || function (mod) {
18
+ return (mod && mod.__esModule) ? mod : { "default": mod };
19
+ };
20
+ Object.defineProperty(exports, "__esModule", { value: true });
21
+ exports.Model = exports.NOW = exports.DataTypes = void 0;
22
+ const BaseChyz_1 = __importDefault(require("../BaseChyz"));
23
+ const Utils_1 = require("../requiments/Utils");
24
+ const Component_1 = require("./Component");
25
+ const InvalidConfigException_1 = require("./InvalidConfigException");
26
+ const sequelize_1 = require("sequelize");
27
+ const Exception_1 = require("./db/Exception");
28
+ var sequelize_2 = require("sequelize");
29
+ Object.defineProperty(exports, "DataTypes", { enumerable: true, get: function () { return sequelize_2.DataTypes; } });
30
+ Object.defineProperty(exports, "NOW", { enumerable: true, get: function () { return sequelize_2.NOW; } });
31
+ /**
32
+ * ValidateMe.init({
33
+ bar: {
34
+ type: Sequelize.STRING,
35
+ validate: {
36
+ is: ["^[a-z]+$",'i'], // will only allow letters
37
+ is: /^[a-z]+$/i, // same as the previous example using real RegExp
38
+ not: ["[a-z]",'i'], // will not allow letters
39
+ isEmail: true, // checks for email format (foo@bar.com)
40
+ isUrl: true, // checks for url format (http://foo.com)
41
+ isIP: true, // checks for IPv4 (129.89.23.1) or IPv6 format
42
+ isIPv4: true, // checks for IPv4 (129.89.23.1)
43
+ isIPv6: true, // checks for IPv6 format
44
+ isAlpha: true, // will only allow letters
45
+ isAlphanumeric: true, // will only allow alphanumeric characters, so "_abc" will fail
46
+ isNumeric: true, // will only allow numbers
47
+ isInt: true, // checks for valid integers
48
+ isFloat: true, // checks for valid floating point numbers
49
+ isDecimal: true, // checks for any numbers
50
+ isLowercase: true, // checks for lowercase
51
+ isUppercase: true, // checks for uppercase
52
+ notNull: true, // won't allow null
53
+ isNull: true, // only allows null
54
+ notEmpty: true, // don't allow empty strings
55
+ equals: 'specific value', // only allow a specific value
56
+ contains: 'foo', // force specific substrings
57
+ notIn: [['foo', 'bar']], // check the value is not one of these
58
+ isIn: [['foo', 'bar']], // check the value is one of these
59
+ notContains: 'bar', // don't allow specific substrings
60
+ len: [2,10], // only allow values with length between 2 and 10
61
+ isUUID: 4, // only allow uuids
62
+ isDate: true, // only allow date strings
63
+ isAfter: "2011-11-05", // only allow date strings after a specific date
64
+ isBefore: "2011-11-05", // only allow date strings before a specific date
65
+ max: 23, // only allow values <= 23
66
+ min: 23, // only allow values >= 23
67
+ isCreditCard: true, // check for valid credit card numbers
68
+
69
+ // Examples of custom validators:
70
+ isEven(value) {
71
+ if (parseInt(value) % 2 !== 0) {
72
+ throw new Error('Only even values are allowed!');
73
+ }
74
+ }
75
+ isGreaterThanOtherField(value) {
76
+ if (parseInt(value) <= parseInt(this.otherField)) {
77
+ throw new Error('Bar must be greater than otherField.');
78
+ }
79
+ }
80
+ }
81
+ }
82
+ }, { sequelize });
83
+ */
84
+ class Model extends Component_1.Component {
85
+ constructor(sequelize) {
86
+ super();
87
+ this._attributes = {};
88
+ this._errors = {};
89
+ this._tableName = this.alias();
90
+ BaseChyz_1.default.debug("Model constructor", this._tableName);
91
+ // this._sequelize = BaseChyz.getComponent("db").db;
92
+ if (sequelize != null)
93
+ this._provider = sequelize;
94
+ else
95
+ this._provider = this.getDb();
96
+ if (!Utils_1.Utils.isEmpty(this.attributes())) {
97
+ this._model = this._provider.define(this._tableName, this.attributes(), {
98
+ tableName: this.tableName(),
99
+ timestamps: false,
100
+ createdAt: false,
101
+ updateAt: false
102
+ });
103
+ }
104
+ else {
105
+ throw new InvalidConfigException_1.InvalidConfigException(BaseChyz_1.default.t("Invalid model configuration, is not emty attributes"));
106
+ }
107
+ // this.init();
108
+ }
109
+ /**
110
+ * Returns the database connection used by this AR class.
111
+ * By default, the "db" application component is used as the database connection.
112
+ * You may override this method if you want to use a different database connection.
113
+ * @return Connection the database connection used by this AR class.
114
+ */
115
+ getDb() {
116
+ return BaseChyz_1.default.getComponent("db").db;
117
+ }
118
+ getDbConnection() {
119
+ return BaseChyz_1.default.getComponent("db");
120
+ }
121
+ get provider() {
122
+ return this._provider;
123
+ }
124
+ set provider(value) {
125
+ this._provider = value;
126
+ }
127
+ /**
128
+ *
129
+ */
130
+ get errors() {
131
+ return this._errors;
132
+ }
133
+ set errors(value) {
134
+ this._errors = value;
135
+ }
136
+ init() {
137
+ BaseChyz_1.default.debug("Model init....", this.constructor.name);
138
+ /**
139
+ * init buraya
140
+ */
141
+ BaseChyz_1.default.debug("Relation init....", this.constructor.name);
142
+ for (const relation of this.relations()) {
143
+ let m = relation.model;
144
+ if (relation.type == "hasOne") {
145
+ // @ts-ignore
146
+ delete relation.model;
147
+ this.model().hasOne(m, relation);
148
+ }
149
+ //
150
+ if (relation.type == "hasMany") {
151
+ // @ts-ignore
152
+ delete relation.model;
153
+ this.model().hasMany(m, relation);
154
+ }
155
+ if (relation.type == "belongsTo") {
156
+ // @ts-ignore
157
+ delete relation.model;
158
+ this.model().belongsTo(m, relation);
159
+ }
160
+ if (relation.type == "belongsToMany") {
161
+ // @ts-ignore
162
+ delete relation.model;
163
+ this.model().belongsToMany(m, relation);
164
+ }
165
+ }
166
+ }
167
+ alias() {
168
+ return this.constructor.name;
169
+ }
170
+ tableName() {
171
+ return this._tableName;
172
+ }
173
+ formName() {
174
+ return this.constructor.name;
175
+ }
176
+ rules() {
177
+ return [];
178
+ }
179
+ setModel(value) {
180
+ this._model = value;
181
+ }
182
+ model() {
183
+ return this._model;
184
+ }
185
+ save(params = {}, options = {}) {
186
+ return __awaiter(this, void 0, void 0, function* () {
187
+ this.errors = {};
188
+ // now instantiate an object
189
+ let p = Object.assign(params, this._attributes);
190
+ let result;
191
+ try {
192
+ result = yield this.model().create(p, options);
193
+ }
194
+ catch (e) {
195
+ BaseChyz_1.default.debug(`Model[${this.constructor.name}].create`, e);
196
+ if (e instanceof sequelize_1.ValidationError) {
197
+ let validationErrorItems = e.errors;
198
+ validationErrorItems.forEach(({ message, path }) => {
199
+ // @ts-ignore
200
+ this._errors[path] = message;
201
+ });
202
+ return false;
203
+ }
204
+ else if (e instanceof sequelize_1.DatabaseError) {
205
+ }
206
+ else if (e instanceof sequelize_1.TimeoutError) {
207
+ }
208
+ else if (e instanceof sequelize_1.UniqueConstraintError) {
209
+ }
210
+ else if (e instanceof sequelize_1.ForeignKeyConstraintError) {
211
+ }
212
+ else if (e instanceof sequelize_1.ExclusionConstraintError) {
213
+ }
214
+ throw new Exception_1.Exception(e.message, this.errors, e.code);
215
+ }
216
+ return result;
217
+ });
218
+ }
219
+ bulkCreate(params = {}, options = {}) {
220
+ return __awaiter(this, void 0, void 0, function* () {
221
+ this.errors = {};
222
+ // now instantiate an object
223
+ let p = Object.assign(params, this._attributes);
224
+ let result;
225
+ try {
226
+ result = yield this.model().bulkCreate(p, options);
227
+ }
228
+ catch (e) {
229
+ BaseChyz_1.default.debug(`Model[${this.constructor.name}].bulkCreate`, e);
230
+ if (e instanceof sequelize_1.ValidationError) {
231
+ let validationErrorItems = e.errors;
232
+ validationErrorItems.forEach(({ message, path }) => {
233
+ // @ts-ignore
234
+ this._errors[path] = message;
235
+ });
236
+ return false;
237
+ }
238
+ else if (e instanceof sequelize_1.DatabaseError) {
239
+ }
240
+ else if (e instanceof sequelize_1.TimeoutError) {
241
+ }
242
+ else if (e instanceof sequelize_1.UniqueConstraintError) {
243
+ }
244
+ else if (e instanceof sequelize_1.ForeignKeyConstraintError) {
245
+ }
246
+ else if (e instanceof sequelize_1.ExclusionConstraintError) {
247
+ }
248
+ throw new Exception_1.Exception(e.message, this.errors, e.code);
249
+ }
250
+ return result;
251
+ });
252
+ }
253
+ update(params = {}, options = {}) {
254
+ this.errors = {};
255
+ let p = Object.assign(params, this._attributes);
256
+ return this.model().update(p, options);
257
+ }
258
+ delete(params = {}, options = {}) {
259
+ this.errors = {};
260
+ let p = Object.assign(params, this._attributes);
261
+ return this.model().destroy(p, options);
262
+ }
263
+ /**
264
+ * As there are often use cases in which it is just easier to execute raw / already prepared SQL queries, you can use the sequelize.query method.
265
+ *
266
+ * By default the function will return two arguments - a results array, and an object containing metadata (such as amount of affected rows, etc). Note that since this is a raw query, the metadata are dialect specific. Some dialects return the metadata "within" the results object (as properties on an array). However, two arguments will always be returned, but for MSSQL and MySQL it will be two references to the same object.
267
+ *
268
+ * const [results, metadata] = await sequelize.query("UPDATE users SET y = 42 WHERE x = 12");
269
+ * // Results will be an empty array and metadata will contain the number of affected rows.
270
+ *
271
+ * In cases where you don't need to access the metadata you can pass in a query type to tell sequelize how to format the results. For example, for a simple select query you could do:
272
+ *
273
+ * const { QueryTypes } = require('@sequelize/core');
274
+ * const users = await sequelize.query("SELECT * FROM `users`", { type: QueryTypes.SELECT });
275
+ * // We didn't need to destructure the result here - the results were returned directly
276
+ *
277
+ * Several other query types are available. Peek into the source for details.
278
+ *
279
+ * A second option is the model. If you pass a model the returned data will be instances of that model.
280
+ *
281
+ * // Callee is the model definition. This allows you to easily map a query to a predefined model
282
+ * const projects = await sequelize.query('SELECT * FROM projects', {
283
+ * model: Projects,
284
+ * mapToModel: true // pass true here if you have any mapped fields
285
+ * });
286
+ * // Each element of `projects` is now an instance of Project
287
+ *
288
+ * See more options in the query API reference. Some examples:
289
+ * ``
290
+ * const { QueryTypes } = require('@sequelize/core');
291
+ * await sequelize.query('SELECT 1', {
292
+ * // A function (or false) for logging your queries
293
+ * // Will get called for every SQL query that gets sent
294
+ * // to the server.
295
+ * logging: console.log,
296
+ *
297
+ * // If plain is true, then sequelize will only return the first
298
+ * // record of the result set. In case of false it will return all records.
299
+ * plain: false,
300
+ *
301
+ * // Set this to true if you don't have a model definition for your query.
302
+ * raw: false,
303
+ *
304
+ * // The type of query you are executing. The query type affects how results are formatted before they are passed back.
305
+ * type: QueryTypes.SELECT
306
+ * });
307
+ *``
308
+ * // Note the second argument being null!
309
+ * // Even if we declared a callee here, the raw: true would
310
+ * // supersede and return a raw object.
311
+ * console.log(await sequelize.query('SELECT * FROM projects', { raw: true }));
312
+ *
313
+ * ##"Dotted" attributes and the nest option
314
+ *
315
+ * If an attribute name of the table contains dots, the resulting objects can become nested objects by setting the nest: true option. This is achieved with dottie.js under the hood. See below:
316
+ *
317
+ * Without nest: true:
318
+ * ``
319
+ * const { QueryTypes } = require('@sequelize/core');
320
+ * const records = await sequelize.query('select 1 as `foo.bar.baz`', {
321
+ * type: QueryTypes.SELECT
322
+ * });
323
+ * console.log(JSON.stringify(records[0], null, 2));
324
+ *
325
+ * {
326
+ * "foo.bar.baz": 1
327
+ * }
328
+ *
329
+ * With nest: true:
330
+ *
331
+ * const { QueryTypes } = require('@sequelize/core');
332
+ * const records = await sequelize.query('select 1 as `foo.bar.baz`', {
333
+ * nest: true,
334
+ * type: QueryTypes.SELECT
335
+ * });
336
+ * console.log(JSON.stringify(records[0], null, 2));
337
+ *
338
+ * {
339
+ * "foo": {
340
+ * "bar": {
341
+ * "baz": 1
342
+ * }
343
+ * }
344
+ * }
345
+ * ``
346
+ * ##Replacements
347
+ *
348
+ * Replacements in a query can be done in two different ways, either using named parameters (starting with :), or unnamed, represented by a ?. Replacements are passed in the options object.
349
+ *
350
+ * If an array is passed, ? will be replaced in the order that they appear in the array
351
+ * If an object is passed, :key will be replaced with the keys from that object. If the object contains keys not found in the query or vice versa, an exception will be thrown.
352
+ * ``
353
+ * const { QueryTypes } = require('@sequelize/core');
354
+ *
355
+ * await sequelize.query(
356
+ * 'SELECT * FROM projects WHERE status = ?',
357
+ * {
358
+ * replacements: ['active'],
359
+ * type: QueryTypes.SELECT
360
+ * }
361
+ * );
362
+ *
363
+ * await sequelize.query(
364
+ * 'SELECT * FROM projects WHERE status = :status',
365
+ * {
366
+ * replacements: { status: 'active' },
367
+ * type: QueryTypes.SELECT
368
+ * }
369
+ * );
370
+ * ``
371
+ * Array replacements will automatically be handled, the following query searches for projects where the status matches an array of values.
372
+ * ``
373
+ * const { QueryTypes } = require('@sequelize/core');
374
+ *
375
+ * await sequelize.query(
376
+ * 'SELECT * FROM projects WHERE status IN(:status)',
377
+ * {
378
+ * replacements: { status: ['active', 'inactive'] },
379
+ * type: QueryTypes.SELECT
380
+ * }
381
+ * );
382
+ * ``
383
+ * To use the wildcard operator %, append it to your replacement. The following query matches users with names that start with 'ben'.
384
+ * ``
385
+ * const { QueryTypes } = require('@sequelize/core');
386
+ *
387
+ * await sequelize.query(
388
+ * 'SELECT * FROM users WHERE name LIKE :search_name',
389
+ * {
390
+ * replacements: { search_name: 'ben%' },
391
+ * type: QueryTypes.SELECT
392
+ * }
393
+ * ); ``
394
+ *
395
+ * ##Bind Parameter
396
+ *
397
+ * Bind parameters are like replacements. Except replacements are escaped and inserted into the query by sequelize before the query is sent to the database, while bind parameters are sent to the database outside the SQL query text. A query can have either bind parameters or replacements. Bind parameters are referred to by either $1, $2, ... (numeric) or $key (alpha-numeric). This is independent of the dialect.
398
+ *
399
+ * If an array is passed, $1 is bound to the 1st element in the array (bind[0])
400
+ * If an object is passed, $key is bound to object['key']. Each key must begin with a non-numeric char. $1 is not a valid key, even if object['1'] exists.
401
+ * In either case $$ can be used to escape a literal $ sign.
402
+ *
403
+ * The array or object must contain all bound values or Sequelize will throw an exception. This applies even to cases in which the database may ignore the bound parameter.
404
+ *
405
+ * The database may add further restrictions to this. Bind parameters cannot be SQL keywords, nor table or column names. They are also ignored in quoted text or data. In PostgreSQL it may also be needed to typecast them, if the type cannot be inferred from the context $1::varchar.
406
+ *``
407
+ * const { QueryTypes } = require('@sequelize/core');
408
+ *
409
+ * await sequelize.query(
410
+ * 'SELECT *, "text with literal $$1 and literal $$status" as t FROM projects WHERE status = $1',
411
+ * {
412
+ * bind: ['active'],
413
+ * type: QueryTypes.SELECT
414
+ * }
415
+ * ); ``
416
+ *
417
+ * `` await sequelize.query(
418
+ * 'SELECT *, "text with literal $$1 and literal $$status" as t FROM projects WHERE status = $status',
419
+ * {
420
+ * bind: { status: 'active' },
421
+ * type: QueryTypes.SELECT
422
+ * }
423
+ * );``
424
+ * @param query
425
+ */
426
+ rawQuery(query, options = { type: sequelize_1.QueryTypes.SELECT, nest: true }) {
427
+ return __awaiter(this, void 0, void 0, function* () {
428
+ this.errors = {};
429
+ return yield this.model().query(query, options);
430
+ });
431
+ }
432
+ /**
433
+ *
434
+ * @param args
435
+ */
436
+ findOne(...args) {
437
+ return this._model.findOne(...arguments);
438
+ }
439
+ /**
440
+ *
441
+ * @param args
442
+ */
443
+ findAll(...args) {
444
+ return this._model.findAll(...arguments);
445
+ }
446
+ /**
447
+ * return {count : number , rows: any}
448
+ * @param args
449
+ */
450
+ findAndCountAll(...args) {
451
+ return this._model.findAndCountAll(...arguments);
452
+ }
453
+ validate() {
454
+ }
455
+ /**
456
+ *
457
+ * @param data
458
+ * @param formName
459
+ */
460
+ load(data, formName = null) {
461
+ let scope = formName === null ? this.formName() : formName;
462
+ if (scope === '' && !Utils_1.Utils.isEmpty(data)) {
463
+ this.setAttribute(data);
464
+ return true;
465
+ }
466
+ else if (data[scope]) {
467
+ this.setAttribute(data[scope]);
468
+ return true;
469
+ }
470
+ return false;
471
+ }
472
+ bulkLoad(data, formName = null) {
473
+ let scope = formName === null ? this.formName() : formName;
474
+ if (scope === '' && !Utils_1.Utils.isEmpty(data)) {
475
+ this.setAttribute(data);
476
+ return true;
477
+ }
478
+ else if (data[scope]) {
479
+ this.setAttribute(data[scope]);
480
+ return true;
481
+ }
482
+ return false;
483
+ }
484
+ setAttribute(values, safeOnly = true) {
485
+ if (values instanceof Object) {
486
+ let attributes = this.attributes();
487
+ for (const valueKey in values) {
488
+ if (Object.keys(attributes).indexOf(valueKey) != -1) {
489
+ // @ts-ignore
490
+ BaseChyz_1.default.debug("Model[" + this.formName() + "] attributes value set ", valueKey, values[valueKey]);
491
+ this._attributes[valueKey] = values[valueKey];
492
+ }
493
+ }
494
+ }
495
+ }
496
+ attributes() {
497
+ return {};
498
+ }
499
+ /**
500
+ * relation return array
501
+ * [
502
+ *
503
+ * ]
504
+ */
505
+ relations() {
506
+ return [];
507
+ }
508
+ }
509
+ exports.Model = Model;