All files / server/models project.js

51.85% Statements 14/27
12.5% Branches 1/8
40% Functions 2/5
51.85% Lines 14/27

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 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92              5x   5x                       5x       5x       5x                       5x 3x     5x       5x 5x   5x 5x     5x           5x                                                          
import mongoose from 'mongoose';
import shortid from 'shortid';
import slugify from 'slugify';
 
// Register User model as it's referenced by Project
import './user';
 
const { Schema } = mongoose;
 
const fileSchema = new Schema(
  {
    name: { type: String, default: 'sketch.js' },
    content: { type: String, default: '' },
    url: { type: String },
    children: { type: [String], default: [] },
    fileType: { type: String, default: 'file' },
    isSelectedFile: { type: Boolean }
  },
  { timestamps: true, _id: true, usePushEach: true }
);
 
fileSchema.virtual('id').get(function getFileId() {
  return this._id.toHexString();
});
 
fileSchema.set('toJSON', {
  virtuals: true
});
 
const projectSchema = new Schema(
  {
    name: { type: String, default: "Hello p5.js, it's the server" },
    user: { type: Schema.Types.ObjectId, ref: 'User' },
    serveSecure: { type: Boolean, default: false },
    files: { type: [fileSchema] },
    _id: { type: String, default: shortid.generate },
    slug: { type: String }
  },
  { timestamps: true, usePushEach: true }
);
 
projectSchema.virtual('id').get(function getProjectId() {
  return this._id;
});
 
projectSchema.set('toJSON', {
  virtuals: true
});
 
projectSchema.pre('save', function generateSlug(next) {
  const project = this;
 
  Eif (!project.slug) {
    project.slug = slugify(project.name, '_');
  }
 
  return next();
});
 
/**
 * Check if slug is unique for this user's projects
 */
projectSchema.methods.isSlugUnique = async function isSlugUnique(cb) {
  const project = this;
  const hasCallback = typeof cb === 'function';
 
  try {
    const docsWithSlug = await project.model('Project')
      .find({ user: project.user, slug: project.slug }, '_id')
      .exec();
 
    const result = {
      isUnique: docsWithSlug.length === 0,
      conflictingIds: docsWithSlug.map(d => d._id) || []
    };
 
    if (hasCallback) {
      cb(null, result);
    }
 
    return result;
  } catch (err) {
    if (hasCallback) {
      cb(err, null);
    }
 
    throw err;
  }
};
 
export default mongoose.model('Project', projectSchema);