not-node 6.3.51 → 6.3.52

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 (36) hide show
  1. package/package.json +1 -1
  2. package/src/core/fields/createdAt.js +1 -1
  3. package/src/exceptions/action.js +100 -0
  4. package/src/exceptions/db.js +5 -4
  5. package/src/exceptions/logic.js +14 -0
  6. package/src/logic/action.runner.js +15 -0
  7. package/src/logic/actions/increment/getByID.js +23 -0
  8. package/src/logic/actions/increment/index.js +1 -0
  9. package/src/logic/actions/index.js +8 -0
  10. package/src/logic/actions/standart/count.js +24 -0
  11. package/src/logic/actions/standart/create.js +21 -0
  12. package/src/logic/actions/standart/delete.js +28 -0
  13. package/src/logic/actions/standart/get.js +38 -0
  14. package/src/logic/actions/standart/getRaw.js +31 -0
  15. package/src/logic/actions/standart/index.js +11 -0
  16. package/src/logic/actions/standart/list.js +27 -0
  17. package/src/logic/actions/standart/listAll.js +21 -0
  18. package/src/logic/actions/standart/listAndCount.js +29 -0
  19. package/src/logic/actions/standart/update.js +30 -0
  20. package/src/logic/actions.before/index.js +7 -0
  21. package/src/logic/actions.before/ownage/index.js +3 -0
  22. package/src/logic/actions.before/ownage/ownage.js +57 -0
  23. package/src/logic/actions.before/populate/index.js +3 -0
  24. package/src/logic/actions.before/populate/populate.js +3 -0
  25. package/src/logic/actions.lib.js +18 -0
  26. package/src/logic/generic.action.after.js +6 -0
  27. package/src/logic/generic.action.before.js +6 -0
  28. package/src/logic/generic.js +51 -0
  29. package/src/logic/logic.js +224 -0
  30. package/src/logic/named.actions.pipes.js +102 -0
  31. package/src/model/default.js +44 -8
  32. package/src/model/utils.js +21 -12
  33. package/src/types.js +48 -0
  34. package/test/model/default.js +5 -0
  35. package/test/model/proto.js +2 -0
  36. package/test/notModel.js +2 -2
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "not-node",
3
- "version": "6.3.51",
3
+ "version": "6.3.52",
4
4
  "description": "node complimentary part for client side notFramework.",
5
5
  "main": "index.js",
