'use strict'; const knex = require('./knex'); const { HttpError } = require('./errors'); function curateStash(stash) { const curatedStash = { id: stash.id, name: stash.name, slug: stash.slug, }; return curatedStash; } async function fetchStash(stashId, sessionUser) { if (!sessionUser) { throw new HttpError('You are not authenthicated', 401); } const stash = await knex('stashes') .where({ id: stashId, user_id: sessionUser.id, }) .first(); if (!stash) { throw new HttpError('You are not authorized to modify this stash', 403); } return stash; } async function stashActor(actorId, stashId, sessionUser) { const stash = await fetchStash(stashId, sessionUser); await knex('stashes_actors') .insert({ stash_id: stash.id, actor_id: actorId, }); } async function stashScene(sceneId, stashId, sessionUser) { const stash = await fetchStash(stashId, sessionUser); await knex('stashes_scenes') .insert({ stash_id: stash.id, scene_id: sceneId, }); } async function unstashActor(actorId, stashId, sessionUser) { await knex .from('stashes_actors AS deletable') .where('deletable.actor_id', actorId) .where('deletable.stash_id', stashId) .whereExists(knex('stashes_actors') // verify user owns this stash .leftJoin('stashes', 'stashes.id', 'stashes_actors.stash_id') .where('stashes_actors.stash_id', knex.raw('deletable.stash_id')) .where('stashes.user_id', sessionUser.id)) .delete(); } async function unstashScene(sceneId, stashId, sessionUser) { await knex .from('stashes_scenes AS deletable') .where('deletable.scene_id', sceneId) .where('deletable.stash_id', stashId) .whereExists(knex('stashes_scenes') // verify user owns this stash .leftJoin('stashes', 'stashes.id', 'stashes_scenes.stash_id') .where('stashes_scenes.stash_id', knex.raw('deletable.stash_id')) .where('stashes.user_id', sessionUser.id)) .delete(); } module.exports = { curateStash, stashActor, stashScene, unstashScene, unstashActor, };