news.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  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. next => {
  66. const newQueries = queries.map(query => {
  67. const { data, filter, filterType } = query;
  68. const newQuery = {};
  69. if (filterType === "regex") {
  70. newQuery[filter.property] = new RegExp(`${data.slice(1, data.length - 1)}`, "i");
  71. } else if (filterType === "contains") {
  72. newQuery[filter.property] = new RegExp(
  73. `${data.replaceAll(/[.*+?^${}()|[\]\\]/g, "\\$&")}`,
  74. "i"
  75. );
  76. } else if (filterType === "exact") {
  77. newQuery[filter.property] = data.toString();
  78. } else if (filterType === "datetimeBefore") {
  79. newQuery[filter.property] = { $lte: new Date(data) };
  80. } else if (filterType === "datetimeAfter") {
  81. newQuery[filter.property] = { $gte: new Date(data) };
  82. } else if (filterType === "numberLesserEqual") {
  83. newQuery[filter.property] = { $lte: data };
  84. } else if (filterType === "numberLesser") {
  85. newQuery[filter.property] = { $lt: data };
  86. } else if (filterType === "numberGreater") {
  87. newQuery[filter.property] = { $gt: data };
  88. } else if (filterType === "numberGreaterEqual") {
  89. newQuery[filter.property] = { $gte: data };
  90. } else if (filterType === "numberEquals") {
  91. newQuery[filter.property] = { $eq: data };
  92. }
  93. return newQuery;
  94. });
  95. const queryObject = {};
  96. if (newQueries.length > 0) {
  97. if (operator === "and") queryObject.$and = newQueries;
  98. else if (operator === "or") queryObject.$or = newQueries;
  99. else if (operator === "nor") queryObject.$nor = newQueries;
  100. }
  101. next(null, queryObject);
  102. },
  103. (queryObject, next) => {
  104. newsModel.find(queryObject).count((err, count) => {
  105. next(err, queryObject, count);
  106. });
  107. },
  108. (queryObject, count, next) => {
  109. newsModel
  110. .find(queryObject)
  111. .sort(sort)
  112. .skip(pageSize * (page - 1))
  113. .limit(pageSize)
  114. .select(properties.join(" "))
  115. .exec((err, news) => {
  116. next(err, count, news);
  117. });
  118. }
  119. ],
  120. async (err, count, news) => {
  121. if (err && err !== true) {
  122. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  123. this.log("ERROR", "NEWS_GET_DATA", `Failed to get data from news. "${err}"`);
  124. return cb({ status: "error", message: err });
  125. }
  126. this.log("SUCCESS", "NEWS_GET_DATA", `Got data from news successfully.`);
  127. return cb({
  128. status: "success",
  129. message: "Successfully got data from news.",
  130. data: { data: news, count }
  131. });
  132. }
  133. );
  134. }),
  135. /**
  136. * Gets all news items that are published
  137. *
  138. * @param {object} session - the session object automatically added by the websocket
  139. * @param {Function} cb - gets called with the result
  140. */
  141. async getPublished(session, cb) {
  142. const newsModel = await DBModule.runJob("GET_MODEL", { modelName: "news" }, this);
  143. async.waterfall(
  144. [
  145. next => {
  146. newsModel.find({ status: "published" }).sort({ createdAt: "desc" }).exec(next);
  147. }
  148. ],
  149. async (err, news) => {
  150. if (err) {
  151. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  152. this.log("ERROR", "NEWS_INDEX", `Indexing news failed. "${err}"`);
  153. return cb({ status: "error", message: err });
  154. }
  155. this.log("SUCCESS", "NEWS_INDEX", `Indexing news successful.`, false);
  156. return cb({ status: "success", data: { news } });
  157. }
  158. );
  159. },
  160. /**
  161. * Gets a news item by id
  162. *
  163. * @param {object} session - the session object automatically added by the websocket
  164. * @param {string} newsId - the news item id
  165. * @param {Function} cb - gets called with the result
  166. */
  167. async getNewsFromId(session, newsId, cb) {
  168. const newsModel = await DBModule.runJob("GET_MODEL", { modelName: "news" }, this);
  169. async.waterfall(
  170. [
  171. next => {
  172. newsModel.findById(newsId, next);
  173. }
  174. ],
  175. async (err, news) => {
  176. if (err) {
  177. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  178. this.log("ERROR", "GET_NEWS_FROM_ID", `Getting news item ${newsId} failed. "${err}"`);
  179. return cb({ status: "error", message: err });
  180. }
  181. this.log("SUCCESS", "GET_NEWS_FROM_ID", `Got news item ${newsId} successfully.`, false);
  182. return cb({ status: "success", data: { news } });
  183. }
  184. );
  185. },
  186. /**
  187. * Creates a news item
  188. *
  189. * @param {object} session - the session object automatically added by the websocket
  190. * @param {object} data - the object of the news data
  191. * @param {Function} cb - gets called with the result
  192. */
  193. create: isAdminRequired(async function create(session, data, cb) {
  194. const newsModel = await DBModule.runJob("GET_MODEL", { modelName: "news" }, this);
  195. async.waterfall(
  196. [
  197. next => {
  198. data.createdBy = session.userId;
  199. data.createdAt = Date.now();
  200. newsModel.create(data, next);
  201. }
  202. ],
  203. async (err, news) => {
  204. if (err) {
  205. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  206. this.log("ERROR", "NEWS_CREATE", `Creating news failed. "${err}"`);
  207. return cb({ status: "error", message: err });
  208. }
  209. CacheModule.runJob("PUB", { channel: "news.create", value: news });
  210. this.log("SUCCESS", "NEWS_CREATE", `Creating news successful.`);
  211. return cb({
  212. status: "success",
  213. message: "Successfully created News"
  214. });
  215. }
  216. );
  217. }),
  218. /**
  219. * Gets the latest news item
  220. *
  221. * @param {object} session - the session object automatically added by the websocket
  222. * @param {Function} cb - gets called with the result
  223. */
  224. async newest(session, cb) {
  225. const newsModel = await DBModule.runJob("GET_MODEL", { modelName: "news" }, this);
  226. async.waterfall([next => newsModel.findOne({}).sort({ createdAt: "desc" }).exec(next)], async (err, news) => {
  227. if (err) {
  228. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  229. this.log("ERROR", "NEWS_NEWEST", `Getting the latest news failed. "${err}"`);
  230. return cb({ status: "error", message: err });
  231. }
  232. this.log("SUCCESS", "NEWS_NEWEST", `Successfully got the latest news.`, false);
  233. return cb({ status: "success", data: { news } });
  234. });
  235. },
  236. /**
  237. * Removes a news item
  238. *
  239. * @param {object} session - the session object automatically added by the websocket
  240. * @param {object} newsId - the id of the news item we want to remove
  241. * @param {Function} cb - gets called with the result
  242. */
  243. remove: isAdminRequired(async function remove(session, newsId, cb) {
  244. const newsModel = await DBModule.runJob("GET_MODEL", { modelName: "news" }, this);
  245. async.waterfall(
  246. [
  247. next => {
  248. if (!newsId) return next("Please provide a news item id to update.");
  249. return next();
  250. },
  251. next => {
  252. newsModel.deleteOne({ _id: newsId }, err => next(err));
  253. }
  254. ],
  255. async err => {
  256. if (err) {
  257. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  258. this.log(
  259. "ERROR",
  260. "NEWS_REMOVE",
  261. `Removing news "${newsId}" failed for user "${session.userId}". "${err}"`
  262. );
  263. return cb({ status: "error", message: err });
  264. }
  265. CacheModule.runJob("PUB", { channel: "news.remove", value: newsId });
  266. this.log("SUCCESS", "NEWS_REMOVE", `Removing news "${newsId}" successful by user "${session.userId}".`);
  267. return cb({
  268. status: "success",
  269. message: "Successfully removed News"
  270. });
  271. }
  272. );
  273. }),
  274. /**
  275. * Updates a news item
  276. *
  277. * @param {object} session - the session object automatically added by the websocket
  278. * @param {string} newsId - the id of the news item
  279. * @param {object} item - the news item object
  280. * @param {string} item.status - the status of the news e.g. published
  281. * @param {string} item.title - taken from a level-1 heading at the top of the markdown
  282. * @param {string} item.markdown - the markdown that forms the content of the news
  283. * @param {Function} cb - gets called with the result
  284. */
  285. update: isAdminRequired(async function update(session, newsId, item, cb) {
  286. const newsModel = await DBModule.runJob("GET_MODEL", { modelName: "news" }, this);
  287. async.waterfall(
  288. [
  289. next => {
  290. if (!newsId) return next("Please provide a news item id to update.");
  291. return next();
  292. },
  293. next => {
  294. newsModel.updateOne({ _id: newsId }, item, { upsert: true }, err => next(err));
  295. }
  296. ],
  297. async err => {
  298. if (err) {
  299. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  300. this.log(
  301. "ERROR",
  302. "NEWS_UPDATE",
  303. `Updating news item "${newsId}" failed for user "${session.userId}". "${err}"`
  304. );
  305. return cb({ status: "error", message: err });
  306. }
  307. CacheModule.runJob("PUB", { channel: "news.update", value: { ...item, _id: newsId } });
  308. this.log(
  309. "SUCCESS",
  310. "NEWS_UPDATE",
  311. `Updating news item "${newsId}" successful for user "${session.userId}".`
  312. );
  313. return cb({
  314. status: "success",
  315. message: "Successfully updated news item"
  316. });
  317. }
  318. );
  319. })
  320. };