]>
Commit | Line | Data |
---|---|---|
69b0a27c C |
1 | const mongoose = require('mongoose') |
2 | ||
9bd26629 | 3 | const customUsersValidators = require('../helpers/custom-validators').users |
5c39adb7 | 4 | const modelUtils = require('./utils') |
9bd26629 | 5 | |
69b0a27c C |
6 | // --------------------------------------------------------------------------- |
7 | ||
8 | const UserSchema = mongoose.Schema({ | |
5c39adb7 C |
9 | createdDate: { |
10 | type: Date, | |
11 | default: Date.now | |
12 | }, | |
69b0a27c | 13 | password: String, |
9bd26629 C |
14 | username: String, |
15 | role: String | |
69b0a27c C |
16 | }) |
17 | ||
9bd26629 C |
18 | UserSchema.path('password').required(customUsersValidators.isUserPasswordValid) |
19 | UserSchema.path('username').required(customUsersValidators.isUserUsernameValid) | |
20 | UserSchema.path('role').validate(customUsersValidators.isUserRoleValid) | |
21 | ||
22 | UserSchema.methods = { | |
23 | toFormatedJSON: toFormatedJSON | |
24 | } | |
69b0a27c C |
25 | |
26 | UserSchema.statics = { | |
5c39adb7 | 27 | countTotal: countTotal, |
2f372a86 | 28 | getByUsernameAndPassword: getByUsernameAndPassword, |
5c39adb7 | 29 | listForApi: listForApi, |
68a3b9f2 | 30 | loadById: loadById, |
9bd26629 | 31 | loadByUsername: loadByUsername |
69b0a27c C |
32 | } |
33 | ||
34 | mongoose.model('User', UserSchema) | |
35 | ||
36 | // --------------------------------------------------------------------------- | |
37 | ||
5c39adb7 | 38 | function countTotal (callback) { |
089ff2f2 C |
39 | return this.count(callback) |
40 | } | |
41 | ||
9bd26629 C |
42 | function getByUsernameAndPassword (username, password) { |
43 | return this.findOne({ username: username, password: password }) | |
44 | } | |
45 | ||
5c39adb7 C |
46 | function listForApi (start, count, sort, callback) { |
47 | const query = {} | |
48 | return modelUtils.listForApiWithCount.call(this, query, start, count, sort, callback) | |
69b0a27c C |
49 | } |
50 | ||
68a3b9f2 C |
51 | function loadById (id, callback) { |
52 | return this.findById(id, callback) | |
53 | } | |
54 | ||
9bd26629 C |
55 | function loadByUsername (username, callback) { |
56 | return this.findOne({ username: username }, callback) | |
57 | } | |
58 | ||
59 | function toFormatedJSON () { | |
60 | return { | |
61 | id: this._id, | |
62 | username: this.username, | |
63 | role: this.role | |
64 | } | |
69b0a27c | 65 | } |