6
6
  "scripts": {
@@ -12,7 +12,7 @@ module.exports = {
12
12
  searchable: true,
13
13
  sortable: true,
14
14
  safe: {
15
- update: ["@owner", "root", "admin"],
15
+ create: ["@system"],
16
16
  read: ["@owner", "root", "admin"],
17
17
  },
18
18
  },
@@ -0,0 +1,100 @@
1
+ const notRequestError = require("not-error/src/request.error.node.cjs");
2
+
3
+ //delete wasnt successful, or error, or count of deleted documents dont match requested
4
+ class ActionExceptionWrongType extends notRequestError {
5
+ constructor({ params = {}, cause = null } = {}) {
6
+ super("Logic cant run this action", { code: 505, params }, cause);
7
+ }
8
+ }
9
+ module.exports.ActionExceptionWrongType = ActionExceptionWrongType;
10
+
11
+ class ActionExceptionPipeExecutionError extends notRequestError {
12
+ constructor({ params = {}, cause = null } = {}) {
13
+ super(
14
+ "Logic cant run this actions sequence",
15
+ { code: 505, params },
16
+ cause
17
+ );
18
+ }
19
+ }
20
+ module.exports.ActionExceptionPipeExecutionError =
21
+ ActionExceptionPipeExecutionError;
22
+
23
+ class OwnageExceptionIdentityUserIdIsNotDefined extends notRequestError {
24
+ constructor(actionName, identity) {
25
+ super(
26
+ "User identity `uid` is not defined, ownage couldnt be determined",
27
+ { code: 505, params: { actionName, identity } },
28
+ null
29
+ );
30
+ }
31
+ }
32
+ module.exports.OwnageExceptionIdentityUserIdIsNotDefined =
33
+ OwnageExceptionIdentityUserIdIsNotDefined;
34
+
35
+ class LogicDeleteActionException extends notRequestError {
36
+ constructor(params, cause) {
37
+ super("Logic Delete Action exception", { code: 505, params }, cause);
38
+ }
39
+ }
40
+ module.exports.LogicDeleteActionException = LogicDeleteActionException;
41
+
42
+ class LogicCreateActionException extends notRequestError {
43
+ constructor(params, cause) {
44
+ super("Logic Create Action exception", { code: 505, params }, cause);
45
+ }
46
+ }
47
+ module.exports.LogicCreateActionException = LogicCreateActionException;
48
+ class LogicUpdateActionException extends notRequestError {
49
+ constructor(params, cause) {
50
+ super("Logic Update Action exception", { code: 505, params }, cause);
51
+ }
52
+ }
53
+ module.exports.LogicUpdateActionException = LogicUpdateActionException;
54
+
55
+ class LogicCountActionException extends notRequestError {
56
+ constructor(params, cause) {
57
+ super("Logic Count Action exception", { code: 505, params }, cause);
58
+ }
59
+ }
60
+ module.exports.LogicCountActionException = LogicCountActionException;
61
+
62
+ class LogicListAndCountActionException extends notRequestError {
63
+ constructor(params, cause) {
64
+ super(
65
+ "Logic ListAndCount Action exception",
66
+ { code: 505, params },
67
+ cause
68
+ );
69
+ }
70
+ }
71
+ module.exports.LogicListAndCountActionException =
72
+ LogicListAndCountActionException;
73
+
74
+ class LogicGetActionException extends notRequestError {
75
+ constructor(params, cause) {
76
+ super("Logic Get Action exception", { code: 505, params }, cause);
77
+ }
78
+ }
79
+ module.exports.LogicGetActionException = LogicGetActionException;
80
+
81
+ class LogicGetRawActionException extends notRequestError {
82
+ constructor(params, cause) {
83
+ super("Logic GetRaw Action exception", { code: 505, params }, cause);
84
+ }
85
+ }
86
+ module.exports.LogicGetRawActionException = LogicGetRawActionException;
87
+
88
+ class LogicListActionException extends notRequestError {
89
+ constructor(params, cause) {
90
+ super("Logic List Action exception", { code: 505, params }, cause);
91
+ }
92
+ }
93
+ module.exports.LogicListActionException = LogicListActionException;
94
+
95
+ class LogicListAllActionException extends notRequestError {
96
+ constructor(params, cause) {
97
+ super("Logic ListAll Action exception", { code: 505, params }, cause);
98
+ }
99
+ }
100
+ module.exports.LogicListAllActionException = LogicListAllActionException;
@@ -1,11 +1,12 @@
1
- const { notRequestError } = require("not-error");
1
+ const { notError, notRequestError } = require("not-error/src/index.cjs");
2
2
 
3
3
  //delete wasnt successful, or error, or count of deleted documents dont match requested
4
- class DBExceptionDeleteWasNotSuccessful extends notRequestError {
5
- constructor({ params = {}, cause = null } = {}) {
6
- super("DB Delete Was Not Successful", { code: 505, ...params }, cause);
4
+ class DBExceptionDeleteWasNotSuccessful extends notError {
5
+ constructor(result) {
6
+ super("DB Delete Was Not Successful", result);
7
7
  }
8
8
  }
9
+
9
10
  module.exports.DBExceptionDeleteWasNotSuccessful =
10
11
  DBExceptionDeleteWasNotSuccessful;
11
12
 
@@ -0,0 +1,14 @@
1
+ const notRequestError = require("not-error/src/request.error.node.cjs");
2
+
3
+ //delete wasnt successful, or error, or count of deleted documents dont match requested
4
+ class LogicExceptionActionExecutionError extends notRequestError {
5
+ constructor(moduleName, modelName, actionName, cause) {
6
+ super(
7
+ "Logic cant run this action",
8
+ { code: 505, params: { moduleName, modelName, actionName } },
9
+ cause
10
+ );
11
+ }
12
+ }
13
+ module.exports.LogicExceptionActionExecutionError =
14
+ LogicExceptionActionExecutionError;
@@ -0,0 +1,15 @@
1
+ const { ActionExceptionWrongType } = require("../exceptions/action.js");
2
+
3
+ class ActionRunner {
4
+ static async run(action, params) {
5
+ //any static class with static run method
6
+ if (typeof action === "function" && typeof action.run === "function") {
7
+ return await action.run(...params);
8
+ } else if (typeof action === "function") {
9
+ return await action(...params);
10
+ }
11
+ throw new ActionExceptionWrongType();
12
+ }
13
+ }
14
+
15
+ module.exports = ActionRunner;
@@ -0,0 +1,23 @@
1
+ module.exports = class GetByIDAction {
2
+ static async run(
3
+ logic,
4
+ actionName,
5
+ { targetID, identity, defaultQueryByID }
6
+ ) {
7
+ logic.logDebugAction(actionName, identity);
8
+
9
+ let populate = await logic.getPopulate(actionName, {
10
+ targetID,
11
+ identity,
12
+ });
13
+
14
+ const result = await logic
15
+ .getModel()
16
+ .getOneByID(targetID, defaultQueryByID, populate);
17
+ logic.logAction(actionName, identity, {
18
+ targetID,
19
+ version: result?.__version,
20
+ });
21
+ return result;
22
+ }
23
+ };
@@ -0,0 +1 @@
1
+ module.exports = { getByID: require("./getByID.js") };
@@ -0,0 +1,8 @@
1
+ const ActionsSetsLibrary = require("../actions.lib");
2
+
3
+ let actionsSetsLibrary = new ActionsSetsLibrary();
4
+
5
+ actionsSetsLibrary.add("standart", require("./standart"));
6
+ actionsSetsLibrary.add("increment", require("./increment"));
7
+
8
+ module.exports = actionsSetsLibrary;
@@ -0,0 +1,24 @@
1
+ const { LogicCountActionException } = require("../../../exceptions/action");
2
+
3
+ module.exports = class CountAction {
4
+ static async run(logic, actionName, { identity, query }) {
5
+ try {
6
+ logic.logDebugAction(actionName, identity);
7
+ const { filter, search } = query;
8
+ const result = await logic
9
+ .getModel()
10
+ .countWithFilter(search || filter);
11
+ logic.logAction(actionName, identity);
12
+ return result;
13
+ } catch (e) {
14
+ throw new LogicCountActionException(
15
+ {
16
+ query,
17
+ activeUserId: identity?.uid,
18
+ role: identity?.role,
19
+ },
20
+ e
21
+ );
22
+ }
23
+ }
24
+ };
@@ -0,0 +1,21 @@
1
+ const { LogicCreateActionException } = require("../../../exceptions/action");
2
+ module.exports = class CreateAction {
3
+ static async run(logic, actionName, { identity, data }) {
4
+ try {
5
+ logic.logDebugAction(actionName, identity);
6
+ const result = await logic.getModel().add(data);
7
+ logic.logAction(actionName, identity, {
8
+ targetId: result?._id,
9
+ });
10
+ return result;
11
+ } catch (e) {
12
+ throw new LogicCreateActionException(
13
+ {
14
+ activeUserId: identity?.uid,
15
+ role: identity?.role,
16
+ },
17
+ e
18
+ );
19
+ }
20
+ }
21
+ };
@@ -0,0 +1,28 @@
1
+ const { LogicDeleteActionException } = require("../../../exceptions/action.js");
2
+ module.exports = class DeleteAction {
3
+ static async run(
4
+ logic,
5
+ actionName,
6
+ { identity, defaultQueryById, targetId }
7
+ ) {
8
+ logic.logDebugAction(actionName, identity);
9
+ /** @type {import('../../../types.js').notAppModel } */
10
+ const model = logic.getModel();
11
+ try {
12
+ await model.removeOne(defaultQueryById);
13
+ logic.logAction(actionName, identity, {
14
+ query: defaultQueryById,
15
+ });
16
+ } catch (e) {
17
+ throw new LogicDeleteActionException(
18
+ {
19
+ targetId,
20
+ query: defaultQueryById,
21
+ activeUserId: identity?.uid,
22
+ role: identity?.role,
23
+ },
24
+ e
25
+ );
26
+ }
27
+ }
28
+ };
@@ -0,0 +1,38 @@
1
+ const { LogicGetActionException } = require("../../../exceptions/action");
2
+
3
+ module.exports = class GetAction {
4
+ static async run(
5
+ logic,
6
+ actionName,
7
+ { identity, defaultQueryById, targetId }
8
+ ) {
9
+ try {
10
+ logic.logDebugAction(actionName, identity);
11
+
12
+ let populate = await logic.getPopulate(actionName, {
13
+ targetId,
14
+ identity,
15
+ });
16
+
17
+ const result = await logic
18
+ .getModel()
19
+ .getOne(targetId, populate, defaultQueryById);
20
+
21
+ logic.logAction(actionName, identity, {
22
+ targetId,
23
+ version: result?.__version,
24
+ });
25
+ return result;
26
+ } catch (e) {
27
+ throw new LogicGetActionException(
28
+ {
29
+ targetId,
30
+ query: defaultQueryById,
31
+ activeUserId: identity?.uid,
32
+ role: identity?.role,
33
+ },
34
+ e
35
+ );
36
+ }
37
+ }
38
+ };
@@ -0,0 +1,31 @@
1
+ const { LogicGetRawActionException } = require("../../../exceptions/action");
2
+
3
+ module.exports = class GetRawAction {
4
+ static async run(
5
+ logic,
6
+ actionName,
7
+ { identity, defaultQueryById, targetId }
8
+ ) {
9
+ try {
10
+ logic.logDebugAction(actionName, identity);
11
+ const result = await logic
12
+ .getModel()
13
+ .getOneRaw(targetId, defaultQueryById);
14
+ logic.logAction(actionName, identity, {
15
+ targetId,
16
+ version: result?.__version,
17
+ });
18
+ return result;
19
+ } catch (e) {
20
+ throw new LogicGetRawActionException(
21
+ {
22
+ targetId,
23
+ query: defaultQueryById,
24
+ activeUserId: identity?.uid,
25
+ role: identity?.role,
26
+ },
27
+ e
28
+ );
29
+ }
30
+ }
31
+ };
@@ -0,0 +1,11 @@
1
+ module.exports = {
2
+ count: require("./count.js"),
3
+ create: require("./create.js"),
4
+ delete: require("./delete.js"),
5
+ get: require("./get.js"),
6
+ getRaw: require("./getRaw.js"),
7
+ list: require("./list.js"),
8
+ listAll: require("./listAll.js"),
9
+ listAndCount: require("./listAndCount.js"),
10
+ update: require("./update.js"),
11
+ };
@@ -0,0 +1,27 @@
1
+ const { LogicListActionException } = require("../../../exceptions/action");
2
+
3
+ module.exports = class ListAction {
4
+ static async run(logic, actionName, { identity, query }) {
5
+ try {
6
+ logic.logDebugAction(actionName, identity);
7
+ const { skip, size, sorter, filter } = query;
8
+ let populate = await logic.getPopulate(actionName, {
9
+ identity,
10
+ });
11
+ const result = await logic
12
+ .getModel()
13
+ .listAndPopulate(skip, size, sorter, filter, populate);
14
+ logic.logAction(actionName, identity, {});
15
+ return result;
16
+ } catch (e) {
17
+ throw new LogicListActionException(
18
+ {
19
+ query,
20
+ activeUserId: identity?.uid,
21
+ role: identity?.role,
22
+ },
23
+ e
24
+ );
25
+ }
26
+ }
27
+ };
@@ -0,0 +1,21 @@
1
+ const { LogicListAllActionException } = require("../../../exceptions/action");
2
+
3
+ module.exports = class ListAllAction {
4
+ static async run(logic, actionName, { identity, defaultQueryMany }) {
5
+ try {
6
+ logic.logDebugAction(actionName, identity);
7
+ const result = await logic.getModel().listAll(defaultQueryMany);
8
+ logic.logAction(actionName, identity, {});
9
+ return result;
10
+ } catch (e) {
11
+ throw new LogicListAllActionException(
12
+ {
13
+ query: defaultQueryMany,
14
+ activeUserId: identity?.uid,
15
+ role: identity?.role,
16
+ },
17
+ e
18
+ );
19
+ }
20
+ }
21
+ };
@@ -0,0 +1,29 @@
1
+ const {
2
+ LogicListAndCountActionException,
3
+ } = require("../../../exceptions/action");
4
+
5
+ module.exports = class ListAndCountAction {
6
+ static async run(logic, actionName, { identity, query }) {
7
+ try {
8
+ logic.logDebugAction(actionName, identity);
9
+ const { skip, size, sorter, filter, search } = query;
10
+ let populate = await logic.getPopulate(actionName, {
11
+ identity,
12
+ });
13
+ const result = await logic
14
+ .getModel()
15
+ .listAndCount(skip, size, sorter, filter, search, populate);
16
+ logic.logAction(actionName, identity, {});
17
+ return result;
18
+ } catch (e) {
19
+ throw new LogicListAndCountActionException(
20
+ {
21
+ query,
22
+ activeUserId: identity?.uid,
23
+ role: identity?.role,
24
+ },
25
+ e
26
+ );
27
+ }
28
+ }
29
+ };
@@ -0,0 +1,30 @@
1
+ const { LogicUpdateActionException } = require("../../../exceptions/action");
2
+ module.exports = class UpdateAction {
3
+ static async run(
4
+ logic,
5
+ actionName,
6
+ { identity, data, targetId, defaultQueryById }
7
+ ) {
8
+ try {
9
+ logic.logDebugAction(actionName, identity);
10
+ const result = await logic
11
+ .getModel()
12
+ .update(defaultQueryById, data);
13
+ logic.logAction(actionName, identity, {
14
+ targetId,
15
+ version: result?.__version,
16
+ });
17
+ return result;
18
+ } catch (e) {
19
+ throw new LogicUpdateActionException(
20
+ {
21
+ targetId,
22
+ query: defaultQueryById,
23
+ activeUserId: identity?.uid,
24
+ role: identity?.role,
25
+ },
26
+ e
27
+ );
28
+ }
29
+ }
30
+ };
@@ -0,0 +1,7 @@
1
+ const ActionsSetsLibrary = require("../actions.lib.js");
2
+
3
+ const ActionsBefore = new ActionsSetsLibrary();
4
+
5
+ ActionsBefore.add("ownage", require("./ownage"));
6
+
7
+ module.exports = ActionsBefore;
@@ -0,0 +1,3 @@
1
+ module.exports = {
2
+ ownage: require("./ownage.js"),
3
+ };
@@ -0,0 +1,57 @@
1
+ const notFilter = require("not-filter");
2
+ const { DOCUMENT_OWNER_FIELD_NAME } = require("../../../auth/const.js");
3
+ const {
4
+ OwnageExceptionIdentityUserIdIsNotDefined,
5
+ } = require("../../../exceptions/action.js");
6
+ const ModelRoutine = require("../../../model/routine.js");
7
+
8
+ //checks that
9
+ module.exports = class OwnageBeforeAction {
10
+ static #ownerFieldName = DOCUMENT_OWNER_FIELD_NAME;
11
+
12
+ static get ownerFieldName() {
13
+ return this.#ownerFieldName;
14
+ }
15
+
16
+ static async run(logic, actionName, args) {
17
+ const { identity, data, query, targetId, targetID } = args;
18
+ if (identity.uid) {
19
+ //if searching, counting, listing and so on
20
+ //adding condition of ownership by this excat user
21
+ const { filter, search } = query;
22
+ if (filter) {
23
+ notFilter.filter.modifyRules(filter, {
24
+ [OwnageBeforeAction.ownerFieldName]: identity?.uid,
25
+ });
26
+ if (search) {
27
+ notFilter.filter.modifyRules(search, filter);
28
+ }
29
+ }
30
+ args.defaultQueryById = {
31
+ _id: targetId,
32
+ [OwnageBeforeAction.ownerFieldName]: identity?.uid,
33
+ };
34
+ const Model = logic.getModel();
35
+ const incFieldName = ModelRoutine.incremental(Model);
36
+ if (incFieldName) {
37
+ args.defaultQueryByID = {
38
+ [incFieldName]: targetID,
39
+ [OwnageBeforeAction.ownerFieldName]: identity?.uid,
40
+ };
41
+ }
42
+
43
+ args.defaultQueryMany = {
44
+ [OwnageBeforeAction.ownerFieldName]: identity?.uid,
45
+ };
46
+ //mark data as owned by
47
+ if (data) {
48
+ data[OwnageBeforeAction.ownerFieldName] = identity.uid;
49
+ }
50
+ } else {
51
+ throw new OwnageExceptionIdentityUserIdIsNotDefined(
52
+ actionName,
53
+ identity
54
+ );
55
+ }
56
+ }
57
+ };
@@ -0,0 +1,3 @@
1
+ module.exports = {
2
+ populate: require("./populate.js"),
3
+ };
@@ -0,0 +1,3 @@
1
+ module.exports = class PopulateBeforeAction {
2
+ static async run(/*logic, actionName, args*/) {}
3
+ };
@@ -0,0 +1,18 @@
1
+ class ActionsSetsLibrary {
2
+ #lib = new Map();
3
+
4
+ add(name, set) {
5
+ if (!this.#lib.has(name)) {
6
+ this.#lib.set(name, set);
7
+ }
8
+ }
9
+
10
+ get(name) {
11
+ if (this.#lib.has(name)) {
12
+ return this.#lib.get(name);
13
+ }
14
+ return {};
15
+ }
16
+ }
17
+
18
+ module.exports = ActionsSetsLibrary;
@@ -0,0 +1,6 @@
1
+ //reference only
2
+ module.exports = class GenericAfterAction {
3
+ static async run(logic, actionName, actionResult, ...args) {
4
+ return [actionResult, ...args];
5
+ }
6
+ };
@@ -0,0 +1,6 @@
1
+ //reference only
2
+ module.exports = class GenericBeforeAction {
3
+ static async run(logic, actionName, ...args) {
4
+ return [...args];
5
+ }
6
+ };
@@ -0,0 +1,51 @@
1
+ const actionsSetsLibrary = require("./actions/index.js");
2
+ const LogicProxied = require("./logic.js");
3
+
4
+ module.exports = ({
5
+ target,
6
+ LogicConstructor = LogicProxied,
7
+ MODULE_NAME,
8
+ MODEL_NAME,
9
+ USER_MODEL_NAME = "not-user//User",
10
+ actionRunner = undefined,
11
+ actionsSets = ["standart"],
12
+ actions = {},
13
+ beforeActions = {},
14
+ beforeActionsAll = [],
15
+ afterActions = {},
16
+ afterActionsAll = [],
17
+ }) => {
18
+ //start with empty set
19
+ const ACTIONS = {};
20
+ //add all from actions sets library
21
+ actionsSets.forEach((setName) => {
22
+ actionsSetsLibrary[setName] &&
23
+ Object.assign(ACTIONS, actionsSetsLibrary[setName]);
24
+ });
25
+ //add user defined
26
+ Object.assign(ACTIONS, actions);
27
+
28
+ const Logic = new LogicConstructor(ACTIONS, actionRunner, {
29
+ MODULE_NAME,
30
+ MODEL_NAME,
31
+ target,
32
+ USER_MODEL_NAME,
33
+ });
34
+
35
+ beforeActionsAll.forEach((action) => Logic.onBefore(undefined, action));
36
+ afterActionsAll.forEach((action) => Logic.onAfter(undefined, action));
37
+
38
+ Object.keys(beforeActions).forEach((actionName) =>
39
+ beforeActions[actionName].forEach((action) =>
40
+ Logic.onBefore(actionName, action)
41
+ )
42
+ );
43
+
44
+ Object.keys(afterActions).forEach((actionName) =>
45
+ afterActions[actionName].forEach((action) =>
46
+ Logic.onAfter(actionName, action)
47
+ )
48
+ );
49
+
50
+ return Logic;
51
+ };
@@ -0,0 +1,224 @@
1
+ const getApp = require("../getApp.js"),
2
+ configInit = require("not-config"),
3
+ { sayForModule, modulePhrase } = require("not-locale"),
4
+ LogInit = require("not-log"),
5
+ { objHas, isFunc, executeFunctionAsAsync } = require("../common.js");
6
+
7
+ const NamedActionPipes = require("./named.actions.pipes.js");
8
+ const ActionRunner = require("./action.runner.js");
9
+ const {
10
+ LogicExceptionActionExecutionError,
11
+ } = require("../exceptions/logic.js");
12
+
13
+ class LogicProxied {
14
+ #afterPipes;
15
+ #beforePipes;
16
+
17
+ #actions = new Map();
18
+ #actionRunner = ActionRunner;
19
+
20
+ #populateBuilders = {};
21
+ #defaultPopulate = [];
22
+
23
+ #MODEL_NAME;
24
+ #MODULE_NAME;
25
+ #USER_MODEL_NAME = "";
26
+
27
+ #log;
28
+ #say;
29
+ #phrase;
30
+ #config;
31
+ #logAction;
32
+ #logDebugAction;
33
+
34
+ get log() {
35
+ return this.#log;
36
+ }
37
+ get say() {
38
+ return this.#say;
39
+ }
40
+ get phrase() {
41
+ return this.#phrase;
42
+ }
43
+
44
+ get config() {
45
+ return this.#config;
46
+ }
47
+
48
+ get logAction() {
49
+ return this.#logAction;
50
+ }
51
+
52
+ get logDebugAction() {
53
+ return this.#logDebugAction;
54
+ }
55
+
56
+ constructor(
57
+ actions = {},
58
+ actionRunner = ActionRunner,
59
+ {
60
+ MODULE_NAME,
61
+ MODEL_NAME,
62
+ target,
63
+ defaultPopulate,
64
+ populateBuilders,
65
+ USER_MODEL_NAME = "not-user//User",
66
+ }
67
+ ) {
68
+ this.#MODEL_NAME = MODEL_NAME;
69
+ this.#MODULE_NAME = MODULE_NAME;
70
+ this.#USER_MODEL_NAME = USER_MODEL_NAME;
71
+
72
+ defaultPopulate && (this.#defaultPopulate = defaultPopulate);
73
+ populateBuilders && (this.#populateBuilders = populateBuilders);
74
+
75
+ actionRunner && (this.#actionRunner = actionRunner);
76
+ this.#afterPipes = new NamedActionPipes(
77
+ NamedActionPipes.PIPE_TYPES.CONSECUTIVE,
78
+ this.#actionRunner
79
+ );
80
+ this.#beforePipes = new NamedActionPipes(
81
+ NamedActionPipes.PIPE_TYPES.CONSECUTIVE,
82
+ this.#actionRunner
83
+ );
84
+
85
+ Object.keys(actions).forEach((actionName) => {
86
+ this.#actions.set(actionName, actions[actionName]);
87
+ });
88
+
89
+ this.#initTools(target);
90
+
91
+ // proxy logic, do something before each call of all methods inside class
92
+ // like if arg passed is 3, print something additionally
93
+ return new Proxy(this, {
94
+ get(target, prop) {
95
+ if (target.#actions.has(prop)) {
96
+ return target.#getActionRunner(prop);
97
+ } else {
98
+ return target[prop];
99
+ }
100
+ },
101
+ });
102
+ }
103
+
104
+ #initTools(target) {
105
+ this.#log = LogInit(
106
+ target,
107
+ `${this.#MODULE_NAME}//Logic//${this.#MODEL_NAME}`
108
+ );
109
+ this.#say = sayForModule(this.#MODULE_NAME);
110
+ this.#phrase = modulePhrase(this.#MODULE_NAME);
111
+ this.#config = configInit.readerForModule(this.#MODULE_NAME);
112
+
113
+ this.#logAction = (actionName, identity, params = {}) => {
114
+ this.#log &&
115
+ this.#log.log({
116
+ time: new Date(),
117
+ module: this.#MODULE_NAME,
118
+ logic: this.#MODEL_NAME,
119
+ action: actionName,
120
+ ...identity,
121
+ params,
122
+ });
123
+ };
124
+ this.#logDebugAction = (action, identity) => {
125
+ this.#log &&
126
+ this.#log.debug(
127
+ new Date(),
128
+ `${this.#MODULE_NAME}//Logic//${
129
+ this.#MODEL_NAME
130
+ }//${action}`,
131
+ identity?.ip,
132
+ identity?.root
133
+ );
134
+ };
135
+ }
136
+
137
+ getModel() {
138
+ return getApp().getModel(`${this.#MODULE_NAME}//${this.#MODEL_NAME}`);
139
+ }
140
+
141
+ getModelSchema() {
142
+ return getApp().getModelSchema(
143
+ `${this.#MODULE_NAME}//${this.#MODEL_NAME}`
144
+ );
145
+ }
146
+
147
+ getModelUser() {
148
+ return this.#USER_MODEL_NAME
149
+ ? getApp().getModel(this.#USER_MODEL_NAME)
150
+ : undefined;
151
+ }
152
+
153
+ async getPopulate(actionName, prepared) {
154
+ if (
155
+ this.#populateBuilders &&
156
+ objHas(this.#populateBuilders, actionName) &&
157
+ isFunc(this.#populateBuilders[actionName])
158
+ ) {
159
+ return await executeFunctionAsAsync(
160
+ this.#populateBuilders[actionName],
161
+ [prepared]
162
+ );
163
+ }
164
+ return this.#defaultPopulate;
165
+ }
166
+
167
+ #getActionRunner(actionName) {
168
+ return async (...args) => {
169
+ try {
170
+ const action = this.#actions.get(actionName);
171
+ await this.#beforeAction(actionName, [
172
+ this,
173
+ actionName,
174
+ ...args,
175
+ ]);
176
+ const actionResult = await this.#actionRunner.run(action, [
177
+ this,
178
+ actionName,
179
+ ...args,
180
+ ]);
181
+ await this.#afterAction(actionName, [
182
+ this,
183
+ actionName,
184
+ actionResult,
185
+ ...args,
186
+ ]);
187
+ return actionResult;
188
+ } catch (e) {
189
+ throw new LogicExceptionActionExecutionError(
190
+ this.#MODULE_NAME,
191
+ this.#MODEL_NAME,
192
+ actionName,
193
+ e
194
+ );
195
+ }
196
+ };
197
+ }
198
+
199
+ async #beforeAction(actionName, args) {
200
+ await this.#beforePipes.execute(actionName, args);
201
+ }
202
+
203
+ async #afterAction(actionName, args) {
204
+ await this.#afterPipes.execute(actionName, args);
205
+ }
206
+
207
+ onAfter(name, action) {
208
+ this.#afterPipes.add(name, action);
209
+ }
210
+
211
+ offAfter(name, action) {
212
+ this.#afterPipes.remove(name, action);
213
+ }
214
+
215
+ onBefore(name, action) {
216
+ this.#beforePipes.add(name, action);
217
+ }
218
+
219
+ offBefore(name, action) {
220
+ this.#beforePipes.remove(name, action);
221
+ }
222
+ }
223
+
224
+ module.exports = LogicProxied;
@@ -0,0 +1,102 @@
1
+ const { objHas } = require("../common.js");
2
+ const {
3
+ ActionExceptionPipeExecutionError,
4
+ } = require("../exceptions/action.js");
5
+
6
+ const ActionRunner = require("./action.runner.js");
7
+
8
+ const CONSECUTIVE = 1;
9
+ const PARALLEL = 2;
10
+
11
+ const PIPE_TYPES = { CONSECUTIVE, PARALLEL };
12
+ Object.freeze(PIPE_TYPES);
13
+
14
+ class NamedActionPipes {
15
+ static PIPE_TYPES = PIPE_TYPES;
16
+ #type = CONSECUTIVE;
17
+ #all = [];
18
+ #named = {};
19
+ #actionRunner = ActionRunner;
20
+
21
+ constructor(type = CONSECUTIVE, actionRunner = ActionRunner) {
22
+ this.#type = type;
23
+ actionRunner && (this.#actionRunner = actionRunner);
24
+ }
25
+
26
+ add(name, action) {
27
+ if (typeof name === "undefined") {
28
+ this.#addToPipe(this.#all, action);
29
+ } else {
30
+ this.#initNamedPipe(name);
31
+ this.#addToPipe(this.#named[name], action);
32
+ }
33
+ return this;
34
+ }
35
+
36
+ #addToPipe(pipe, action) {
37
+ if (!pipe.includes(action)) {
38
+ pipe.push(action);
39
+ }
40
+ }
41
+
42
+ #removeFromPipe(pipe, action) {
43
+ if (pipe.includes(action)) {
44
+ pipe.splice(pipe.indexOf(action), 1);
45
+ }
46
+ }
47
+
48
+ #initNamedPipe(name) {
49
+ if (!objHas(this.#named, name) || !Array.isArray(this.#named[name])) {
50
+ this.#named[name] = [];
51
+ }
52
+ }
53
+
54
+ remove(name, action) {
55
+ if (typeof name === "undefined") {
56
+ this.#removeFromPipe(this.#all, action);
57
+ } else {
58
+ this.#initNamedPipe(name);
59
+ this.#removeFromPipe(this.#named[name], action);
60
+ }
61
+ return this;
62
+ }
63
+
64
+ #buildPipe(name) {
65
+ const final = [...this.#all];
66
+ this.#initNamedPipe(name);
67
+ final.push(...this.#named[name]);
68
+ return final;
69
+ }
70
+
71
+ async execute(name, params) {
72
+ try {
73
+ const pipe = this.#buildPipe(name);
74
+ return await this.#execute(pipe, params);
75
+ } catch (e) {
76
+ throw new ActionExceptionPipeExecutionError({ cause: e });
77
+ }
78
+ }
79
+
80
+ async #execute(pipe, params) {
81
+ const ways = {
82
+ CONSECUTIVE: this.#executeConsecutive,
83
+ PARALLEL: this.#executeParallel,
84
+ };
85
+ return await ways[this.#type](pipe, params);
86
+ }
87
+
88
+ async #executeConsecutive(pipe, params) {
89
+ for (let action of pipe) {
90
+ await this.#actionRunner.run(action, params);
91
+ }
92
+ }
93
+
94
+ async #executeParallel(pipe, params) {
95
+ const promisesOfPipe = pipe.map((action) =>
96
+ this.#actionRunner.run(action, params)
97
+ );
98
+ await Promise.all(promisesOfPipe);
99
+ }
100
+ }
101
+
102
+ module.exports = NamedActionPipes;
@@ -1,3 +1,5 @@
1
+ const { deleteResponseSuccess, updateResponseSuccess } = require("./utils.js");
2
+ const { DBExceptionDeleteWasNotSuccessful } = require("../exceptions/db.js");
1
3
  /** @module Model/Default */
