chore: commit lint fixes for the api

This commit is contained in:
Bouncey
2019-02-06 14:19:58 +00:00
committed by mrugesh mohapatra
parent 010fa63e76
commit 07266b7e43
17 changed files with 159 additions and 154 deletions

View File

@ -115,10 +115,10 @@ export default function(UserIdent) {
return identity return identity
? Observable.of(identity.user()) ? Observable.of(identity.user())
: User.findOne$({ where: { email } }).flatMap(user => { : User.findOne$({ where: { email } }).flatMap(user => {
return user return user
? Observable.of(user) ? Observable.of(user)
: User.create$({ email }).toPromise(); : User.create$({ email }).toPromise();
}); });
}) })
.flatMap(user => { .flatMap(user => {
const createToken = observeQuery(AccessToken, 'create', { const createToken = observeQuery(AccessToken, 'create', {

View File

@ -4,14 +4,19 @@ export function dashify(str) {
return ('' + str) return ('' + str)
.toLowerCase() .toLowerCase()
.replace(/\s/g, '-') .replace(/\s/g, '-')
.replace(/[^a-z0-9\-\.]/gi, '') .replace(/[^a-z0-9\-.]/gi, '')
.replace(/\:/g, ''); .replace(/:/g, '');
} }
// todo: unify with server/utils/index.js:dasherize // todo: unify with server/utils/index.js:dasherize
const dasherize = dashify; const dasherize = dashify;
export { dasherize }; export { dasherize };
export const fixCompletedChallengeItem = obj => pick( export const fixCompletedChallengeItem = obj =>
obj, pick(obj, [
[ 'id', 'completedDate', 'solution', 'githubLink', 'challengeType', 'files' ] 'id',
); 'completedDate',
'solution',
'githubLink',
'challengeType',
'files',
]);

View File

@ -21,9 +21,9 @@ export default function donateBoot(app, done) {
name: name:
'Monthly Donation to freeCodeCamp.org - ' + 'Monthly Donation to freeCodeCamp.org - ' +
`Thank you ($${current / 100})` `Thank you ($${current / 100})`
}, },
currency: 'usd', currency: 'usd',
id: `monthly-donation-${current}` id: `monthly-donation-${current}`
} }
}), {} }), {}
); );
@ -59,8 +59,8 @@ export default function donateBoot(app, done) {
throw err; throw err;
} }
console.log(`${plan.id} created`); console.log(`${plan.id} created`);
return; return;
}); });
} }
function createStripeDonation(req, res) { function createStripeDonation(req, res) {
@ -104,34 +104,34 @@ export default function donateBoot(app, done) {
email, email,
card: id card: id
}); });
}) })
.then(customer => { .then(customer => {
donation.customerId = customer.id; donation.customerId = customer.id;
return stripe.subscriptions.create({ return stripe.subscriptions.create({
customer: customer.id, customer: customer.id,
items: [ items: [
{ {
plan: `monthly-donation-${amount}` plan: `monthly-donation-${amount}`
} }
] ]
});
})
.then(subscription => {
donation.subscriptionId = subscription.id;
return res.send(subscription);
})
.then(() => {
donatingUser.createDonation(donation).toPromise()
.catch(err => {
throw new Error(err);
}); });
}) })
.catch(err => { .then(subscription => {
if (err.type === 'StripeCardError') { donation.subscriptionId = subscription.id;
return res.status(402).send({ error: err.message }); return res.send(subscription);
} })
return res.status(500).send({ error: 'Donation Failed' }); .then(() => {
}); donatingUser.createDonation(donation).toPromise()
.catch(err => {
throw new Error(err);
});
})
.catch(err => {
if (err.type === 'StripeCardError') {
return res.status(402).send({ error: err.message });
}
return res.status(500).send({ error: 'Donation Failed' });
});
} }
const pubKey = keys.stripe.public; const pubKey = keys.stripe.public;

View File

