news.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  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: Number(data) };
  141. } else if (filterType === "numberLesser") {
  142. newQuery[filter.property] = { $lt: Number(data) };
  143. } else if (filterType === "numberGreater") {
  144. newQuery[filter.property] = { $gt: Number(data) };
  145. } else if (filterType === "numberGreaterEqual") {
  146. newQuery[filter.property] = { $gte: Number(data) };
  147. } else if (filterType === "numberEquals") {
  148. newQuery[filter.property] = { $eq: Number(data) };
  149. } else if (filterType === "boolean") {
  150. newQuery[filter.property] = { $eq: !!data };
  151. }
  152. if (filter.property === "createdBy")
  153. return { $or: [newQuery, { createdByUsername: newQuery.createdBy }] };
  154. return newQuery;
  155. });
  156. if (queryError) next(queryError);
  157. const queryObject = {};
  158. if (newQueries.length > 0) {
  159. if (operator === "and") queryObject.$and = newQueries;
  160. else if (operator === "or") queryObject.$or = newQueries;
  161. else if (operator === "nor") queryObject.$nor = newQueries;
  162. }
  163. pipeline.push({ $match: queryObject });
  164. next(null, pipeline);
  165. },
  166. // Adds sort stage to aggregation pipeline if there is at least one column being sorted, responsible for sorting data
  167. (pipeline, next) => {
  168. const newSort = Object.fromEntries(
  169. Object.entries(sort).map(([property, direction]) => [
  170. property,
  171. direction === "ascending" ? 1 : -1
  172. ])
  173. );
  174. if (Object.keys(newSort).length > 0) pipeline.push({ $sort: newSort });
  175. next(null, pipeline);
  176. },
  177. // Adds first project stage to aggregation pipeline, responsible for including only the requested properties
  178. (pipeline, next) => {
  179. pipeline.push({ $project: Object.fromEntries(properties.map(property => [property, 1])) });
  180. next(null, pipeline);
  181. },
  182. // Adds the facet stage to aggregation pipeline, responsible for returning a total document count, skipping and limitting the documents that will be returned
  183. (pipeline, next) => {
  184. pipeline.push({
  185. $facet: {
  186. count: [{ $count: "count" }],
  187. documents: [{ $skip: pageSize * (page - 1) }, { $limit: pageSize }]
  188. }
  189. });
  190. // console.dir(pipeline, { depth: 6 });
  191. next(null, pipeline);
  192. },
  193. // Executes the aggregation pipeline
  194. (pipeline, next) => {
  195. newsModel.aggregate(pipeline).exec((err, result) => {
  196. // console.dir(err);
  197. // console.dir(result, { depth: 6 });
  198. if (err) return next(err);
  199. if (result[0].count.length === 0) return next(null, 0, []);
  200. const { count } = result[0].count[0];
  201. const { documents } = result[0];
  202. // console.log(111, err, result, count, documents[0]);
  203. return next(null, count, documents);
  204. });
  205. }
  206. ],
  207. async (err, count, news) => {
  208. if (err && err !== true) {
  209. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  210. this.log("ERROR", "NEWS_GET_DATA", `Failed to get data from news. "${err}"`);
  211. return cb({ status: "error", message: err });
  212. }
  213. this.log("SUCCESS", "NEWS_GET_DATA", `Got data from news successfully.`);
  214. return cb({
  215. status: "success",
  216. message: "Successfully got data from news.",
  217. data: { data: news, count }
  218. });
  219. }
  220. );
  221. }),
  222. /**
  223. * Gets all news items that are published
  224. *
  225. * @param {object} session - the session object automatically added by the websocket
  226. * @param {Function} cb - gets called with the result
  227. */
  228. async getPublished(session, cb) {
  229. const newsModel = await DBModule.runJob("GET_MODEL", { modelName: "news" }, this);
  230. async.waterfall(
  231. [
  232. next => {
  233. newsModel.find({ status: "published" }).sort({ createdAt: "desc" }).exec(next);
  234. }
  235. ],
  236. async (err, news) => {
  237. if (err) {
  238. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  239. this.log("ERROR", "NEWS_INDEX", `Indexing news failed. "${err}"`);
  240. return cb({ status: "error", message: err });
  241. }
  242. this.log("SUCCESS", "NEWS_INDEX", `Indexing news successful.`, false);
  243. return cb({ status: "success", data: { news } });
  244. }
  245. );
  246. },
  247. /**
  248. * Gets a news item by id
  249. *
  250. * @param {object} session - the session object automatically added by the websocket
  251. * @param {string} newsId - the news item id
  252. * @param {Function} cb - gets called with the result
  253. */
  254. async getNewsFromId(session, newsId, cb) {
  255. const newsModel = await DBModule.runJob("GET_MODEL", { modelName: "news" }, this);
  256. async.waterfall(
  257. [
  258. next => {
  259. newsModel.findById(newsId, next);
  260. }
  261. ],
  262. async (err, news) => {
  263. if (err) {
  264. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  265. this.log("ERROR", "GET_NEWS_FROM_ID", `Getting news item ${newsId} failed. "${err}"`);
  266. return cb({ status: "error", message: err });
  267. }
  268. this.log("SUCCESS", "GET_NEWS_FROM_ID", `Got news item ${newsId} successfully.`, false);
  269. return cb({ status: "success", data: { news } });
  270. }
  271. );
  272. },
  273. /**
  274. * Creates a news item
  275. *
  276. * @param {object} session - the session object automatically added by the websocket
  277. * @param {object} data - the object of the news data
  278. * @param {Function} cb - gets called with the result
  279. */
  280. create: isAdminRequired(async function create(session, data, cb) {
  281. const newsModel = await DBModule.runJob("GET_MODEL", { modelName: "news" }, this);
  282. async.waterfall(
  283. [
  284. next => {
  285. data.createdBy = session.userId;
  286. data.createdAt = Date.now();
  287. newsModel.create(data, next);
  288. }
  289. ],
  290. async (err, news) => {
  291. if (err) {
  292. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  293. this.log("ERROR", "NEWS_CREATE", `Creating news failed. "${err}"`);
  294. return cb({ status: "error", message: err });
  295. }
  296. CacheModule.runJob("PUB", { channel: "news.create", value: news });
  297. this.log("SUCCESS", "NEWS_CREATE", `Creating news successful.`);
  298. return cb({
  299. status: "success",
  300. message: "Successfully created News"
  301. });
  302. }
  303. );
  304. }),
  305. /**
  306. * Gets the latest news item
  307. *
  308. * @param {object} session - the session object automatically added by the websocket
  309. * @param {Function} cb - gets called with the result
  310. */
  311. async newest(session, cb) {
  312. const newsModel = await DBModule.runJob("GET_MODEL", { modelName: "news" }, this);
  313. async.waterfall([next => newsModel.findOne({}).sort({ createdAt: "desc" }).exec(next)], async (err, news) => {
  314. if (err) {
  315. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  316. this.log("ERROR", "NEWS_NEWEST", `Getting the latest news failed. "${err}"`);
  317. return cb({ status: "error", message: err });
  318. }
  319. this.log("SUCCESS", "NEWS_NEWEST", `Successfully got the latest news.`, false);
  320. return cb({ status: "success", data: { news } });
  321. });
  322. },
  323. /**
  324. * Removes a news item
  325. *
  326. * @param {object} session - the session object automatically added by the websocket
  327. * @param {object} newsId - the id of the news item we want to remove
  328. * @param {Function} cb - gets called with the result
  329. */
  330. remove: isAdminRequired(async function remove(session, newsId, cb) {
  331. const newsModel = await DBModule.runJob("GET_MODEL", { modelName: "news" }, this);
  332. async.waterfall(
  333. [
  334. next => {
  335. if (!newsId) return next("Please provide a news item id to update.");
  336. return next();
  337. },
  338. next => {
  339. newsModel.deleteOne({ _id: newsId }, err => next(err));
  340. }
  341. ],
  342. async err => {
  343. if (err) {
  344. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  345. this.log(
  346. "ERROR",
  347. "NEWS_REMOVE",
  348. `Removing news "${newsId}" failed for user "${session.userId}". "${err}"`
  349. );
  350. return cb({ status: "error", message: err });
  351. }
  352. CacheModule.runJob("PUB", { channel: "news.remove", value: newsId });
  353. this.log("SUCCESS", "NEWS_REMOVE", `Removing news "${newsId}" successful by user "${session.userId}".`);
  354. return cb({
  355. status: "success",
  356. message: "Successfully removed News"
  357. });
  358. }
  359. );
  360. }),
  361. /**
  362. * Updates a news item
  363. *
  364. * @param {object} session - the session object automatically added by the websocket
  365. * @param {string} newsId - the id of the news item
  366. * @param {object} item - the news item object
  367. * @param {string} item.status - the status of the news e.g. published
  368. * @param {string} item.title - taken from a level-1 heading at the top of the markdown
  369. * @param {string} item.markdown - the markdown that forms the content of the news
  370. * @param {Function} cb - gets called with the result
  371. */
  372. update: isAdminRequired(async function update(session, newsId, item, cb) {
  373. const newsModel = await DBModule.runJob("GET_MODEL", { modelName: "news" }, this);
  374. async.waterfall(
  375. [
  376. next => {
  377. if (!newsId) return next("Please provide a news item id to update.");
  378. return next();
  379. },
  380. next => {
  381. newsModel.updateOne({ _id: newsId }, item, { upsert: true }, err => next(err));
  382. }
  383. ],
  384. async err => {
  385. if (err) {
  386. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  387. this.log(
  388. "ERROR",
  389. "NEWS_UPDATE",
  390. `Updating news item "${newsId}" failed for user "${session.userId}". "${err}"`
  391. );
  392. return cb({ status: "error", message: err });
  393. }
  394. CacheModule.runJob("PUB", { channel: "news.update", value: { ...item, _id: newsId } });
  395. this.log(
  396. "SUCCESS",
  397. "NEWS_UPDATE",
  398. `Updating news item "${newsId}" successful for user "${session.userId}".`
  399. );
  400. return cb({
  401. status: "success",
  402. message: "Successfully updated news item"
  403. });
  404. }
  405. );
  406. })
  407. };