'use strict'
const Groupe = require('../../constructors/Groupe')
const { getNormalizedName } = require('../lib/normalize')
const { uniq } = require('lodash')
module.exports = function (component) {
component.entity('EntityGroupe', function ($cacheGroupe) {
const EntityGroupe = this
EntityGroupe.validateJsonSchema({
type: 'object',
properties: {
oid: { type: 'string' },
nom: { type: 'string' },
description: { type: 'string' },
ouvert: { type: 'boolean' },
public: { type: 'boolean' },
gestionnaires: {
type: 'array',
items: { type: 'string' },
uniqueItems: true
},
dateCreation: { instanceof: 'Date' }
},
additionalProperties: false,
required: [
'nom',
'ouvert',
'public',
'gestionnaires'
]
})
/**
* L'entité groupe
* @entity EntityGroupe
* @extends Entity
* @extends Groupe
*/
EntityGroupe.construct(function (values) {
Object.assign(this, new Groupe(values))
})
EntityGroupe.beforeStore(function (next) {
if (!this.dateCreation) this.dateCreation = new Date()
if (!this.gestionnaires || !this.gestionnaires.length) return next(new Error(`Impossible de sauvegarder un groupe sans gestionnaires (${this.nom})`))
// _.uniq plus rapide que Array.from(new Set(initialArray))
// https://jsperf.com/lodash-uniq-vs-set-vs-jquery-uniquesort
if (this.gestionnaires.length > 1) this.gestionnaires = uniq(this.gestionnaires)
next()
})
EntityGroupe.afterStore(function (next) {
// on met en cache
$cacheGroupe.set(this, function (error) { if (error) log.error(error) })
// et on passe au suivant sans se préoccuper du retour de mise en cache
next()
})
// NOTE : en cas de pb d'unicité sur le nom, lancer localement
// `./scripts/mongoApp -f ./scripts-mongo/fixUniqueGroupeNom.js`
EntityGroupe
.defineIndex('nom', { normalizer: getNormalizedName, unique: true })
.defineIndex('ouvert', 'boolean')
.defineIndex('public', 'boolean')
.defineIndex('gestionnaires')
})
}