const express = require('express'); const req = require('express/lib/request'); module.exports = function (options) { const db = options.db; var router = express.Router(); router.route('/') .get(function(request, response, next) { db.Artifact.findAll({ }).then(artifacts => { response.display("library", { user: request.user, pageTitle: "Library - Mantra", artifacts: artifacts }) }).catch(error => { next(error) }) }) router.route('/add') .get(function(request, response, next) { if (request.user) { response.display("library-form", { user: request.user, pageTitle: "Add Library - Mantra", artifact: { version: "1.0" } }) } else { next() } }) .post(function(request, response, next) { if (request.user) { db.Dialect.findOne({ where: { languageId: "en", countryId: "int" } }).then(dialect => { if (dialect) { return db.Artifact.create({ creatorId: request.user.id, name: request.body.name, url: request.body.url, dialectId: dialect.id, licenseId: "copyright", artifactVersions: [ { creatorId: request.user.id, tag: request.body.version } ], entityId: request.user.individualEntityUser.entityUser.entityId }, { include: [ { association: db.Artifact.ArtifactVersions, } ] }) } else { response.redirect("/library/add") // TODO: Show error message on missing dialect... } }).then(artifact => { if (artifact) { response.redirect(`/library/${artifact.id}`) } else { next() } }).catch(error => { next(error) }) } else { next() } }) router.route('/:id') .get(function(request, response, next) { db.Artifact.findByPk(request.params.id, { include: [ { association: db.Artifact.ArtifactApproval }, { association: db.Artifact.ArtifactVersions } ] }).then(artifact => { if (artifact) { if (artifact.artifactVersions.length == 1) { response.redirect(`/v/${artifact.artifactVersions[0].id}`) } else { response.display("artifact", { user: request.user, pageTitle: "Library - Mantra", artifact: artifact }) } } else { next() } }).catch(error => { next(error) }) }) return router; };