All files / server/controllers/project.controller getProjectsForUser.js

71.88% Statements 23/32
78.57% Branches 11/14
63.64% Functions 7/11
74.19% Lines 23/31

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73          1x     4x 4x 4x 2x 2x     2x 2x 2x                                     3x 2x     2x 1x   1x           1x 1x       3x 2x           2x 1x   1x         1x 1x    
import Project from '../../models/project';
import User from '../../models/user';
import { toApi as toApiProjectObject } from '../../domain-objects/Project';
import createApplicationErrorClass from '../../utils/createApplicationErrorClass';
 
const UserNotFoundError = createApplicationErrorClass('UserNotFoundError');
 
function getProjectsForUserName(username) {
  return new Promise((resolve, reject) => {
    User.findOne({ username }, (err, user) => {
      if (err) {
        reject(err);
        return;
      }
 
      Eif (!user) {
        reject(new UserNotFoundError());
        return;
      }
 
      Project.find({ user: user._id })
        .sort('-createdAt')
        .select('name files id createdAt updatedAt')
        .exec((innerErr, projects) => {
          if (innerErr) {
            reject(innerErr);
            return;
          }
 
          resolve(projects);
        });
    });
  });
}
 
export default function getProjectsForUser(req, res) {
  if (req.params.username) {
    return getProjectsForUserName(req.params.username)
      .then(projects => res.json(projects))
      .catch((err) => {
        if (err instanceof UserNotFoundError) {
          res.status(404).json({ message: 'User with that username does not exist.' });
        } else {
          res.status(500).json({ message: 'Error fetching projects' });
        }
      });
  }
 
  // could just move this to client side
  res.status(200).json([]);
  return Promise.resolve();
}
 
export function apiGetProjectsForUser(req, res) {
  if (req.params.username) {
    return getProjectsForUserName(req.params.username)
      .then((projects) => {
        const asApiObjects = projects.map(p => toApiProjectObject(p));
        res.json({ sketches: asApiObjects });
      })
      .catch((err) => {
        if (err instanceof UserNotFoundError) {
          res.status(404).json({ message: 'User with that username does not exist.' });
        } else {
          res.status(500).json({ message: 'Error fetching projects' });
        }
      });
  }
 
  res.status(422).json({ message: 'Username not provided' });
  return Promise.resolve();
}