* feat: Add alias property to task model
This commit is contained in:
Blade Barringer
2016-06-16 12:28:45 -05:00
committed by GitHub
parent c34c21192b
commit b7b61e6251
21 changed files with 536 additions and 97 deletions

View File

@@ -3,6 +3,7 @@ import shared from '../../../common';
import validator from 'validator';
import moment from 'moment';
import baseModel from '../libs/api-v3/baseModel';
import { InternalServerError } from '../libs/api-v3/errors';
import _ from 'lodash';
import { preenHistory } from '../libs/api-v3/preening';
@@ -25,6 +26,21 @@ export let TaskSchema = new Schema({
type: {type: String, enum: tasksTypes, required: true, default: tasksTypes[0]},
text: {type: String, required: true},
notes: {type: String, default: ''},
alias: {
type: String,
match: [/^[a-zA-Z0-9-_]+$/, 'Task short names can only contain alphanumeric characters, underscores and dashes.'],
validate: [{
validator () {
return Boolean(this.userId);
},
msg: 'Task short names can only be applied to tasks in a user\'s own task list.',
}, {
validator (val) {
return !validator.isUUID(val);
},
msg: 'Task short names cannot be uuids.',
}],
},
tags: [{
type: String,
validate: [validator.isUUID, 'Invalid uuid.'],
@@ -73,6 +89,25 @@ TaskSchema.plugin(baseModel, {
timestamps: true,
});
TaskSchema.statics.findByIdOrAlias = async function findByIdOrAlias (identifier, userId, additionalQueries = {}) {
// not using i18n strings because these errors are meant for devs who forgot to pass some parameters
if (!identifier) throw new InternalServerError('Task identifier is a required argument');
if (!userId) throw new InternalServerError('User identifier is a required argument');
let query = _.cloneDeep(additionalQueries);
if (validator.isUUID(identifier)) {
query._id = identifier;
} else {
query.userId = userId;
query.alias = identifier;
}
let task = await this.findOne(query).exec();
return task;
};
// Sanitize user tasks linked to a challenge
// See http://habitica.wikia.com/wiki/Challenges#Challenge_Participant.27s_Permissions for more info
TaskSchema.statics.sanitizeUserChallengeTask = function sanitizeUserChallengeTask (taskObj) {
@@ -167,6 +202,20 @@ TaskSchema.statics.fromJSONV2 = function fromJSONV2 (taskObj) {
export let Task = mongoose.model('Task', TaskSchema);
Task.schema.path('alias').validate(function valiateAliasNotTaken (alias, respond) {
Task.findOne({
_id: { $ne: this._id },
userId: this.userId,
alias,
}).exec().then((task) => {
let aliasAvailable = !task;
respond(aliasAvailable);
}).catch(() => {
respond(false);
});
}, 'Task alias already used on another task.');
// habits and dailies shared fields
let habitDailySchema = () => {
return {history: Array}; // [{date:Date, value:Number}], // this causes major performance problems