2
4
  const routine = require("./routine");
3
5
  const notQuery = require("not-filter");
@@ -158,7 +160,7 @@ function getOneRaw(id, condition = {}) {
158
160
  * @static
159
161
  * @param {string} method name of the method
160
162
  * @param {object|array} filter filtering rules object
161
- * @return {Query} mongoose query object
163
+ * @return {import('mongoose').Query} mongoose query object
162
164
  **/
163
165
  function makeQuery(method, filter) {
164
166
  let versioningMod = {
@@ -349,6 +351,34 @@ function update(filter, data, many = false) {
349
351
  }
350
352
  }
351
353
 
354
+ async function removeOne(filter) {
355
+ if (this.schema.statics.__versioning) {
356
+ const res = await this.updateOne(filter, { __closed: true });
357
+ if (!updateResponseSuccess(res, 1)) {
358
+ throw new DBExceptionDeleteWasNotSuccessful(res);
359
+ }
360
+ } else {
361
+ const res = await this.deleteOne(filter);
362
+ if (!deleteResponseSuccess(res, 1)) {
363
+ throw new DBExceptionDeleteWasNotSuccessful(res);
364
+ }
365
+ }
366
+ }
367
+
368
+ async function removeMany(filter) {
369
+ if (this.schema.statics.__versioning) {
370
+ const res = await this.updateMany(filter, { __closed: true });
371
+ if (!updateResponseSuccess(res, 0)) {
372
+ throw new DBExceptionDeleteWasNotSuccessful(res);
373
+ }
374
+ } else {
375
+ const res = await this.deleteMany(filter);
376
+ if (!deleteResponseSuccess(res, 0)) {
377
+ throw new DBExceptionDeleteWasNotSuccessful(res);
378
+ }
379
+ }
380
+ }
381
+
352
382
  module.exports.thisStatics = {
353
383
  sanitizeInput,
354
384
  getOne,
@@ -364,6 +394,8 @@ module.exports.thisStatics = {
364
394
  listAndCount,
365
395
  add,
366
396
  update,
397
+ removeOne,
398
+ removeMany,
367
399
  };
368
400
 
369
401
  /**
@@ -383,14 +415,18 @@ function getID() {
383
415
  * @return {number} ID
384
416
  */
385
417
  function close(data = undefined) {
386
- if (data && Object.keys(data)) {
387
- Object.keys(data).forEach((fieldName) => {
388
- notPath.setValueByPath(this, fieldName, data[fieldName]);
389
- this.markModified(fieldName);
390
- });
418
+ if (this?.schema?.statics?.__versioning) {
419
+ if (data && Object.keys(data)) {
420
+ Object.keys(data).forEach((fieldName) => {
421
+ notPath.setValueByPath(this, fieldName, data[fieldName]);
422
+ this.markModified(fieldName);
423
+ });
424
+ }
425
+ this.__closed = true;
426
+ return this.save();
427
+ } else {
428
+ return this.deleteOne({ _id: this._id });
391
429
  }
392
- this.__closed = true;
393
- return this.save();
394
430
  }
395
431
 
396
432
  function saveNewVersion() {
@@ -7,12 +7,16 @@ function getBaseResult() {
7
7
  }
8
8
 
9
9
  function createInsertManySuccessSignature(count) {
10
- return Object.assign(
11
- {
12
- insertedCount: count,
13
- },
14
- getBaseResult()
15
- );
10
+ if (count > 0) {
11
+ return Object.assign(
12
+ {
13
+ insertedCount: count,
14
+ },
15
+ getBaseResult()
16
+ );
17
+ } else {
18
+ return Object.assign({}, getBaseResult());
19
+ }
16
20
  }
17
21
 
18
22
  function createInsertOneSuccessSignature() {
@@ -31,12 +35,16 @@ function createUpdateManySuccessSignature(count) {
31
35
  }
32
36
 
33
37
  function createDeleteManySuccessSignature(count) {
34
- return Object.assign(
35
- {
36
- deletedCount: count,
37
- },
38
- getBaseResult()
39
- );
38
+ if (count > 0) {
39
+ return Object.assign(
40
+ {
41
+ deletedCount: count,
42
+ },
43
+ getBaseResult()
44
+ );
45
+ } else {
46
+ return Object.assign({}, getBaseResult());
47
+ }
40
48
  }
41
49
 
42
50
  function insertResponseSuccess(res, count = 1) {
@@ -68,6 +76,7 @@ function deleteManyResponseSuccess(res, count) {
68
76
  }
69
77
 
70
78
  module.exports.deleteManyResponseSuccess = deleteManyResponseSuccess;
79
+
71
80
  /**
72
81
  * checking result of modification queries to ensure that changes were made
73
82
  */
package/src/types.js CHANGED
@@ -169,4 +169,52 @@
169
169
  * @property {notFieldModel} [model]
170
170
  */
171
171
 
172
+ /**
173
+ * @typedef {string} uuid
174
+ */
175
+
176
+ /**
177
+ * @typedef {object} ListAndCountResult
178
+ * @property {Array<notAppDocument>} list list of extended mongoose documents
179
+ * @property {number} skip count of skiped from start of set
180
+ * @property {number} count total count of documents in this set
181
+ * @property {number} page number of returned page
182
+ * @property {number} pages total count of pages in this set
183
+ */
184
+
185
+ /**
186
+ * @typedef {object} notAppModelMethods
187
+ * @property {function(object):object} sanitizeInput
188
+ * @property {function(uuid, [Array<string>], [object]):Promise<notAppDocument>} getOne
189
+ * @property {function(number, [Array<string>], [object]):Promise<notAppDocument>} getOneByID
190
+ * @property {function(uuid, [object]):Promise<notAppDocument>} getOneRaw
191
+ * @property {function(string, object):Promise<notAppDocument|Array<notAppDocument>|undefined>} makeQuery
192
+ * @property {function(number, number, object, object|Array):Promise<Array<notAppDocument>>} list
193
+ * @property {function(string, Array<String>, object, Array<String>):Promise<Array<notAppDocument>>} listByField
194
+ * @property {function([object]):Promise<Array<notAppDocument>>} listAll
195
+ * @property {function(object|array):Promise<Array<notAppDocument>>} listAllAndPopulate
196
+ * @property {function(object):Promise<number>} countWithFilter
197
+ * @property {function(number, number, object, object | Array, Array<String>):Promise<Array<notAppDocument>>} listAndPopulate
198
+ * @property {function(number, number, object, object|array, object|array, object):Promise<ListAndCountResult>} listAndCount
199
+ * @property {function(object):Promise<notAppDocument>} add
200
+ * @property {function(object, object, boolean):Promise<notAppDocument|undefined>} update
201
+ * @property {function(object):Promise<undefined>} removeOne
202
+ * @property {function(object):Promise<undefined>} removeMany
203
+ */
204
+
205
+ /**
206
+ * @typedef {import('mongoose').Model & notAppModelMethods} notAppModel
207
+ **/
208
+
209
+ /**
210
+ * @typedef {object} notAppDocumentMethods
211
+ * @property {function():number} getID
212
+ * @property {function([object]):Promise<notAppDocument|undefined>} close
213
+ * @property {function():Promise<notAppDocument>} saveNewVersion
214
+ **/
215
+
216
+ /**
217
+ * @typedef {import('mongoose').Document & notAppDocumentMethods} notAppDocument
218
+ **/
219
+
172
220
  module.exports = {};
@@ -974,6 +974,11 @@ module.exports = ({
974
974
  describe("close", () => {
975
975
  it("simple run", async () => {
976
976
  const ctx = {
977
+ schema: {
978
+ statics: {
979
+ __versioning: true,
980
+ },
981
+ },
977
982
  __closed: false,
978
983
  async save() {
979
984
  return this;
@@ -351,6 +351,8 @@ module.exports = ({ mongod, mongoose }) => {
351
351
  "listAllAndPopulate",
352
352
  "listAndCount",
353
353
  "listByField",
354
+ "removeMany",
355
+ "removeOne",
354
356
  ]);
355
357
  expect(moduleProto1.mongooseSchema.methods).to.have.keys([
356
358
  "getName",
package/test/notModel.js CHANGED
@@ -41,11 +41,11 @@ describe("notModel", function () {
41
41
  mongoose,
42
42
  });
43
43
 
44
- require("./model/utils")({
44
+ /*require("./model/utils")({
45
45
  expect,
46
46
  mongod,
47
47
  mongoose,
48
- });
48
+ });*/
49
49
 
50
50
  after(async () => {
51
51
  await mongoose.disconnect();