news.js 10 KB

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