51 lines
1.4 KiB
JavaScript
51 lines
1.4 KiB
JavaScript
var mongoose = require('mongoose');
|
|
var uniqueValidator = require('mongoose-unique-validator');
|
|
var slug = require('slug');
|
|
|
|
var ApplicationSchema = new mongoose.Schema({
|
|
apikey: String,
|
|
maskedkey: String,
|
|
slug: { type: String, lowercase: true, unique: true },
|
|
title: String,
|
|
description: String,
|
|
author: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }
|
|
}, { timestamps: true, toJSON: { virtuals: true } });
|
|
|
|
ApplicationSchema.plugin(uniqueValidator, { message: 'is already taken' });
|
|
|
|
ApplicationSchema.pre('validate', function (next) {
|
|
if (!this.slug) {
|
|
this.slugify();
|
|
}
|
|
next();
|
|
});
|
|
|
|
ApplicationSchema.methods.slugify = function () {
|
|
this.slug = slug(this.title) + '-' + (Math.random() * Math.pow(36, 6) | 0).toString(36);
|
|
};
|
|
|
|
ApplicationSchema.methods.toJSONFor = function (user) {
|
|
return {
|
|
maskedkey: this.maskedkey,
|
|
slug: this.slug,
|
|
title: this.title,
|
|
description: this.description,
|
|
createdAt: this.createdAt,
|
|
updatedAt: this.updatedAt,
|
|
author: this.author.toProfileJSONFor(user)
|
|
};
|
|
};
|
|
|
|
ApplicationSchema.methods.toAuthJSON = function () {
|
|
return {
|
|
maskedkey: this.maskedkey,
|
|
slug: this.slug,
|
|
title: this.title,
|
|
description: this.description,
|
|
createdAt: this.createdAt,
|
|
updatedAt: this.updatedAt,
|
|
author: this.author.toJSONFor()
|
|
};
|
|
};
|
|
|
|
mongoose.model('Application', ApplicationSchema); |