2020-11-20 10:02:30 +00:00
|
|
|
const mongoose = require('mongoose');
|
|
|
|
const uniqueValidator = require('mongoose-unique-validator');
|
|
|
|
const slug = require('slug');
|
2020-04-13 00:02:40 +00:00
|
|
|
|
2020-11-20 10:02:30 +00:00
|
|
|
const TrackSchema = new mongoose.Schema(
|
|
|
|
{
|
|
|
|
slug: { type: String, lowercase: true, unique: true },
|
|
|
|
title: String,
|
|
|
|
description: String,
|
|
|
|
body: String,
|
|
|
|
visible: Boolean,
|
2020-11-23 16:51:22 +00:00
|
|
|
uploadedByUserAgent: String,
|
2020-11-20 10:02:30 +00:00
|
|
|
numEvents: { type: Number, default: 0 },
|
|
|
|
comments: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Comment' }],
|
|
|
|
author: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
|
|
|
|
trackData: { type: mongoose.Schema.Types.ObjectId, ref: 'TrackData' },
|
|
|
|
},
|
|
|
|
{ timestamps: true },
|
|
|
|
);
|
2020-04-13 00:02:40 +00:00
|
|
|
|
2020-11-20 10:02:30 +00:00
|
|
|
TrackSchema.plugin(uniqueValidator, { message: 'is already taken' });
|
2020-04-13 00:02:40 +00:00
|
|
|
|
2020-11-20 10:02:30 +00:00
|
|
|
TrackSchema.pre('validate', function (next) {
|
|
|
|
if (!this.slug) {
|
2020-04-13 00:02:40 +00:00
|
|
|
this.slugify();
|
|
|
|
}
|
|
|
|
|
|
|
|
next();
|
|
|
|
});
|
|
|
|
|
2020-11-20 10:02:30 +00:00
|
|
|
TrackSchema.methods.slugify = function () {
|
|
|
|
this.slug = slug(this.title) + '-' + ((Math.random() * Math.pow(36, 6)) | 0).toString(36);
|
2020-04-13 00:02:40 +00:00
|
|
|
};
|
|
|
|
|
2020-11-23 23:30:55 +00:00
|
|
|
TrackSchema.methods.isVisibleTo = function (user) {
|
|
|
|
if (this.visible) {
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!user) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (user._id.toString() === this.author._id.toString()) {
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
return false;
|
|
|
|
};
|
|
|
|
|
2020-11-18 21:17:00 +00:00
|
|
|
TrackSchema.methods.toJSONFor = function (user, include) {
|
2020-04-13 00:02:40 +00:00
|
|
|
return {
|
|
|
|
slug: this.slug,
|
|
|
|
title: this.title,
|
|
|
|
description: this.description,
|
|
|
|
createdAt: this.createdAt,
|
|
|
|
updatedAt: this.updatedAt,
|
2020-08-16 21:23:18 +00:00
|
|
|
visibleForAll: this.author ? this.author.areTracksVisibleForAll : false,
|
2020-08-28 19:50:53 +00:00
|
|
|
visible: this.visible,
|
2020-11-18 21:17:00 +00:00
|
|
|
author: this.author.toProfileJSONFor(user),
|
2020-11-21 16:49:38 +00:00
|
|
|
...(include && include.body ? { body: this.body } : {}),
|
2020-04-13 00:02:40 +00:00
|
|
|
};
|
|
|
|
};
|
|
|
|
|
|
|
|
mongoose.model('Track', TrackSchema);
|