@ -88,7 +88,7 @@ module.exports = function(app) {
.then(() => { .then(() => {
req.flash( req.flash(
'success', 'success',
"We've successfully updated your email preferences." 'We\'ve successfully updated your email preferences.'
); );
return res.redirectWithFlash( return res.redirectWithFlash(
`${homeLocation}/unsubscribed/${unsubscribeId}` `${homeLocation}/unsubscribed/${unsubscribeId}`
@ -144,7 +144,7 @@ module.exports = function(app) {
.then(() => { .then(() => {
req.flash( req.flash(
'success', 'success',
"We've successfully updated your email preferences. Thank you " + 'We\'ve successfully updated your email preferences. Thank you ' +
'for resubscribing.' 'for resubscribing.'
); );
return res.redirectWithFlash(homeLocation); return res.redirectWithFlash(homeLocation);
@ -175,7 +175,7 @@ module.exports = function(app) {
} }
pulls = pulls pulls = pulls
? Object.keys(JSON.parse(pulls)).length ? Object.keys(JSON.parse(pulls)).length
: "Can't connect to github"; : 'Can\'t connect to github';
return request( return request(
[ [
@ -193,7 +193,7 @@ module.exports = function(app) {
issues = issues =
pulls === parseInt(pulls, 10) && issues pulls === parseInt(pulls, 10) && issues
? Object.keys(JSON.parse(issues)).length - pulls ? Object.keys(JSON.parse(issues)).length - pulls
: "Can't connect to GitHub"; : 'Can\'t connect to GitHub';
return res.send({ return res.send({
issues: issues, issues: issues,
pulls: pulls pulls: pulls

View File

@ -229,7 +229,7 @@ function createPostReportUserProfile(app) {
to: 'team@freecodecamp.org', to: 'team@freecodecamp.org',
cc: user.email, cc: user.email,
from: 'team@freecodecamp.org', from: 'team@freecodecamp.org',
subject: 'Abuse Report : Reporting ' + username + "'s profile.", subject: `Abuse Report : Reporting ${username}'s profile.`,
text: dedent(` text: dedent(`
Hello Team,\n Hello Team,\n
This is to report the profile of ${username}.\n This is to report the profile of ${username}.\n

View File

@ -3,7 +3,7 @@ import helmet from 'helmet';
import { homeLocation } from '../../../config/env'; import { homeLocation } from '../../../config/env';
let trusted = [ let trusted = [
"'self'", '\'self\'',
'https://search.freecodecamp.org', 'https://search.freecodecamp.org',
homeLocation, homeLocation,
'https://' + process.env.AUTH0_DOMAIN 'https://' + process.env.AUTH0_DOMAIN
@ -31,8 +31,8 @@ export default function csp() {
'https://*.algolia.net' 'https://*.algolia.net'
]), ]),
scriptSrc: [ scriptSrc: [
"'unsafe-eval'", '\'unsafe-eval\'',
"'unsafe-inline'", '\'unsafe-inline\'',
'*.google-analytics.com', '*.google-analytics.com',
'*.gstatic.com', '*.gstatic.com',
'https://*.cloudflare.com', 'https://*.cloudflare.com',
@ -48,7 +48,7 @@ export default function csp() {
'*.ytimg.com' '*.ytimg.com'
].concat(trusted), ].concat(trusted),
styleSrc: [ styleSrc: [
"'unsafe-inline'", '\'unsafe-inline\'',
'*.gstatic.com', '*.gstatic.com',
'*.googleapis.com', '*.googleapis.com',
'*.bootstrapcdn.com', '*.bootstrapcdn.com',

View File

@ -69,15 +69,15 @@ export default () => function authorizeByJWT(req, res, next) {
if (!req.user) { if (!req.user) {
const User = loopback.getModelByType('User'); const User = loopback.getModelByType('User');
return User.findById(userId) return User.findById(userId)
.then(user => { .then(user => {
if (user) { if (user) {
user.points = user.progressTimestamps.length; user.points = user.progressTimestamps.length;
req.user = user; req.user = user;
} }
return; return;
}) })
.then(next) .then(next)
.catch(next); .catch(next);
} else { } else {
return next(); return next();
} }

View File

@ -33,35 +33,35 @@ class NewsFeed {
const currentFeed = this.state.combinedFeed.slice(0); const currentFeed = this.state.combinedFeed.slice(0);
log('grabbing feeds'); log('grabbing feeds');
return Promise.all([ return Promise.all([
getMediumFeed(), getMediumFeed(),
getLybsynFeed() getLybsynFeed()
]).then( ]).then(
([mediumFeed, lybsynFeed]) => this.setState( ([mediumFeed, lybsynFeed]) => this.setState(
state => ({ state => ({
...state, ...state,
mediumFeed, mediumFeed,
lybsynFeed lybsynFeed
})
))
.then(() => {
log('crossing the streams');
const { mediumFeed, lybsynFeed} = this.state;
const combinedFeed = [ ...mediumFeed, ...lybsynFeed ].sort((a, b) => {
return compareDesc(a.isoDate, b.isoDate);
});
this.setState(state => ({
...state,
combinedFeed,
readyState: true
}));
}) })
)) .catch(err => {
.then(() => { console.log(err);
log('crossing the streams'); this.setState(state => ({
const { mediumFeed, lybsynFeed} = this.state; ...state,
const combinedFeed = [ ...mediumFeed, ...lybsynFeed ].sort((a, b) => { combinedFeed: currentFeed
return compareDesc(a.isoDate, b.isoDate); }));
}); });
this.setState(state => ({
...state,
combinedFeed,
readyState: true
}));
})
.catch(err => {
console.log(err);
this.setState(state => ({
...state,
combinedFeed: currentFeed
}));
});
} }

View File

@ -31,12 +31,12 @@ export function getLybsynFeed() {
]) ])
) )
/* eslint-disable camelcase */ /* eslint-disable camelcase */
.map(({ full_item_url, item_title, release_date, item_body_short}) => ({ .map(({ full_item_url, item_title, release_date, item_body_short}) => ({
title: item_title, title: item_title,
extract: item_body_short, extract: item_body_short,
isoDate: new Date(release_date).toISOString(), isoDate: new Date(release_date).toISOString(),
link: full_item_url link: full_item_url
})); }));
/* eslint-enable camelcase */ /* eslint-enable camelcase */
return resolve(items); return resolve(items);
}); });

View File

@ -11,7 +11,7 @@ function getExtract(str) {
function addResponsiveClass(str) { function addResponsiveClass(str) {
return str.replace(/\<img/g, '<img class="img-responsive"'); return str.replace(/<img/g, '<img class="img-responsive"');
} }
export function getMediumFeed() { export function getMediumFeed() {

View File

@ -13,12 +13,12 @@ export default function getChallengesForBlock(app) {
return { return {
name: 'challenge', name: 'challenge',
read: function readChallengesForBlock( read: function readChallengesForBlock(
req, req,
resource, resource,
{ dashedName, blockName} = {}, { dashedName, blockName} = {},
config, config,
cb cb
) { ) {
const getChallengeBlock$ = challengeMap const getChallengeBlock$ = challengeMap
.flatMap(({ .flatMap(({
result: { superBlocks }, result: { superBlocks },

View File

@ -25,7 +25,6 @@ export default function userServices() {
config, config,
cb) { cb) {
const queryUser = req.user; const queryUser = req.user;
console.log(queryUser.completedChallengeCount)
const source = queryUser && Observable.forkJoin( const source = queryUser && Observable.forkJoin(
queryUser.getCompletedChallenges$(), queryUser.getCompletedChallenges$(),
queryUser.getPoints$(), queryUser.getPoints$(),
@ -63,7 +62,7 @@ export default function userServices() {
result: user.username result: user.username
}) })
) )
) )
.subscribe( .subscribe(
user => cb(null, user), user => cb(null, user),
cb cb

View File

@ -7,5 +7,5 @@ export function dayCount([head, tail], timezone = 'UTC') {
moment(tail).tz(timezone).startOf('day'), moment(tail).tz(timezone).startOf('day'),
'days', 'days',
true) true)
); );
} }

View File

@ -1,4 +1,3 @@
function getCompletedCertCount(user) { function getCompletedCertCount(user) {
return [ return [
'isApisMicroservicesCert', 'isApisMicroservicesCert',
@ -7,46 +6,48 @@ function getCompletedCertCount(user) {
'isInfosecQaCert', 'isInfosecQaCert',
'isJsAlgoDataStructCert', 'isJsAlgoDataStructCert',
'isRespWebDesignCert' 'isRespWebDesignCert'
].reduce((sum, key) => user[key] ? sum + 1 : sum, 0); ].reduce((sum, key) => (user[key] ? sum + 1 : sum), 0);
} }
function getLegacyCertCount(user) { function getLegacyCertCount(user) {
return [ return ['isFrontEndCert', 'isBackEndCert', 'isDataVisCert'].reduce(
'isFrontEndCert', (sum, key) => (user[key] ? sum + 1 : sum),
'isBackEndCert', 0
'isDataVisCert' );
].reduce((sum, key) => user[key] ? sum + 1 : sum, 0);
} }
export default function populateUser(db, user) { export default function populateUser(db, user) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
let populatedUser = {...user}; let populatedUser = { ...user };
db.collection('user') db.collection('user')
.aggregate([ .aggregate([
{ $match: { _id: user.id } }, { $match: { _id: user.id } },
{ $project: { points: { $size: '$progressTimestamps' } } } { $project: { points: { $size: '$progressTimestamps' } } },
]).get(function(err, [{ points = 1 } = {}]) { ])
if (err) { return reject(err); } .get(function(err, [{ points = 1 } = {}]) {
user.points = points; if (err) {
let completedChallengeCount = 0; return reject(err);
let completedProjectCount = 0; }
if ('completedChallenges' in user) { user.points = points;
completedChallengeCount = user.completedChallenges.length; let completedChallengeCount = 0;
user.completedChallenges.forEach(item => { let completedProjectCount = 0;
if ( if ('completedChallenges' in user) {
'challengeType' in item && completedChallengeCount = user.completedChallenges.length;
(item.challengeType === 3 || item.challengeType === 4) user.completedChallenges.forEach(item => {
) { if (
completedProjectCount++; 'challengeType' in item &&
} (item.challengeType === 3 || item.challengeType === 4)
}); ) {
} completedProjectCount++;
populatedUser.completedChallengeCount = completedChallengeCount; }
populatedUser.completedProjectCount = completedProjectCount; });
populatedUser.completedCertCount = getCompletedCertCount(user); }
populatedUser.completedLegacyCertCount = getLegacyCertCount(user); populatedUser.completedChallengeCount = completedChallengeCount;
populatedUser.completedChallenges = []; populatedUser.completedProjectCount = completedProjectCount;
return resolve(populatedUser); populatedUser.completedCertCount = getCompletedCertCount(user);
}); populatedUser.completedLegacyCertCount = getLegacyCertCount(user);
populatedUser.completedChallenges = [];
return resolve(populatedUser);
});
}); });
} }

View File

@ -2,25 +2,25 @@ exports.dasherize = function dasherize(name) {
return ('' + name) return ('' + name)
.toLowerCase() .toLowerCase()
.replace(/\s/g, '-') .replace(/\s/g, '-')
.replace(/[^a-z0-9\-\.]/gi, '') .replace(/[^a-z0-9\-.]/gi, '')
.replace(/\:/g, ''); .replace(/:/g, '');
} };
exports.nameify = function nameify(str) { exports.nameify = function nameify(str) {
return ('' + str) return ('' + str).replace(/[^a-zA-Z0-9\s]/g, '').replace(/:/g, '');
.replace(/[^a-zA-Z0-9\s]/g, '') };
.replace(/\:/g, '');
}
exports.unDasherize = function unDasherize(name) { exports.unDasherize = function unDasherize(name) {
return ('' + name) return (
// replace dash with space ('' + name)
.replace(/\-/g, ' ') // replace dash with space
// strip nonalphanumarics chars except whitespace .replace(/-/g, ' ')
.replace(/[^a-zA-Z\d\s]/g, '') // strip nonalphanumarics chars except whitespace
.trim(); .replace(/[^a-zA-Z\d\s]/g, '')
} .trim()
);
};
exports.addPlaceholderImage = function addPlaceholderImage(name) { exports.addPlaceholderImage = function addPlaceholderImage(name) {
return `https://identicon.org?t=${name}&s=256`; return `https://identicon.org?t=${name}&s=256`;
} };

View File

@ -69,7 +69,7 @@ export function getProgress(progressTimestamps, timezone = 'EST') {
.reduce((data, timestamp) => { .reduce((data, timestamp) => {
data[Math.floor(timestamp / 1000)] = 1; data[Math.floor(timestamp / 1000)] = 1;
return data; return data;
}, {}); }, {});
const uniqueHours = prepUniqueDaysByHours(progressTimestamps, timezone); const uniqueHours = prepUniqueDaysByHours(progressTimestamps, timezone);
const streak = { const streak = {
longest: calcLongestStreak(uniqueHours, timezone), longest: calcLongestStreak(uniqueHours, timezone),

View File

@ -25,7 +25,7 @@ export function getHost() {
export function getServerFullURL() { export function getServerFullURL() {
if (!isDev) { if (!isDev) {
return getProtocol() return getProtocol()
+ '://' + '://'
+ getHost(); + getHost();
} }