project.controller.js 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  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. /**
  113. * Find a single project by it's ID or permalink.
  114. *
  115. * @param req The received request by the server.
  116. * @param res The request to be sent by the server.
  117. */
  118. exports.findOne = (req, res) => {
  119. const id = req.params.id;
  120. Project.findOne({
  121. where: {visible: true, [Op.or]: {permalink: id, id: id }},
  122. include: ["license", "type", "tags", {model: ProjectUrl, include: "type"}, "project-images"],
  123. attributes: { exclude: ['licenseId', 'projectTypeId']}
  124. })
  125. .then(async data => {
  126. if (data){
  127. data = await localeService.localizeProject(data, req);
  128. res.send(data);
  129. }
  130. else res.status(404).send(`No project with id or permalink ${id}.`});
  131. })
  132. .catch(err => {
  133. logger.error("Error retrieving project with id or permalink " + id + ": " + err);
  134. res.status(500).send("Error retrieving project with id or permalink " + id + ".");
  135. });
  136. };
  137. /**
  138. * Update a single project by it's ID.
  139. *
  140. * @param req The received request by the server.
  141. * @param res The request to be sent by the server.
  142. */
  143. exports.update = (req, res) => {
  144. // Check authentication
  145. const validation = authService.validateToken(req, res);
  146. if (validation.success === false){
  147. res.status(validation.code).send(validation.message);
  148. return;
  149. }
  150. const id = req.params.id;
  151. Project.update(req.body, {where: {[Op.or]: {permalink: id, id: id }}, user: user}})
  152. .then(num => {
  153. if (num == 1) res.send("Project updated successfully.");
  154. else res.send(`Cannot update project with id or permalink ${id}.`);
  155. })
  156. .catch(err => {
  157. logger.error("Error updating project with id or permalink " + id + ": " + err);
  158. res.status(500).send("Error updating project with id or permalink " + id + ".");
  159. });
  160. };
  161. /**
  162. * Delete a single project by it's ID.
  163. *
  164. * @param req The received request by the server.
  165. * @param res The request to be sent by the server.
  166. */
  167. exports.delete = (req, res) => {
  168. // Check authentication
  169. const validation = authService.validateToken(req, res);
  170. if (validation.success === false){
  171. res.status(validation.code).send(validation.message);
  172. return;
  173. }
  174. const user = validation.user;
  175. const id = req.params.id;
  176. Project.destroy({where: {[Op.or]: {permalink: id, id: id }}, user: user}})
  177. .then(num => {
  178. if (num == 1) res.send({message: "Project deleted successfully."});
  179. else res.send({message: `Cannot delete project with id or permalink ${id}.`});
  180. })
  181. .catch(err => {
  182. logger.error("Error deleting project with id or permalink " + id + ": " + err);
  183. res.status(500).send("Error deleting project with id or permalink " + id + ".");
  184. });
  185. };
  186. /**
  187. * Delete all projects.
  188. *
  189. * @param req The received request by the server.
  190. * @param res The request to be sent by the server.
  191. */
  192. exports.deleteAll = (req, res) => {
  193. // Check authentication
  194. const validation = authService.validateToken(req, res);
  195. if (validation.success === false){
  196. res.status(validation.code).send(validation.message);
  197. return;
  198. }
  199. const user = validation.user;
  200. Project.destroy({where: {user: user}, truncate: false})
  201. .then(nums => {res.send(`${nums} projects deleted successfully.`);})
  202. .catch(err => {
  203. logger.error("Error deleting projects: " + err);
  204. res.status(500).send("Error deleting projects.");
  205. });
  206. };