christmas/routes/api/wishlist/index.js

41 lines
1.3 KiB
JavaScript
Raw Normal View History

2019-11-17 15:05:45 -08:00
const express = require('express')
2020-11-08 13:54:08 -08:00
module.exports = ({ db }) => {
2019-11-17 15:05:45 -08:00
const router = express.Router()
router.get('/', (req, res) => {
res.send({
route: 'wishlist'
})
})
router.post('/:user/:id/move/:direction', async (req, res) => {
try {
if (req.user._id !== req.params.user) return res.json({ error: 'Not correct user' })
const doc = await db.get(req.user._id)
const wishlist = doc.wishlist
if (req.params.direction === 'up') wishlist.reverse()
let moveFromIndex
wishlist.forEach(wish => {
2020-11-08 13:54:08 -08:00
if (wish.id === req.params.id) moveFromIndex = wishlist.indexOf(wish)
2019-11-17 15:05:45 -08:00
})
const moveToIndex = wishlist.findIndex(wish => {
2020-11-08 13:54:08 -08:00
return (wishlist.indexOf(wish) > moveFromIndex && wish.addedBy === req.user._id)
2019-11-17 15:05:45 -08:00
})
2020-11-08 13:54:08 -08:00
if (moveToIndex < 0 || moveToIndex > wishlist.length) return res.send({ error: 'Invalid move ' })
2019-11-17 15:05:45 -08:00
const original = wishlist[moveToIndex]
wishlist[moveToIndex] = wishlist[moveFromIndex]
wishlist[moveFromIndex] = original
if (req.params.direction === 'up') wishlist.reverse()
doc.wishlist = wishlist
await db.put(doc)
res.send({ error: false })
} catch (error) {
console.error(error)
res.send({ error: error.message })
}
})
return router
2020-11-08 13:54:08 -08:00
}