news.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. import async from "async";
  2. import { isAdminRequired } from "./hooks";
  3. import moduleManager from "../../index";
  4. const DBModule = moduleManager.modules.db;
  5. const UtilsModule = moduleManager.modules.utils;
  6. const WSModule = moduleManager.modules.ws;
  7. const CacheModule = moduleManager.modules.cache;
  8. CacheModule.runJob("SUB", {
  9. channel: "news.create",
  10. cb: news => {
  11. WSModule.runJob("EMIT_TO_ROOM", {
  12. room: "admin.news",
  13. args: ["event:admin.news.created", { data: { news } }]
  14. });
  15. if (news.status === "published")
  16. WSModule.runJob("EMIT_TO_ROOM", {
  17. room: "news",
  18. args: ["event:news.created", { data: { news } }]
  19. });
  20. }
  21. });
  22. CacheModule.runJob("SUB", {
  23. channel: "news.remove",
  24. cb: newsId => {
  25. WSModule.runJob("EMIT_TO_ROOM", {
  26. room: "admin.news",
  27. args: ["event:admin.news.deleted", { data: { newsId } }]
  28. });
  29. WSModule.runJob("EMIT_TO_ROOM", {
  30. room: "news",
  31. args: ["event:news.deleted", { data: { newsId } }]
  32. });
  33. }
  34. });
  35. CacheModule.runJob("SUB", {
  36. channel: "news.update",
  37. cb: news => {
  38. WSModule.runJob("EMIT_TO_ROOM", {
  39. room: "admin.news",
  40. args: ["event:admin.news.updated", { data: { news } }]
  41. });
  42. WSModule.runJob("EMIT_TO_ROOM", {
  43. room: "news",
  44. args: ["event:news.updated", { data: { news } }]
  45. });
  46. }
  47. });
  48. export default {
  49. /**
  50. * Gets news items, used in the admin news page by the AdvancedTable component
  51. *
  52. * @param {object} session - the session object automatically added by the websocket
  53. * @param page - the page
  54. * @param pageSize - the size per page
  55. * @param properties - the properties to return for each news item
  56. * @param sort - the sort object
  57. * @param queries - the queries array
  58. * @param operator - the operator for queries
  59. * @param cb
  60. */
  61. getData: isAdminRequired(async function getSet(session, page, pageSize, properties, sort, queries, operator, cb) {
  62. const newsModel = await DBModule.runJob("GET_MODEL", { modelName: "news" }, this);
  63. async.waterfall(
  64. [
  65. // Creates pipeline array
  66. next => next(null, []),
  67. // If a filter exists for createdBy, add createdByUsername property to all documents
  68. (pipeline, next) => {
  69. // Check if a filter with the createdBy property exists
  70. const createdByFilterExists =
  71. queries.map(query => query.filter.property).indexOf("createdBy") !== -1;
  72. // If no such filter exists, skip this function
  73. if (!createdByFilterExists) return next(null, pipeline);
  74. // Adds createdByOID field, which is an ObjectId version of createdBy
  75. pipeline.push({
  76. $addFields: {
  77. createdByOID: {
  78. $convert: {
  79. input: "$createdBy",
  80. to: "objectId",
  81. onError: "unknown",
  82. onNull: "unknown"
  83. }
  84. }
  85. }
  86. });
  87. // Looks up user(s) with the same _id as the createdByOID and puts the result in the createdByUser field
  88. pipeline.push({
  89. $lookup: {
  90. from: "users",
  91. localField: "createdByOID",
  92. foreignField: "_id",
  93. as: "createdByUser"
  94. }
  95. });
  96. // Unwinds the createdByUser array field into an object
  97. pipeline.push({
  98. $unwind: {
  99. path: "$createdByUser",
  100. preserveNullAndEmptyArrays: true
  101. }
  102. });
  103. // Adds createdByUsername field from the createdByUser username, or unknown if it doesn't exist
  104. pipeline.push({
  105. $addFields: {
  106. createdByUsername: {
  107. $ifNull: ["$createdByUser.username", "unknown"]
  108. }
  109. }
  110. });
  111. // Removes the createdByOID and createdByUser property, just in case it doesn't get removed at a later stage
  112. pipeline.push({
  113. $project: {
  114. createdByOID: 0,
  115. createdByUser: 0
  116. }
  117. });
  118. return next(null, pipeline);
  119. },
  120. // Adds the match stage to aggregation pipeline, which is responsible for filtering
  121. (pipeline, next) => {
  122. let queryError;
  123. const newQueries = queries.flatMap(query => {
  124. const { data, filter, filterType } = query;
  125. const newQuery = {};
  126. if (filterType === "regex") {
  127. newQuery[filter.property] = new RegExp(`${data.slice(1, data.length - 1)}`, "i");
  128. } else if (filterType === "contains") {
  129. newQuery[filter.property] = new RegExp(
  130. `${data.replaceAll(/[.*+?^${}()|[\]\\]/g, "\\$&")}`,
  131. "i"
  132. );
  133. } else if (filterType === "exact") {
  134. newQuery[filter.property] = data.toString();
  135. } else if (filterType === "datetimeBefore") {
  136. newQuery[filter.property] = { $lte: new Date(data) };
  137. } else if (filterType === "datetimeAfter") {
  138. newQuery[filter.property] = { $gte: new Date(data) };
  139. } else if (filterType === "numberLesserEqual") {
  140. newQuery[filter.property] = { $lte: data };
  141. } else if (filterType === "numberLesser") {
  142. newQuery[filter.property] = { $lt: data };
  143. } else if (filterType === "numberGreater") {
  144. newQuery[filter.property] = { $gt: data };
  145. } else if (filterType === "numberGreaterEqual") {
  146. newQuery[filter.property] = { $gte: data };
  147. } else if (filterType === "numberEquals" || filterType === "boolean") {
  148. newQuery[filter.property] = { $eq: data };
  149. }
  150. if (filter.property === "createdBy")
  151. return { $or: [newQuery, { createdByUsername: newQuery.createdBy }] };
  152. return newQuery;
  153. });
  154. if (queryError) next(queryError);
  155. const queryObject = {};
  156. if (newQueries.length > 0) {
  157. if (operator === "and") queryObject.$and = newQueries;
  158. else if (operator === "or") queryObject.$or = newQueries;
  159. else if (operator === "nor") queryObject.$nor = newQueries;
  160. }
  161. pipeline.push({ $match: queryObject });
  162. next(null, pipeline);
  163. },
  164. // Adds sort stage to aggregation pipeline if there is at least one column being sorted, responsible for sorting data
  165. (pipeline, next) => {
  166. const newSort = Object.fromEntries(
  167. Object.entries(sort).map(([property, direction]) => [
  168. property,
  169. direction === "ascending" ? 1 : -1
  170. ])
  171. );
  172. if (Object.keys(newSort).length > 0) pipeline.push({ $sort: newSort });
  173. next(null, pipeline);
  174. },
  175. // Adds first project stage to aggregation pipeline, responsible for including only the requested properties
  176. (pipeline, next) => {
  177. pipeline.push({ $project: Object.fromEntries(properties.map(property => [property, 1])) });
  178. next(null, pipeline);
  179. },
  180. // Adds the facet stage to aggregation pipeline, responsible for returning a total document count, skipping and limitting the documents that will be returned
  181. (pipeline, next) => {
  182. pipeline.push({
  183. $facet: {
  184. count: [{ $count: "count" }],
  185. documents: [{ $skip: pageSize * (page - 1) }, { $limit: pageSize }]
  186. }
  187. });
  188. // console.dir(pipeline, { depth: 6 });
  189. next(null, pipeline);
  190. },
  191. // Executes the aggregation pipeline
  192. (pipeline, next) => {
  193. newsModel.aggregate(pipeline).exec((err, result) => {
  194. // console.dir(err);
  195. // console.dir(result, { depth: 6 });
  196. if (err) return next(err);
  197. if (result[0].count.length === 0) return next(null, 0, []);
  198. const { count } = result[0].count[0];
  199. const { documents } = result[0];
  200. // console.log(111, err, result, count, documents[0]);
  201. return next(null, count, documents);
  202. });
  203. }
  204. ],
  205. async (err, count, news) => {
  206. if (err && err !== true) {
  207. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  208. this.log("ERROR", "NEWS_GET_DATA", `Failed to get data from news. "${err}"`);
  209. return cb({ status: "error", message: err });
  210. }
  211. this.log("SUCCESS", "NEWS_GET_DATA", `Got data from news successfully.`);
  212. return cb({
  213. status: "success",
  214. message: "Successfully got data from news.",
  215. data: { data: news, count }
  216. });
  217. }
  218. );
  219. }),
  220. /**
  221. * Gets all news items that are published
  222. *
  223. * @param {object} session - the session object automatically added by the websocket
  224. * @param {Function} cb - gets called with the result
  225. */
  226. async getPublished(session, cb) {
  227. const newsModel = await DBModule.runJob("GET_MODEL", { modelName: "news" }, this);
  228. async.waterfall(
  229. [
  230. next => {
  231. newsModel.find({ status: "published" }).sort({ createdAt: "desc" }).exec(next);
  232. }
  233. ],
  234. async (err, news) => {
  235. if (err) {
  236. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  237. this.log("ERROR", "NEWS_INDEX", `Indexing news failed. "${err}"`);
  238. return cb({ status: "error", message: err });
  239. }
  240. this.log("SUCCESS", "NEWS_INDEX", `Indexing news successful.`, false);
  241. return cb({ status: "success", data: { news } });
  242. }
  243. );
  244. },
  245. /**
  246. * Gets a news item by id
  247. *
  248. * @param {object} session - the session object automatically added by the websocket
  249. * @param {string} newsId - the news item id
  250. * @param {Function} cb - gets called with the result
  251. */
  252. async getNewsFromId(session, newsId, cb) {
  253. const newsModel = await DBModule.runJob("GET_MODEL", { modelName: "news" }, this);
  254. async.waterfall(
  255. [
  256. next => {
  257. newsModel.findById(newsId, next);
  258. }
  259. ],
  260. async (err, news) => {
  261. if (err) {
  262. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  263. this.log("ERROR", "GET_NEWS_FROM_ID", `Getting news item ${newsId} failed. "${err}"`);
  264. return cb({ status: "error", message: err });
  265. }
  266. this.log("SUCCESS", "GET_NEWS_FROM_ID", `Got news item ${newsId} successfully.`, false);
  267. return cb({ status: "success", data: { news } });
  268. }
  269. );
  270. },
  271. /**
  272. * Creates a news item
  273. *
  274. * @param {object} session - the session object automatically added by the websocket
  275. * @param {object} data - the object of the news data
  276. * @param {Function} cb - gets called with the result
  277. */
  278. create: isAdminRequired(async function create(session, data, cb) {
  279. const newsModel = await DBModule.runJob("GET_MODEL", { modelName: "news" }, this);
  280. async.waterfall(
  281. [
  282. next => {
  283. data.createdBy = session.userId;
  284. data.createdAt = Date.now();
  285. newsModel.create(data, next);
  286. }
  287. ],
  288. async (err, news) => {
  289. if (err) {
  290. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  291. this.log("ERROR", "NEWS_CREATE", `Creating news failed. "${err}"`);
  292. return cb({ status: "error", message: err });
  293. }
  294. CacheModule.runJob("PUB", { channel: "news.create", value: news });
  295. this.log("SUCCESS", "NEWS_CREATE", `Creating news successful.`);
  296. return cb({
  297. status: "success",
  298. message: "Successfully created News"
  299. });
  300. }
  301. );
  302. }),
  303. /**
  304. * Gets the latest news item
  305. *
  306. * @param {object} session - the session object automatically added by the websocket
  307. * @param {Function} cb - gets called with the result
  308. */
  309. async newest(session, cb) {
  310. const newsModel = await DBModule.runJob("GET_MODEL", { modelName: "news" }, this);
  311. async.waterfall([next => newsModel.findOne({}).sort({ createdAt: "desc" }).exec(next)], async (err, news) => {
  312. if (err) {
  313. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  314. this.log("ERROR", "NEWS_NEWEST", `Getting the latest news failed. "${err}"`);
  315. return cb({ status: "error", message: err });
  316. }
  317. this.log("SUCCESS", "NEWS_NEWEST", `Successfully got the latest news.`, false);
  318. return cb({ status: "success", data: { news } });
  319. });
  320. },
  321. /**
  322. * Removes a news item
  323. *
  324. * @param {object} session - the session object automatically added by the websocket
  325. * @param {object} newsId - the id of the news item we want to remove
  326. * @param {Function} cb - gets called with the result
  327. */
  328. remove: isAdminRequired(async function remove(session, newsId, cb) {
  329. const newsModel = await DBModule.runJob("GET_MODEL", { modelName: "news" }, this);
  330. async.waterfall(
  331. [
  332. next => {
  333. if (!newsId) return next("Please provide a news item id to update.");
  334. return next();
  335. },
  336. next => {
  337. newsModel.deleteOne({ _id: newsId }, err => next(err));
  338. }
  339. ],
  340. async err => {
  341. if (err) {
  342. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  343. this.log(
  344. "ERROR",
  345. "NEWS_REMOVE",
  346. `Removing news "${newsId}" failed for user "${session.userId}". "${err}"`
  347. );
  348. return cb({ status: "error", message: err });
  349. }
  350. CacheModule.runJob("PUB", { channel: "news.remove", value: newsId });
  351. this.log("SUCCESS", "NEWS_REMOVE", `Removing news "${newsId}" successful by user "${session.userId}".`);
  352. return cb({
  353. status: "success",
  354. message: "Successfully removed News"
  355. });
  356. }
  357. );
  358. }),
  359. /**
  360. * Updates a news item
  361. *
  362. * @param {object} session - the session object automatically added by the websocket
  363. * @param {string} newsId - the id of the news item
  364. * @param {object} item - the news item object
  365. * @param {string} item.status - the status of the news e.g. published
  366. * @param {string} item.title - taken from a level-1 heading at the top of the markdown
  367. * @param {string} item.markdown - the markdown that forms the content of the news
  368. * @param {Function} cb - gets called with the result
  369. */
  370. update: isAdminRequired(async function update(session, newsId, item, cb) {
  371. const newsModel = await DBModule.runJob("GET_MODEL", { modelName: "news" }, this);
  372. async.waterfall(
  373. [
  374. next => {
  375. if (!newsId) return next("Please provide a news item id to update.");
  376. return next();
  377. },
  378. next => {
  379. newsModel.updateOne({ _id: newsId }, item, { upsert: true }, err => next(err));
  380. }
  381. ],
  382. async err => {
  383. if (err) {
  384. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  385. this.log(
  386. "ERROR",
  387. "NEWS_UPDATE",
  388. `Updating news item "${newsId}" failed for user "${session.userId}". "${err}"`
  389. );
  390. return cb({ status: "error", message: err });
  391. }
  392. CacheModule.runJob("PUB", { channel: "news.update", value: { ...item, _id: newsId } });
  393. this.log(
  394. "SUCCESS",
  395. "NEWS_UPDATE",
  396. `Updating news item "${newsId}" successful for user "${session.userId}".`
  397. );
  398. return cb({
  399. status: "success",
  400. message: "Successfully updated news item"
  401. });
  402. }
  403. );
  404. })
  405. };