news.js 9.7 KB

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