freeCodeCamp/common/models/promo.js

82 lines
1.8 KiB
JavaScript
Raw Normal View History

2015-11-23 23:38:05 +00:00
import { isAlphanumeric, isHexadecimal } from 'validator';
import debug from 'debug';
const log = debug('freecc:models:promo');
2015-10-25 21:26:37 +00:00
export default function promo(Promo) {
2015-11-23 23:38:05 +00:00
Promo.getButton = function getButton(id, code, type = 'isNot') {
const Job = Promo.app.models.Job;
if (!id || !isHexadecimal(id)) {
return Promise.reject(new Error(
'Must include job id'
));
}
2015-10-25 21:26:37 +00:00
if (
!isAlphanumeric(code) &&
type &&
!isAlphanumeric(type)
) {
return Promise.reject(new Error(
'Code or Type should be an alphanumeric'
));
}
const query = {
where: {
2015-11-23 23:38:05 +00:00
and: [{
code: type === 'isNot' ? type : 'isHighlighted'
},
{
type: type.replace(/^\$/g, '')
}]
2015-10-25 21:26:37 +00:00
}
};
2015-11-23 23:38:05 +00:00
return Promo.findOne(query)
.then(function(promo) {
2015-11-23 23:51:42 +00:00
// turn promo model to plain js object;
promo = promo.toJSON();
2015-11-23 23:38:05 +00:00
return Job.updateAll({ id: id }, { promoCodeUsed: code })
.then(function({ count = 0 } = {}) {
log('job', count);
if (count) {
2015-11-23 23:51:42 +00:00
return Object.assign({}, promo, { name: `${code} Discount` });
2015-11-23 23:38:05 +00:00
}
return Promise.reject(new Error(
`Job ${id} not found`
));
});
});
2015-10-25 21:26:37 +00:00
};
Promo.remoteMethod(
'getButton',
{
description: 'Get button id for promocode',
accepts: [
2015-11-23 23:38:05 +00:00
{
arg: 'id',
type: 'string',
required: true
},
2015-10-25 21:26:37 +00:00
{
arg: 'code',
type: 'string',
required: true
},
{
arg: 'type',
type: 'string'
}
],
returns: [
{
arg: 'promo',
type: 'object'
}
]
}
);
}