const express = require('express') const { Op } = require("sequelize") module.exports = function (options) { const db = options.db; var router = express.Router(); router.route('/:id') .get(function(request, response, next) { db.TranslationEntry.findByPk(request.params.id, { include: [ { association: db.TranslationEntry.Entry, required: true, include: [ { association: db.Entry.Chapters, required: true, limit: 1, // TODO: Order by chapter index } ] } ] }).then(translationEntry => { if (translationEntry) { response.redirect(`/translate/${translationEntry.id}/chapter/${translationEntry.entry.chapters[0].id}`) } else { next() } }) }) router.route('/:id/chapter/:chapterId') .get(function(request, response, next) { db.Chapter.findByPk(request.params.chapterId, { include: [ { association: db.Chapter.Chunks, include: [ { association: db.Chunk.Translation } ] }, { association: db.Chapter.Entry, required: true, include: [ { association: db.Entry.TranslationEntries, required: true, where: { id: request.params.id } }, { association: db.Entry.Dialect } ] } ] }).then(chapter => { if (chapter) { response.display("translate-chapter", { user: request.user, pageTitle: `Translate Chapter ${chapter.name}`, chapter: chapter }) } else { next() } }).catch(error => { next(error) }) }) router.route('/:id/chapter/:chapterId/t/:chunkIndex') .get(function(request, response, next) { const previousIndex = Number(request.params.chunkIndex)-1 const nextIndex = Number(request.params.chunkIndex)+1 db.Chunk.findAll({ where: { chapterId: request.params.chapterId, index: { [Op.between]: [ previousIndex, nextIndex ], } }, limit: 3, include: [ { association: db.Chunk.Translation }, { association: db.Chunk.Chapter, required: true, include: [ { association: db.Chapter.Entry, required: true, include: [ { association: db.Entry.TranslationEntries, required: true, where: { id: request.params.id } }, { association: db.Entry.Dialect } ] } ] } ] }).then(chunks => { if (chunks.length > 0) { const chunk = chunks.find(chunk => chunk.index == Number(request.params.chunkIndex)) response.display("translate-chunk", { user: request.user, pageTitle: `Translate ${chunk.chapter.entry.name}`, chunk: chunk, previousChunk: chunks.find(chunk => chunk.index == previousIndex), nextChunk: chunks.find(chunk => chunk.index == nextIndex) }) } else { next() } }).catch(error => { next(error) }) }) return router; };