news.js 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  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 {Function} cb - gets called with the result
  236. */
  237. async newest(session, cb) {
  238. const newsModel = await DBModule.runJob("GET_MODEL", { modelName: "news" }, this);
  239. async.waterfall([next => newsModel.findOne({}).sort({ createdAt: "desc" }).exec(next)], async (err, news) => {
  240. if (err) {
  241. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  242. this.log("ERROR", "NEWS_NEWEST", `Getting the latest news failed. "${err}"`);
  243. return cb({ status: "error", message: err });
  244. }
  245. this.log("SUCCESS", "NEWS_NEWEST", `Successfully got the latest news.`, false);
  246. return cb({ status: "success", data: { news } });
  247. });
  248. },
  249. /**
  250. * Removes a news item
  251. *
  252. * @param {object} session - the session object automatically added by the websocket
  253. * @param {object} newsId - the id of the news item we want to remove
  254. * @param {Function} cb - gets called with the result
  255. */
  256. remove: isAdminRequired(async function remove(session, newsId, cb) {
  257. const newsModel = await DBModule.runJob("GET_MODEL", { modelName: "news" }, this);
  258. async.waterfall(
  259. [
  260. next => {
  261. if (!newsId) return next("Please provide a news item id to update.");
  262. return next();
  263. },
  264. next => {
  265. newsModel.deleteOne({ _id: newsId }, err => next(err));
  266. }
  267. ],
  268. async err => {
  269. if (err) {
  270. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  271. this.log(
  272. "ERROR",
  273. "NEWS_REMOVE",
  274. `Removing news "${newsId}" failed for user "${session.userId}". "${err}"`
  275. );
  276. return cb({ status: "error", message: err });
  277. }
  278. CacheModule.runJob("PUB", { channel: "news.remove", value: newsId });
  279. this.log("SUCCESS", "NEWS_REMOVE", `Removing news "${newsId}" successful by user "${session.userId}".`);
  280. return cb({
  281. status: "success",
  282. message: "Successfully removed News"
  283. });
  284. }
  285. );
  286. }),
  287. /**
  288. * Updates a news item
  289. *
  290. * @param {object} session - the session object automatically added by the websocket
  291. * @param {string} newsId - the id of the news item
  292. * @param {object} item - the news item object
  293. * @param {string} item.status - the status of the news e.g. published
  294. * @param {string} item.title - taken from a level-1 heading at the top of the markdown
  295. * @param {string} item.markdown - the markdown that forms the content of the news
  296. * @param {Function} cb - gets called with the result
  297. */
  298. update: isAdminRequired(async function update(session, newsId, item, cb) {
  299. const newsModel = await DBModule.runJob("GET_MODEL", { modelName: "news" }, this);
  300. async.waterfall(
  301. [
  302. next => {
  303. if (!newsId) return next("Please provide a news item id to update.");
  304. return next();
  305. },
  306. next => {
  307. newsModel.updateOne({ _id: newsId }, item, { upsert: true }, err => next(err));
  308. }
  309. ],
  310. async err => {
  311. if (err) {
  312. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  313. this.log(
  314. "ERROR",
  315. "NEWS_UPDATE",
  316. `Updating news item "${newsId}" failed for user "${session.userId}". "${err}"`
  317. );
  318. return cb({ status: "error", message: err });
  319. }
  320. CacheModule.runJob("PUB", { channel: "news.update", value: { ...item, _id: newsId } });
  321. this.log(
  322. "SUCCESS",
  323. "NEWS_UPDATE",
  324. `Updating news item "${newsId}" successful for user "${session.userId}".`
  325. );
  326. return cb({
  327. status: "success",
  328. message: "Successfully updated news item"
  329. });
  330. }
  331. );
  332. })
  333. };