news.js 10 KB

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