news.js 9.9 KB

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