news.js 10 KB

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