news.js 10 KB

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