@ozdao/prometheus-framework 0.1.34 → 0.1.35

Sign up to get free protection for your applications and to get access to all the features.
@@ -3,6 +3,7 @@ const _commonjsHelpers = require("./_commonjsHelpers-3b53548e.js");
3
3
  require("uuid");
4
4
  const require$$0 = require("mongoose");
5
5
  const index = require("./index-21dfdbd9.js");
6
+ const metadata_schema = require("./metadata.schema-4f856191.js");
6
7
  require("jsonwebtoken");
7
8
  require("mongodb");
8
9
  async function getBlockedMembers$1(Membership, userId) {
@@ -579,54 +580,18 @@ var reactions_routes = function(app, db) {
579
580
  controller.delete
580
581
  );
581
582
  };
582
- var blogpost_model = (mongoose) => {
583
- const BlogpostSchema = new mongoose.Schema({
584
- url: { type: String },
585
- name: { type: String },
586
- content: { type: Array },
587
- views: { type: Number },
588
- tags: { type: Array },
589
- status: {
583
+ const applyCommonSchema = metadata_schema.common_schema;
584
+ const applyEngagementSchema = metadata_schema.engagement_schema;
585
+ const applyOwnershipSchema = metadata_schema.ownership_schema;
586
+ const applyMetadataSchema = metadata_schema.metadata_schema;
587
+ var blogpost_model = (db) => {
588
+ const BlogpostSchema = new db.mongoose.Schema({
589
+ name: {
590
590
  type: String,
591
- enum: ["draft", "published", "removed"],
592
- default: "draft",
593
591
  required: true
594
592
  },
595
- owner: {
596
- type: {
597
- type: String,
598
- required: true
599
- },
600
- target: {
601
- type: mongoose.Schema.Types.ObjectId,
602
- ref: function(value) {
603
- if (this.owner.type === "user")
604
- return "User";
605
- if (this.owner.type === "organization")
606
- return "Organization";
607
- },
608
- required: true
609
- }
610
- },
611
- creator: {
612
- hidden: {
613
- type: Boolean,
614
- required: true
615
- },
616
- type: {
617
- type: String,
618
- required: true
619
- },
620
- target: {
621
- type: mongoose.Schema.Types.ObjectId,
622
- ref: function(value) {
623
- if (this.owner.type === "user")
624
- return "User";
625
- if (this.owner.type === "organization")
626
- return "Organization";
627
- },
628
- required: true
629
- }
593
+ content: {
594
+ type: Array
630
595
  }
631
596
  }, {
632
597
  timestamps: {
@@ -635,7 +600,11 @@ var blogpost_model = (mongoose) => {
635
600
  }, {
636
601
  strict: false
637
602
  });
638
- const Blogpost = mongoose.model("Blogpost", BlogpostSchema);
603
+ applyCommonSchema(BlogpostSchema);
604
+ applyEngagementSchema(BlogpostSchema, db);
605
+ applyOwnershipSchema(BlogpostSchema, db);
606
+ applyMetadataSchema(BlogpostSchema);
607
+ const Blogpost = db.mongoose.model("Blogpost", BlogpostSchema);
639
608
  return Blogpost;
640
609
  };
641
610
  var comment_model = (mongoose) => {
@@ -2,6 +2,7 @@ import { g as getDefaultExportFromCjs } from "./_commonjsHelpers-83b1d755.mjs";
2
2
  import "uuid";
3
3
  import require$$0 from "mongoose";
4
4
  import { s as server$1 } from "./index-fa8d5df4.mjs";
5
+ import { c as common_schema, e as engagement_schema, o as ownership_schema, m as metadata_schema } from "./metadata.schema-7f36e829.mjs";
5
6
  import "jsonwebtoken";
6
7
  import "mongodb";
7
8
  async function getBlockedMembers$1(Membership, userId) {
@@ -578,54 +579,18 @@ var reactions_routes = function(app, db) {
578
579
  controller.delete
579
580
  );
580
581
  };
581
- var blogpost_model = (mongoose) => {
582
- const BlogpostSchema = new mongoose.Schema({
583
- url: { type: String },
584
- name: { type: String },
585
- content: { type: Array },
586
- views: { type: Number },
587
- tags: { type: Array },
588
- status: {
582
+ const applyCommonSchema = common_schema;
583
+ const applyEngagementSchema = engagement_schema;
584
+ const applyOwnershipSchema = ownership_schema;
585
+ const applyMetadataSchema = metadata_schema;
586
+ var blogpost_model = (db) => {
587
+ const BlogpostSchema = new db.mongoose.Schema({
588
+ name: {
589
589
  type: String,
590
- enum: ["draft", "published", "removed"],
591
- default: "draft",
592
590
  required: true
593
591
  },
594
- owner: {
595
- type: {
596
- type: String,
597
- required: true
598
- },
599
- target: {
600
- type: mongoose.Schema.Types.ObjectId,
601
- ref: function(value) {
602
- if (this.owner.type === "user")
603
- return "User";
604
- if (this.owner.type === "organization")
605
- return "Organization";
606
- },
607
- required: true
608
- }
609
- },
610
- creator: {
611
- hidden: {
612
- type: Boolean,
613
- required: true
614
- },
615
- type: {
616
- type: String,
617
- required: true
618
- },
619
- target: {
620
- type: mongoose.Schema.Types.ObjectId,
621
- ref: function(value) {
622
- if (this.owner.type === "user")
623
- return "User";
624
- if (this.owner.type === "organization")
625
- return "Organization";
626
- },
627
- required: true
628
- }
592
+ content: {
593
+ type: Array
629
594
  }
630
595
  }, {
631
596
  timestamps: {
@@ -634,7 +599,11 @@ var blogpost_model = (mongoose) => {
634
599
  }, {
635
600
  strict: false
636
601
  });
637
- const Blogpost = mongoose.model("Blogpost", BlogpostSchema);
602
+ applyCommonSchema(BlogpostSchema);
603
+ applyEngagementSchema(BlogpostSchema, db);
604
+ applyOwnershipSchema(BlogpostSchema, db);
605
+ applyMetadataSchema(BlogpostSchema);
606
+ const Blogpost = db.mongoose.model("Blogpost", BlogpostSchema);
638
607
  return Blogpost;
639
608
  };
640
609
  var comment_model = (mongoose) => {
@@ -3,6 +3,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
3
  const _commonjsHelpers = require("./_commonjsHelpers-3b53548e.js");
4
4
  const require$$0 = require("mongoose");
5
5
  const index = require("./index-21dfdbd9.js");
6
+ const metadata_schema = require("./metadata.schema-4f856191.js");
6
7
  require("jsonwebtoken");
7
8
  require("mongodb");
8
9
  const ObjectId$1 = require$$0.Types.ObjectId;
@@ -383,8 +384,7 @@ const middlewareFactory = (db) => {
383
384
  }
384
385
  };
385
386
  const create = async (req, res) => {
386
- if (req.body._id)
387
- delete req.body._id;
387
+ delete req.body._id;
388
388
  try {
389
389
  req.body.url = createFriendlyURL(req.body.name);
390
390
  const event = await Event.create(req.body);
@@ -634,12 +634,12 @@ var tickets_routes = function(app, db, origins) {
634
634
  );
635
635
  };
636
636
  const tickets_routes$1 = /* @__PURE__ */ _commonjsHelpers.getDefaultExportFromCjs(tickets_routes);
637
- var event_model = (mongoose) => {
638
- const EventSchema = new mongoose.Schema({
639
- url: {
640
- type: String,
641
- required: true
642
- },
637
+ const applyCommonSchema = metadata_schema.common_schema;
638
+ const applyEngagementSchema = metadata_schema.engagement_schema;
639
+ const applyOwnershipSchema = metadata_schema.ownership_schema;
640
+ const applyMetadataSchema = metadata_schema.metadata_schema;
641
+ var event_model = (db) => {
642
+ const EventSchema = new db.mongoose.Schema({
643
643
  cover: {
644
644
  type: String
645
645
  },
@@ -647,12 +647,6 @@ var event_model = (mongoose) => {
647
647
  type: String,
648
648
  required: true
649
649
  },
650
- status: {
651
- type: String,
652
- enum: ["draft", "published", "removed"],
653
- default: "draft",
654
- required: true
655
- },
656
650
  description: {
657
651
  type: String,
658
652
  required: true
@@ -668,53 +662,25 @@ var event_model = (mongoose) => {
668
662
  end: {
669
663
  type: Date
670
664
  }
671
- },
672
- tags: [{
673
- type: String
674
- }],
675
- owner: {
676
- type: {
677
- type: String,
678
- required: true
679
- },
680
- target: {
681
- type: mongoose.Schema.Types.ObjectId,
682
- ref: function(value) {
683
- if (this.owner.type === "user")
684
- return "User";
685
- if (this.owner.type === "organization")
686
- return "Organization";
687
- },
688
- required: true
689
- }
690
- },
691
- creator: {
692
- hidden: {
693
- type: Boolean,
694
- required: true
695
- },
696
- type: {
697
- type: String,
698
- required: true
699
- },
700
- target: {
701
- type: mongoose.Schema.Types.ObjectId,
702
- ref: function(value) {
703
- if (this.owner.type === "user")
704
- return "User";
705
- if (this.owner.type === "organization")
706
- return "Organization";
707
- },
708
- required: true
709
- }
710
665
  }
711
666
  }, {
712
667
  timestamps: {
713
668
  currentTime: () => Date.now()
714
669
  }
715
670
  });
716
- EventSchema.index({ "url": 1, "name": 1, "date.start": 1, "date.end": -1, "tags": 1, "owner.target": 1, "creator.target": 1 });
717
- const Event = mongoose.model("Event", EventSchema);
671
+ EventSchema.index({
672
+ "name": 1,
673
+ "date.start": 1,
674
+ "date.end": -1
675
+ });
676
+ applyCommonSchema(EventSchema);
677
+ applyEngagementSchema(EventSchema, db);
678
+ applyOwnershipSchema(EventSchema, db);
679
+ applyMetadataSchema(EventSchema);
680
+ EventSchema.post("aggregate", async function(docs) {
681
+ console.log(EventSchema);
682
+ });
683
+ const Event = db.mongoose.model("Event", EventSchema);
718
684
  return Event;
719
685
  };
720
686
  const event_model$1 = /* @__PURE__ */ _commonjsHelpers.getDefaultExportFromCjs(event_model);
@@ -1,6 +1,7 @@
1
1
  import { g as getDefaultExportFromCjs } from "./_commonjsHelpers-83b1d755.mjs";
2
2
  import require$$0 from "mongoose";
3
3
  import { s as server$1 } from "./index-fa8d5df4.mjs";
4
+ import { c as common_schema, e as engagement_schema, o as ownership_schema, m as metadata_schema } from "./metadata.schema-7f36e829.mjs";
4
5
  import "jsonwebtoken";
5
6
  import "mongodb";
6
7
  const ObjectId$1 = require$$0.Types.ObjectId;
@@ -381,8 +382,7 @@ const middlewareFactory = (db) => {
381
382
  }
382
383
  };
383
384
  const create = async (req, res) => {
384
- if (req.body._id)
385
- delete req.body._id;
385
+ delete req.body._id;
386
386
  try {
387
387
  req.body.url = createFriendlyURL(req.body.name);
388
388
  const event = await Event.create(req.body);
@@ -632,12 +632,12 @@ var tickets_routes = function(app, db, origins) {
632
632
  );
633
633
  };
634
634
  const tickets_routes$1 = /* @__PURE__ */ getDefaultExportFromCjs(tickets_routes);
635
- var event_model = (mongoose) => {
636
- const EventSchema = new mongoose.Schema({
637
- url: {
638
- type: String,
639
- required: true
640
- },
635
+ const applyCommonSchema = common_schema;
636
+ const applyEngagementSchema = engagement_schema;
637
+ const applyOwnershipSchema = ownership_schema;
638
+ const applyMetadataSchema = metadata_schema;
639
+ var event_model = (db) => {
640
+ const EventSchema = new db.mongoose.Schema({
641
641
  cover: {
642
642
  type: String
643
643
  },
@@ -645,12 +645,6 @@ var event_model = (mongoose) => {
645
645
  type: String,
646
646
  required: true
647
647
  },
648
- status: {
649
- type: String,
650
- enum: ["draft", "published", "removed"],
651
- default: "draft",
652
- required: true
653
- },
654
648
  description: {
655
649
  type: String,
656
650
  required: true
@@ -666,53 +660,25 @@ var event_model = (mongoose) => {
666
660
  end: {
667
661
  type: Date
668
662
  }
669
- },
670
- tags: [{
671
- type: String
672
- }],
673
- owner: {
674
- type: {
675
- type: String,
676
- required: true
677
- },
678
- target: {
679
- type: mongoose.Schema.Types.ObjectId,
680
- ref: function(value) {
681
- if (this.owner.type === "user")
682
- return "User";
683
- if (this.owner.type === "organization")
684
- return "Organization";
685
- },
686
- required: true
687
- }
688
- },
689
- creator: {
690
- hidden: {
691
- type: Boolean,
692
- required: true
693
- },
694
- type: {
695
- type: String,
696
- required: true
697
- },
698
- target: {
699
- type: mongoose.Schema.Types.ObjectId,
700
- ref: function(value) {
701
- if (this.owner.type === "user")
702
- return "User";
703
- if (this.owner.type === "organization")
704
- return "Organization";
705
- },
706
- required: true
707
- }
708
663
  }
709
664
  }, {
710
665
  timestamps: {
711
666
  currentTime: () => Date.now()
712
667
  }
713
668
  });
714
- EventSchema.index({ "url": 1, "name": 1, "date.start": 1, "date.end": -1, "tags": 1, "owner.target": 1, "creator.target": 1 });
715
- const Event = mongoose.model("Event", EventSchema);
669
+ EventSchema.index({
670
+ "name": 1,
671
+ "date.start": 1,
672
+ "date.end": -1
673
+ });
674
+ applyCommonSchema(EventSchema);
675
+ applyEngagementSchema(EventSchema, db);
676
+ applyOwnershipSchema(EventSchema, db);
677
+ applyMetadataSchema(EventSchema);
678
+ EventSchema.post("aggregate", async function(docs) {
679
+ console.log(EventSchema);
680
+ });
681
+ const Event = db.mongoose.model("Event", EventSchema);
716
682
  return Event;
717
683
  };
718
684
  const event_model$1 = /* @__PURE__ */ getDefaultExportFromCjs(event_model);
@@ -0,0 +1,85 @@
1
+ "use strict";
2
+ var common_schema = function applyCommonSchema(schema, db) {
3
+ schema.add({
4
+ status: {
5
+ type: String,
6
+ enum: ["draft", "published", "removed"],
7
+ default: "draft",
8
+ required: true
9
+ }
10
+ });
11
+ };
12
+ var engagement_schema = function applyEngagementSchema(schema, db) {
13
+ schema.add({
14
+ views: {
15
+ type: Number,
16
+ default: 0
17
+ }
18
+ });
19
+ schema.post("aggregate", async function(docs) {
20
+ if (docs.length > 0) {
21
+ console.log("Post-aggregate hook in engagement schena triggered");
22
+ try {
23
+ await Promise.all(docs.map(async (doc) => {
24
+ console.log(doc._id);
25
+ const updatedViews = await db.event.findOneAndUpdate({ _id: doc._id }, { $inc: { views: 1 } }).exec();
26
+ }));
27
+ } catch (error) {
28
+ console.error("Error updating views:", error);
29
+ }
30
+ }
31
+ });
32
+ };
33
+ var ownership_schema = function applyOwnershipSchema(schema, db) {
34
+ schema.add({
35
+ owner: {
36
+ type: {
37
+ type: String,
38
+ required: true
39
+ },
40
+ target: {
41
+ type: db.mongoose.Schema.Types.ObjectId,
42
+ refPath: "owner.type",
43
+ required: true
44
+ }
45
+ },
46
+ creator: {
47
+ hidden: {
48
+ type: Boolean,
49
+ required: true
50
+ },
51
+ type: {
52
+ type: String,
53
+ required: true
54
+ },
55
+ target: {
56
+ type: db.mongoose.Schema.Types.ObjectId,
57
+ refPath: "creator.type",
58
+ required: true
59
+ }
60
+ }
61
+ });
62
+ schema.index({
63
+ "owner.target": 1,
64
+ "creator.target": 1
65
+ });
66
+ };
67
+ var metadata_schema = function applyMetadataSchema(schema, db) {
68
+ schema.add({
69
+ url: {
70
+ type: String,
71
+ required: true
72
+ },
73
+ tags: [{
74
+ type: String
75
+ }]
76
+ });
77
+ schema.index({
78
+ "url": 1,
79
+ "tags": 1
80
+ });
81
+ };
82
+ exports.common_schema = common_schema;
83
+ exports.engagement_schema = engagement_schema;
84
+ exports.metadata_schema = metadata_schema;
85
+ exports.ownership_schema = ownership_schema;
@@ -0,0 +1,86 @@
1
+ var common_schema = function applyCommonSchema(schema, db) {
2
+ schema.add({
3
+ status: {
4
+ type: String,
5
+ enum: ["draft", "published", "removed"],
6
+ default: "draft",
7
+ required: true
8
+ }
9
+ });
10
+ };
11
+ var engagement_schema = function applyEngagementSchema(schema, db) {
12
+ schema.add({
13
+ views: {
14
+ type: Number,
15
+ default: 0
16
+ }
17
+ });
18
+ schema.post("aggregate", async function(docs) {
19
+ if (docs.length > 0) {
20
+ console.log("Post-aggregate hook in engagement schena triggered");
21
+ try {
22
+ await Promise.all(docs.map(async (doc) => {
23
+ console.log(doc._id);
24
+ const updatedViews = await db.event.findOneAndUpdate({ _id: doc._id }, { $inc: { views: 1 } }).exec();
25
+ }));
26
+ } catch (error) {
27
+ console.error("Error updating views:", error);
28
+ }
29
+ }
30
+ });
31
+ };
32
+ var ownership_schema = function applyOwnershipSchema(schema, db) {
33
+ schema.add({
34
+ owner: {
35
+ type: {
36
+ type: String,
37
+ required: true
38
+ },
39
+ target: {
40
+ type: db.mongoose.Schema.Types.ObjectId,
41
+ refPath: "owner.type",
42
+ required: true
43
+ }
44
+ },
45
+ creator: {
46
+ hidden: {
47
+ type: Boolean,
48
+ required: true
49
+ },
50
+ type: {
51
+ type: String,
52
+ required: true
53
+ },
54
+ target: {
55
+ type: db.mongoose.Schema.Types.ObjectId,
56
+ refPath: "creator.type",
57
+ required: true
58
+ }
59
+ }
60
+ });
61
+ schema.index({
62
+ "owner.target": 1,
63
+ "creator.target": 1
64
+ });
65
+ };
66
+ var metadata_schema = function applyMetadataSchema(schema, db) {
67
+ schema.add({
68
+ url: {
69
+ type: String,
70
+ required: true
71
+ },
72
+ tags: [{
73
+ type: String
74
+ }]
75
+ });
76
+ schema.index({
77
+ "url": 1,
78
+ "tags": 1
79
+ });
80
+ };
81
+ export {
82
+ common_schema as c,
83
+ engagement_schema as e,
84
+ metadata_schema as m,
85
+ ownership_schema as o
86
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ozdao/prometheus-framework",
3
- "version": "0.1.34",
3
+ "version": "0.1.35",
4
4
  "description": "Web3 Framework focused on user experience and ease of development.",
5
5
  "author": "OZ DAO <hello@ozdao.dev>",
6
6
  "license": "GPL-3.0-or-later",
@@ -0,0 +1,290 @@
1
+ // Query Processor
2
+ const queryProcessor = require('./utils/queryProcessor');
3
+ const queryProcessorGlobals = require('@pf/src/modules/globals/controllers/utils/queryProcessor');
4
+ // Utils
5
+ const { getBlockedMembers, addConditionsForBlocked } = require('@pf/src/modules/organizations/controllers/utils/excludeBlockedMembers');
6
+
7
+ const controllerFactory = (db) => {
8
+ const Blogpost = db.blogpost;
9
+ const Organization = db.organization;
10
+ const Membership = db.membership;
11
+
12
+ const read = async (req, res) => {
13
+
14
+ let stages = [];
15
+
16
+ stages = [
17
+ ...queryProcessorGlobals.getBasicOptions(
18
+ req.query
19
+ ),
20
+ // Pagination
21
+ ...queryProcessorGlobals.getSortingOptions(
22
+ req.query
23
+ ),
24
+ ...queryProcessorGlobals.getPaginationOptions(
25
+ req.query
26
+ )
27
+ ]
28
+
29
+ let query = [];
30
+ let matchStage = {};
31
+
32
+
33
+ if (req.query.status) {
34
+ matchStage["status"] = req.query.status;
35
+ }
36
+
37
+ // EXCLUDE USERS AND ORGS BLOCKED BY USER
38
+ if (req.query.user) {
39
+ const blockedMembers = await getBlockedMembers(Membership, req.query.user);
40
+
41
+ console.log(blockedMembers);
42
+
43
+ if (blockedMembers.length > 0) {
44
+ addConditionsForBlocked(matchStage, "owner.target", blockedMembers);
45
+ addConditionsForBlocked(matchStage, "creator.target", blockedMembers);
46
+ }
47
+ }
48
+
49
+ if (req.query.tags) {
50
+ matchStage["tags"] = { $in: req.query.tags.split(',') };
51
+ }
52
+
53
+ if (req.query.period) {
54
+ const date = new Date();
55
+
56
+ switch (req.query.period) {
57
+ case 'today':
58
+ date.setDate(date.getDate() - 1);
59
+ break;
60
+ case 'week':
61
+ date.setDate(date.getDate() - 7);
62
+ break;
63
+ case 'month':
64
+ date.setMonth(date.getMonth() - 1);
65
+ break;
66
+ case 'year':
67
+ date.setFullYear(date.getFullYear() - 1);
68
+ break;
69
+ }
70
+ matchStage["createdAt"] = { $gte: date };
71
+ }
72
+
73
+ // FILTER BY CATEGORY
74
+ if (req.query.category) {
75
+ switch (req.query.category) {
76
+ case 'featured':
77
+ matchStage["tags"] = { $in: ["Featured"] };
78
+ break;
79
+ case 'popular':
80
+ query.push({ $sort: { views: -1, likes: -1 } });
81
+ break;
82
+ case 'new':
83
+ query.push({ $sort: { createdAt: -1 } });
84
+ break;
85
+ case 'following':
86
+ if (req.query.user) {
87
+ const memberships = await Membership.find({ user: req.query.user });
88
+ const followedOrganizations = memberships.filter(membership => membership.type === 'organization').map(membership => membership.target);
89
+ const followedAuthors = memberships.filter(membership => membership.type === 'user').map(membership => membership.target);
90
+
91
+ matchStage["$or"] = [
92
+ { "owner.target": { $in: followedOrganizations } },
93
+ { "owner.target": { $in: followedAuthors } }
94
+ ];
95
+ }
96
+ break;
97
+ }
98
+ }
99
+
100
+
101
+ query.push({ $match: matchStage });
102
+
103
+
104
+ query.push({
105
+ $lookup: {
106
+ from: "comments",
107
+ localField: "_id",
108
+ foreignField: "target",
109
+ as: "comments"
110
+ }
111
+ });
112
+
113
+ query.push({
114
+ $lookup: {
115
+ from: "reactions",
116
+ localField: "_id",
117
+ foreignField: "target",
118
+ as: "reactions"
119
+ }
120
+ });
121
+
122
+ query.push({
123
+ $addFields: {
124
+ numberOfComments: { $size: "$comments" },
125
+ numberOfReactions: { $size: "$reactions" },
126
+ isReacted: {
127
+ $in: [
128
+ new db.mongoose.Types.ObjectId(req.query.user),
129
+ "$reactions.user"
130
+ ]
131
+ },
132
+ reactionId: {
133
+ $let: {
134
+ vars: {
135
+ reactionIndex: {
136
+ $indexOfArray: [
137
+ "$reactions.user",
138
+ new db.mongoose.Types.ObjectId(req.query.user)
139
+ ]
140
+ }
141
+ },
142
+ in: {
143
+ $cond: [
144
+ { $gte: ["$$reactionIndex", 0] },
145
+ { $arrayElemAt: ["$reactions._id", "$$reactionIndex"] },
146
+ null
147
+ ]
148
+ }
149
+ }
150
+ }
151
+ }
152
+ });
153
+
154
+ query.push({
155
+ $lookup: {
156
+ from: "users",
157
+ localField: "creator.target",
158
+ foreignField: "_id",
159
+ as: "creatorUser"
160
+ }
161
+ },
162
+ {
163
+ $lookup: {
164
+ from: "organizations",
165
+ localField: "creator.target",
166
+ foreignField: "_id",
167
+ as: "creatorOrganization"
168
+ }
169
+ },
170
+ // Для owner
171
+ {
172
+ $lookup: {
173
+ from: "users",
174
+ localField: "owner.target",
175
+ foreignField: "_id",
176
+ as: "ownerUser"
177
+ }
178
+ },
179
+ {
180
+ $lookup: {
181
+ from: "organizations",
182
+ localField: "owner.target",
183
+ foreignField: "_id",
184
+ as: "ownerOrganization"
185
+ }
186
+ },
187
+ {
188
+ $addFields: {
189
+ "creator.target": {
190
+ $cond: [
191
+ { $eq: ["$creator.type", "user"] },
192
+ { $arrayElemAt: ["$creatorUser", 0] },
193
+ { $arrayElemAt: ["$creatorOrganization", 0] }
194
+ ]
195
+ },
196
+ "owner.target": {
197
+ $cond: [
198
+ { $eq: ["$owner.type", "user"] },
199
+ { $arrayElemAt: ["$ownerUser", 0] },
200
+ { $arrayElemAt: ["$ownerOrganization", 0] }
201
+ ]
202
+ }
203
+ }
204
+ })
205
+
206
+ query.push({
207
+ $project: {
208
+ comments: 0,
209
+ reactions: 0
210
+ }
211
+ });
212
+
213
+ try {
214
+ const posts = await Blogpost.aggregate(query).exec();
215
+
216
+ if (posts.length === 0) {
217
+ return res.status(200).send([]);
218
+ // return res.status(404).send({ message: "Posts not found." });
219
+ }
220
+
221
+ console.log(posts)
222
+
223
+ res.status(200).send(posts);
224
+ } catch (err) {
225
+ console.log(err);
226
+ res.status(500).send({ err });
227
+ }
228
+ };
229
+
230
+
231
+ const create = (req, res) => {
232
+ let user = JSON.parse(req.cookies.user);
233
+
234
+ const newBlogpost = {
235
+ url: req.body.name.toLowerCase().replace(/ /g, '-').replace(/[^\w-]+/g, ''),
236
+ name: req.body.name,
237
+ status: req.body.status,
238
+ tags: req.body.tags ? req.body.tags : ['All'],
239
+ owner: req.body.owner,
240
+ creator: req.body.creator,
241
+ content: req.body.content,
242
+ views: 1
243
+ };
244
+
245
+ Blogpost.create(newBlogpost)
246
+ .then((post) => {
247
+ res.status(200).send(post);
248
+ })
249
+ .catch((err) => {
250
+ res.status(500).send({ message: err.message || "Some error occurred while creating the blogpost." });
251
+ });
252
+ };
253
+
254
+ const update = (req, res) => {
255
+ Blogpost.findOneAndUpdate({ _id: req.body._id }, { $set: req.body }, { new: true })
256
+ .exec()
257
+ .then((post) => {
258
+ if (!post) {
259
+ return res.status(404).send({ message: "Something wrong when updating the blogpost." });
260
+ }
261
+ res.status(200).send(post);
262
+ })
263
+ .catch((err) => {
264
+ res.status(500).send({ message: err.message || "Some error occurred while updating the blogpost." });
265
+ });
266
+ };
267
+
268
+ const del = (req, res) => {
269
+ Blogpost.findOneAndDelete({ _id: req.params._id })
270
+ .exec()
271
+ .then((post) => {
272
+ if (!post) {
273
+ return res.status(404).send({ message: "The blogpost is not deleted." });
274
+ }
275
+ res.status(200).send(post);
276
+ })
277
+ .catch((err) => {
278
+ res.status(500).send({ message: err.message || "Some error occurred while deleting the blogpost." });
279
+ });
280
+ };
281
+
282
+ return {
283
+ read,
284
+ create,
285
+ update,
286
+ delete: del
287
+ };
288
+ };
289
+
290
+ module.exports = controllerFactory;
@@ -1,48 +1,17 @@
1
- module.exports = (mongoose) => {
2
- const BlogpostSchema = new mongoose.Schema({
3
- url: { type: String },
4
- name: { type: String },
5
- content: { type: Array },
6
- views: { type: Number },
7
- tags: { type: Array },
8
- status: {
9
- type: String,
10
- enum: ['draft','published','removed'],
11
- default: 'draft',
12
- required: true,
1
+ const applyCommonSchema = require('@pf/src/modules/globals/models/common.schema.js');
2
+ const applyEngagementSchema = require('@pf/src/modules/globals/models/engagement.schema.js');
3
+ const applyOwnershipSchema = require('@pf/src/modules/globals/models/ownership.schema.js');
4
+ const applyMetadataSchema = require('@pf/src/modules/globals/models/metadata.schema.js');
5
+
6
+ module.exports = (db) => {
7
+ const BlogpostSchema = new db.mongoose.Schema({
8
+ name: {
9
+ type: String,
10
+ required: true
13
11
  },
14
- owner: {
15
- type: {
16
- type: String,
17
- required: true
18
- },
19
- target: {
20
- type: mongoose.Schema.Types.ObjectId,
21
- ref: function (value) {
22
- if (this.owner.type === 'user') return 'User';
23
- if (this.owner.type === 'organization') return 'Organization';
24
- },
25
- required: true,
26
- },
12
+ content: {
13
+ type: Array
27
14
  },
28
- creator: {
29
- hidden: {
30
- type: Boolean,
31
- required: true
32
- },
33
- type: {
34
- type: String,
35
- required: true
36
- },
37
- target: {
38
- type: mongoose.Schema.Types.ObjectId,
39
- ref: function (value) {
40
- if (this.owner.type === 'user') return 'User';
41
- if (this.owner.type === 'organization') return 'Organization';
42
- },
43
- required: true,
44
- },
45
- }
46
15
  }, {
47
16
  timestamps: {
48
17
  currentTime: () => Date.now()
@@ -51,7 +20,12 @@ module.exports = (mongoose) => {
51
20
  strict: false
52
21
  });
53
22
 
54
- const Blogpost = mongoose.model("Blogpost", BlogpostSchema);
23
+ applyCommonSchema(BlogpostSchema,db);
24
+ applyEngagementSchema(BlogpostSchema,db);
25
+ applyOwnershipSchema(BlogpostSchema,db);
26
+ applyMetadataSchema(BlogpostSchema,db);
27
+
28
+ const Blogpost = db.mongoose.model("Blogpost", BlogpostSchema);
55
29
 
56
30
  return Blogpost;
57
31
  };
@@ -61,6 +61,7 @@ const middlewareFactory = (db) => {
61
61
  try {
62
62
  const events = await Event.aggregate(stages).exec();
63
63
  res.status(200).send(events);
64
+
64
65
  } catch (err) {
65
66
  console.log(err);
66
67
  return res.status(500).send({ message: err });
@@ -69,7 +70,7 @@ const middlewareFactory = (db) => {
69
70
 
70
71
 
71
72
  const create = async (req, res) => {
72
- if (req.body._id) delete req.body._id;
73
+ delete req.body._id;
73
74
 
74
75
  try {
75
76
  req.body.url = createFriendlyURL(req.body.name);
@@ -23,10 +23,12 @@ const middlewareFactory = (db) => {
23
23
  // Обновление события
24
24
  const updatingEventId = req.body._id; // Изменено с updatingBlogpostId на updatingEventId
25
25
  const existingEvent = await Event.findById(updatingEventId); // Изменено с Blogpost на Event и с existingBlogpost на existingEvent
26
+
26
27
  if (!existingEvent) { // Изменено с existingBlogpost на existingEvent
27
28
  res.status(404).send({ errorCode: 'EVENT_NOT_FOUND', accessToken: null }); // Изменено с BLOGPOST_NOT_FOUND на EVENT_NOT_FOUND
28
29
  return;
29
30
  }
31
+
30
32
  if (existingEvent.url !== url) { // Изменено с existingBlogpost на existingEvent
31
33
  const event = await Event.findOne({ url }); // Изменено с Blogpost на Event и с blogpost на event
32
34
  if (event) { // Изменено с blogpost на event
@@ -1,9 +1,11 @@
1
- module.exports = (mongoose) => {
2
- const EventSchema = new mongoose.Schema({
3
- url: {
4
- type: String,
5
- required: true
6
- },
1
+ const applyCommonSchema = require('@pf/src/modules/globals/models/common.schema.js');
2
+ const applyEngagementSchema = require('@pf/src/modules/globals/models/engagement.schema.js');
3
+ const applyOwnershipSchema = require('@pf/src/modules/globals/models/ownership.schema.js');
4
+ const applyMetadataSchema = require('@pf/src/modules/globals/models/metadata.schema.js');
5
+
6
+ module.exports = (db) => {
7
+
8
+ const EventSchema = new db.mongoose.Schema({
7
9
  cover: {
8
10
  type: String,
9
11
  },
@@ -11,12 +13,6 @@ module.exports = (mongoose) => {
11
13
  type: String,
12
14
  required: true
13
15
  },
14
- status: {
15
- type: String,
16
- enum: ['draft','published','removed'],
17
- default: 'draft',
18
- required: true,
19
- },
20
16
  description: {
21
17
  type: String,
22
18
  required: true
@@ -32,41 +28,6 @@ module.exports = (mongoose) => {
32
28
  end: {
33
29
  type: Date,
34
30
  }
35
- },
36
- tags: [{
37
- type: String
38
- }],
39
- owner: {
40
- type: {
41
- type: String,
42
- required: true
43
- },
44
- target: {
45
- type: mongoose.Schema.Types.ObjectId,
46
- ref: function (value) {
47
- if (this.owner.type === 'user') return 'User';
48
- if (this.owner.type === 'organization') return 'Organization';
49
- },
50
- required: true,
51
- },
52
- },
53
- creator: {
54
- hidden: {
55
- type: Boolean,
56
- required: true
57
- },
58
- type: {
59
- type: String,
60
- required: true
61
- },
62
- target: {
63
- type: mongoose.Schema.Types.ObjectId,
64
- ref: function (value) {
65
- if (this.owner.type === 'user') return 'User';
66
- if (this.owner.type === 'organization') return 'Organization';
67
- },
68
- required: true,
69
- },
70
31
  }
71
32
  }, {
72
33
  timestamps: {
@@ -74,9 +35,23 @@ module.exports = (mongoose) => {
74
35
  }
75
36
  });
76
37
 
77
- EventSchema.index({ 'url': 1, 'name': 1, 'date.start': 1, 'date.end': -1, 'tags': 1, 'owner.target': 1, 'creator.target': 1 });
38
+ EventSchema.index({
39
+ 'name': 1,
40
+ 'date.start': 1,
41
+ 'date.end': -1,
42
+ });
78
43
 
79
- const Event = mongoose.model("Event", EventSchema);
44
+ applyCommonSchema(EventSchema,db);
45
+ applyEngagementSchema(EventSchema,db);
46
+ applyOwnershipSchema(EventSchema,db);
47
+ applyMetadataSchema(EventSchema,db);
48
+
49
+ EventSchema.post('aggregate', async function(docs) {
50
+ console.log(EventSchema)
51
+ });
52
+
53
+ const Event = db.mongoose.model("Event", EventSchema);
80
54
 
81
55
  return Event;
82
- };
56
+ };
57
+
@@ -1,14 +1,10 @@
1
- module.exports = (mongoose) => {
2
- const CommonSchema = new mongoose.Schema({
1
+ module.exports = function applyCommonSchema(schema,db) {
2
+ schema.add({
3
3
  status: {
4
4
  type: String,
5
5
  enum: ['draft','published','removed'],
6
6
  default: 'draft',
7
7
  required: true,
8
8
  },
9
- });
10
-
11
- // CommonSchema.index({ user: 1, type: 1, target: 1 });
12
-
13
- return CommonSchema;
9
+ })
14
10
  }
@@ -1,10 +1,32 @@
1
- module.exports = (db) => {
2
- const EngagementSchema = new db.mongoose.Schema({
1
+ module.exports = function applyEngagementSchema(schema,db) {
2
+ // Добавляем поля
3
+ schema.add({
3
4
  views: {
4
5
  type: Number,
5
- default: 0
6
- },
6
+ default: 0
7
+ }
7
8
  });
8
9
 
9
- return EngagementSchema;
10
- }
10
+ // Если есть middleware для этой схемы, добавляем его здесь
11
+ schema.post('aggregate', async function(docs) {
12
+
13
+ // Проверяем, возвращены ли какие-либо документы
14
+ if (docs.length > 0) {
15
+ console.log('Post-aggregate hook in engagement schena triggered');
16
+ try {
17
+ // Так как мы не можем использовать `this` для обновления внутри агрегации,
18
+ // мы должны выполнить обновление вручную для каждого соответствующего документа.
19
+ await Promise.all(docs.map(async (doc) => {
20
+ // Предполагается, что у каждого документа есть уникальный идентификатор '_id'
21
+ console.log(doc._id)
22
+ const updatedViews = await db.event.findOneAndUpdate({ _id: doc._id }, { $inc: { views: 1 } }).exec();
23
+ // console.log(updatedViews)
24
+ }));
25
+ } catch (error) {
26
+ console.error("Error updating views:", error);
27
+ }
28
+ }
29
+ });
30
+
31
+ // Возвращать схему не нужно, так как мы модифицируем её напрямую
32
+ };
@@ -1,5 +1,5 @@
1
- module.exports = (mongoose) => {
2
- const MetadataSchema = new mongoose.Schema({
1
+ module.exports = function applyMetadataSchema(schema,db) {
2
+ schema.add({
3
3
  url: {
4
4
  type: String,
5
5
  required: true
@@ -7,9 +7,10 @@ module.exports = (mongoose) => {
7
7
  tags: [{
8
8
  type: String
9
9
  }],
10
- });
11
-
12
- // MetadataSchema.index({ user: 1, type: 1, target: 1 });
10
+ })
13
11
 
14
- return MetadataSchema;
12
+ schema.index({
13
+ 'url': 1,
14
+ 'tags': 1,
15
+ });
15
16
  }
@@ -1,12 +1,12 @@
1
- module.exports = (mongoose) => {
2
- const OwnershipSchema = new mongoose.Schema({
1
+ module.exports = function applyOwnershipSchema(schema,db) {
2
+ schema.add({
3
3
  owner: {
4
4
  type: {
5
5
  type: String,
6
6
  required: true
7
7
  },
8
8
  target: {
9
- type: mongoose.Schema.Types.ObjectId,
9
+ type: db.mongoose.Schema.Types.ObjectId,
10
10
  refPath: 'owner.type',
11
11
  required: true,
12
12
  },
@@ -21,14 +21,15 @@ module.exports = (mongoose) => {
21
21
  required: true
22
22
  },
23
23
  target: {
24
- type: mongoose.Schema.Types.ObjectId,
24
+ type: db.mongoose.Schema.Types.ObjectId,
25
25
  refPath: 'creator.type',
26
26
  required: true,
27
- },
27
+ }
28
28
  }
29
29
  });
30
30
 
31
- // OwnershipSchema.index({ user: 1, type: 1, target: 1 });
32
-
33
- return OwnershipSchema;
31
+ schema.index({
32
+ 'owner.target': 1,
33
+ 'creator.target': 1
34
+ });
34
35
  }
@@ -1,76 +0,0 @@
1
- const CommonSchema = require('@pf/src/modules/globals/models/common.schema.js')
2
- const EngagementSchema = require('@pf/src/modules/globals/models/engagement.schema.js')
3
- const OwnershipSchema = require('@pf/src/modules/globals/models/ownership.schema.js')
4
- const MetadataSchema = require('@pf/src/modules/globals/models/metadata.schema.js')
5
-
6
- module.exports = (db) => {
7
-
8
- const EventSchema = new db.mongoose.Schema({
9
- ...CommonSchema,
10
- ...EngagementSchema,
11
- ...OwnershipSchema,
12
- ...MetadataSchema,
13
- // views: {
14
- // type: Number,
15
- // default: 0
16
- // },
17
- cover: {
18
- type: String,
19
- },
20
- name: {
21
- type: String,
22
- required: true
23
- },
24
- description: {
25
- type: String,
26
- required: true
27
- },
28
-
29
- content: {
30
- type: Array
31
- },
32
- date: {
33
- start: {
34
- type: Date,
35
- required: true
36
- },
37
- end: {
38
- type: Date,
39
- }
40
- },
41
- }, {
42
- timestamps: {
43
- currentTime: () => Date.now()
44
- }
45
- });
46
-
47
- EventSchema.index({ 'url': 1, 'name': 1, 'date.start': 1, 'date.end': -1, 'tags': 1, 'owner.target': 1, 'creator.target': 1 });
48
-
49
- EventSchema.post('aggregate', async function(docs) {
50
-
51
- console.log(EventSchema)
52
-
53
- // Проверяем, возвращены ли какие-либо документы
54
- if (docs.length > 0) {
55
- console.log('Post-aggregate hook triggered');
56
- // console.log(docs)
57
- try {
58
- // Так как мы не можем использовать `this` для обновления внутри агрегации,
59
- // мы должны выполнить обновление вручную для каждого соответствующего документа.
60
- await Promise.all(docs.map(async (doc) => {
61
- // Предполагается, что у каждого документа есть уникальный идентификатор '_id'
62
- console.log(doc._id)
63
- const updatedViews = await db.event.findOneAndUpdate({ _id: doc._id }, { $inc: { views: 1 } }).exec();
64
- // console.log(updatedViews)
65
- }));
66
- } catch (error) {
67
- console.error("Error updating views:", error);
68
- }
69
- }
70
- });
71
-
72
- const Event = db.mongoose.model("Event", EventSchema);
73
-
74
- return Event;
75
- };
76
-