Implémentation SkydiverId API

This commit is contained in:
Rampeur
2024-05-08 20:37:33 +02:00
parent eb64f2c411
commit a4d2b76bc5
43 changed files with 2772 additions and 1267 deletions
+31 -8
View File
@@ -2,22 +2,45 @@ var mongoose = require('mongoose');
var uniqueValidator = require('mongoose-unique-validator');
var slug = require('slug');
var QCMSchema = new mongoose.Schema({
var QcmSchema = new mongoose.Schema({
name: { type: String, lowercase: true, unique: true },
slug: { type: String, lowercase: true, unique: true },
categories: [
{ type: mongoose.Schema.Types.ObjectId, ref: 'QCMCategory' }
{ type: mongoose.Schema.Types.ObjectId, ref: 'QcmCategory' }
]
}, {timestamps: true, toJSON: {virtuals: true}});
QCMSchema.plugin(uniqueValidator, { message: 'is already taken' });
QcmSchema.plugin(uniqueValidator, { message: 'is already taken' });
QCMSchema.methods.toJSONFor = function(){
QcmSchema.pre('validate', function (next) {
if (!this.slug) {
this.slugify();
}
next();
});
QcmSchema.methods.slugify = function () {
this.slug = slug(`${this.name}-`) + (Math.random() * Math.pow(36, 6) | 0).toString(36);
};
QcmSchema.methods.addCategory = function (id) {
if (this.categories.indexOf(id) === -1) {
this.categories.push(id);
}
return this.save();
};
QcmSchema.methods.removeCategory = function (id) {
this.categories.remove(id);
return this.save();
};
QcmSchema.methods.toJSONFor = function() {
return {
name: this.name,
categories: this.categories,
createdAt: this.createdAt,
updatedAt: this.updatedAt
slug: this.slug,
categories: this.categories.map(category => category.toJSONFor())
};
};
mongoose.model('QCM', QCMSchema);
mongoose.model('Qcm', QcmSchema);