project.controller.js 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. /**
  2. * @file Provides the model and operation for projects.
  3. * @author Inigo Valentin
  4. * @since 4.0.0
  5. */
  6. const logger = require('pino')();
  7. const db = require("../models");
  8. const Project = db.projects;
  9. const Op = db.Sequelize.Op;
  10. const LocaleService = require('../services/locale.service.js');
  11. const localeService = new LocaleService(db);
  12. const AuthService = require("../services/auth.service.js");
  13. const authService = new AuthService(db);
  14. /**
  15. * Create and save a new project.
  16. *
  17. * @param req The received request by the server.
  18. * @param res The request to be sent by the server.
  19. */
  20. exports.create = (req, res) => {
  21. // Check authentication
  22. const validation = authService.validateToken(req, res);
  23. if (validation.success === false){
  24. res.status(validation.code).send(validation.message);
  25. return;
  26. }
  27. const user = validation.user;
  28. // Validate request
  29. let missing = [];
  30. if (!req.body.permalink) missing.push("permalink");
  31. if (!req.body.title) missing.push("title");
  32. if (!req.body.header) missing.push("header");
  33. if (!req.body.type) missing.push("type");
  34. if (!req.body.license) missing.push("license");
  35. if (missing.length > 0){
  36. let message = "Missing required fields: [";
  37. for (let i = 0; i < missing.length; i ++){
  38. message += missing[i];
  39. if (i < missing.length - 1) message += ", ";
  40. }
  41. message += "].";
  42. res.status(400).send(message);
  43. return;
  44. }
  45. let permalink = req.body.permalink;
  46. // TODO: Validate and format permalink.
  47. let idx = 0; // TODO: Obtain it.
  48. const title = localeService.generateLocalizedObject(req.body.title, "PROJECT_" + permalink.toUpperCase().replace(" ", "").replace("-", "_"), "DB_PROJECT");
  49. if (title.valid === false){
  50. res.status(400).send("Invalid title values");
  51. return;
  52. }
  53. const header = localeService.generateLocalizedObject(req.body.header, "PROJECT_" + permalink.toUpperCase().replace(" ", "").replace("-", "_") + "_HEADER", "DB_PROJECT");
  54. if (header.valid === false){
  55. res.status(400).send("Invalid header values");
  56. return;
  57. }
  58. const text = localeService.generateLocalizedObject(req.body.text, "PROJECT_" + permalink.toUpperCase().replace(" ", "").replace("-", "_") + "_TEXT", "DB_PROJECT");
  59. const comment = localeService.generateLocalizedObject(req.body.comment, "PROJECT_" + permalink.toUpperCase().replace(" ", "").replace("-", "_") + "_COMMENT", "DB_PROJECT");
  60. const type = req.body.type; // TODO: Validate
  61. const logo = req.body.logo;
  62. const license = req.body.license; // TODO: Validate
  63. const visible = ((req.body.visible + "").toLowerCase() === 'true') ? true : false;
  64. localeService.saveLocalizedObject(title);
  65. localeService.saveLocalizedObject(header);
  66. localeService.saveLocalizedObject(text);
  67. localeService.saveLocalizedObject(comment);
  68. // Create a Project
  69. const Project = {
  70. permalink: permalink,
  71. user: user,
  72. idx: idx,
  73. projectTypeId: type,
  74. title: title,
  75. logo: logo,
  76. header: header,
  77. text: text,
  78. comment: comment,
  79. licenseId: license,
  80. visible: visible
  81. };
  82. // Save Project in the database
  83. Project.create(Project)
  84. .then(data => {res.send(data);})
  85. .catch(err => {
  86. logger.error("Error creating project: " + err);
  87. res.status(500).send("Error creating project.");
  88. });
  89. };
  90. /**
  91. * Retrieve all projects from the database.
  92. *
  93. * @param req The received request by the server.
  94. * @param res The request to be sent by the server.
  95. */
  96. exports.findAll = (req, res) => {
  97. Project.findAll({
  98. where: {visible: true},
  99. include: ["license", "type", "tags", {model: ProjectUrl, include: "type"}],
  100. attributes: {exclude: ['licenseId', 'projectTypeId']},
  101. order: [['idx', 'ASC'], ['id', 'DESC']]
  102. })
  103. .then(async data => {
  104. data = await localeService.localizeProjects(data, req);
  105. res.send(data);
  106. })
  107. .catch(err => {
  108. logger.error("Error retrieving projects: " + err);
  109. res.status(500).send("Error retrieving projects.");
  110. });
  111. };
  112. exports.findTop = (req, res) => {
  113. const limit = !isNaN(req.params.total) ? Number(req.params.total) : 3;
  114. Project.findAll({
  115. where: {visible: true},
  116. include: ["license", "type", "tags", {model: ProjectUrl, include: "type"}],
  117. attributes: {exclude: ['licenseId', 'projectTypeId']},
  118. order: [['idx', 'ASC'], ['id', 'DESC']],
  119. limit: limit
  120. })
  121. .then(async data => {
  122. data = await localeService.localizeProjects(data, req);
  123. res.send(data);
  124. })
  125. .catch(err => {
  126. logger.error("Error retrieving projects: " + err);
  127. res.status(500).send("Error retrieving projects.");
  128. });
  129. };
  130. /**
  131. * Find a single project by it's ID or permalink.
  132. *
  133. * @param req The received request by the server.
  134. * @param res The request to be sent by the server.
  135. */
  136. exports.findOne = (req, res) => {
  137. const id = req.params.id;
  138. Project.findOne({
  139. where: {visible: true, [Op.or]: {permalink: id, id: id }},
  140. include: ["license", "type", "tags", {model: ProjectUrl, include: "type"}, "project-images"],
  141. attributes: { exclude: ['licenseId', 'projectTypeId']}
  142. })
  143. .then(async data => {
  144. if (data){
  145. data = await localeService.localizeProject(data, req);
  146. res.send(data);
  147. }
  148. else res.status(404).send(`No project with id or permalink ${id}.`);
  149. })
  150. .catch(err => {
  151. logger.error("Error retrieving project with id or permalink " + id + ": " + err);
  152. res.status(500).send("Error retrieving project with id or permalink " + id + ".");
  153. });
  154. };
  155. /**
  156. * Update a single project by it's ID.
  157. *
  158. * @param req The received request by the server.
  159. * @param res The request to be sent by the server.
  160. */
  161. exports.update = (req, res) => {
  162. // Check authentication
  163. const validation = authService.validateToken(req, res);
  164. if (validation.success === false){
  165. res.status(validation.code).send(validation.message);
  166. return;
  167. }
  168. const id = req.params.id;
  169. Project.update(req.body, {where: {[Op.or]: {permalink: id, id: id }}, user: user})
  170. .then(num => {
  171. if (num == 1) res.send("Project updated successfully.");
  172. else res.send(`Cannot update project with id or permalink ${id}.`);
  173. })
  174. .catch(err => {
  175. logger.error("Error updating project with id or permalink " + id + ": " + err);
  176. res.status(500).send("Error updating project with id or permalink " + id + ".");
  177. });
  178. };
  179. /**
  180. * Delete a single project by it's ID.
  181. *
  182. * @param req The received request by the server.
  183. * @param res The request to be sent by the server.
  184. */
  185. exports.delete = (req, res) => {
  186. // Check authentication
  187. const validation = authService.validateToken(req, res);
  188. if (validation.success === false){
  189. res.status(validation.code).send(validation.message);
  190. return;
  191. }
  192. const user = validation.user;
  193. const id = req.params.id;
  194. Project.destroy({where: {[Op.or]: {permalink: id, id: id }}, user: user})
  195. .then(num => {
  196. if (num == 1) res.send({message: "Project deleted successfully."});
  197. else res.send(`Cannot delete project with id or permalink ${id}.`);
  198. })
  199. .catch(err => {
  200. logger.error("Error deleting project with id or permalink " + id + ": " + err);
  201. res.status(500).send("Error deleting project with id or permalink " + id + ".");
  202. });
  203. };
  204. /**
  205. * Delete all projects.
  206. *
  207. * @param req The received request by the server.
  208. * @param res The request to be sent by the server.
  209. */
  210. exports.deleteAll = (req, res) => {
  211. // Check authentication
  212. const validation = authService.validateToken(req, res);
  213. if (validation.success === false){
  214. res.status(validation.code).send(validation.message);
  215. return;
  216. }
  217. const user = validation.user;
  218. Project.destroy({where: {user: user}, truncate: false})
  219. .then(nums => {res.send(`${nums} projects deleted successfully.`);})
  220. .catch(err => {
  221. logger.error("Error deleting projects: " + err);
  222. res.status(500).send("Error deleting projects.");
  223. });
  224. };