news.js 10 KB

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