Apply Javascript styleguide

This commit is contained in:
Jonathan Cremin 2015-08-23 22:12:32 +01:00
parent 752ce964c8
commit 6e0f351093
30 changed files with 364 additions and 375 deletions

View file

@ -10,20 +10,20 @@ const debug = debugname('hostr-api');
const router = new Router();
let statsdOpts = {prefix: 'hostr-api', host: process.env.STATSD_HOST || 'localhost'};
const statsdOpts = {prefix: 'hostr-api', host: process.env.STATSD_HOST || 'localhost'};
router.use(stats(statsdOpts));
let statsd = new StatsD(statsdOpts);
router.use(function*(next) {
const statsd = new StatsD(statsdOpts);
router.use(function* statsMiddleware(next) {
this.statsd = statsd;
yield next;
});
router.use(cors({
origin: '*',
credentials: true
credentials: true,
}));
router.use('/*',function* (next) {
router.use('/*', function* authMiddleware(next) {
try {
yield next;
if (this.response.status === 404 && !this.response.body) {
@ -35,13 +35,13 @@ router.use('/*',function* (next) {
this.set('WWW-Authenticate', 'Basic');
this.status = 401;
this.body = err.message;
} else if(err.status === 404) {
} else if (err.status === 404) {
this.status = 404;
this.body = {
error: {
message: 'File not found',
code: 604
}
code: 604,
},
};
} else {
if (!err.status) {
@ -70,7 +70,7 @@ router.delete('/file/:id', auth, file.del);
router.delete('/file/:id', auth, file.del);
// Hack, if no route matches here, router does not dispatch at all
router.get('/(.*)', function* () {
router.get('/(.*)', function* errorMiddleware() {
this.throw(404);
});

View file

@ -7,7 +7,7 @@ const debug = debugname('hostr-api:auth');
const badLoginMsg = '{"error": {"message": "Incorrect login details.", "code": 607}}';
module.exports = function* (next) {
export default function* (next) {
const Users = this.db.Users;
const Files = this.db.Files;
const Logins = this.db.Logins;
@ -20,7 +20,6 @@ module.exports = function* (next) {
debug('Token found');
user = yield Users.findOne({'_id': objectID(userToken)});
} else {
const authUser = auth(this);
this.assert(authUser, 401, badLoginMsg);
const remoteIp = this.req.headers['x-real-ip'] || this.req.connection.remoteAddress;
@ -39,7 +38,7 @@ module.exports = function* (next) {
this.assert(!user.activationCode, 401, '{"error": {"message": "Account has not been activated.", "code": 603}}');
const uploadedTotal = yield Files.count({owner: user._id, status: {'$ne': 'deleted'}});
const uploadedToday = yield Files.count({owner: user._id, 'time_added': {'$gt': Math.ceil(Date.now()/1000)-86400}});
const uploadedToday = yield Files.count({owner: user._id, 'time_added': {'$gt': Math.ceil(Date.now() / 1000) - 86400}});
const normalisedUser = {
'id': user._id,
@ -48,10 +47,10 @@ module.exports = function* (next) {
'file_count': uploadedTotal,
'max_filesize': user.type === 'Pro' ? 524288000 : 20971520,
'plan': user.type || 'Free',
'uploads_today': uploadedToday
'uploads_today': uploadedToday,
};
this.response.set('Daily-Uploads-Remaining', user.type === 'Pro' ? 'unlimited' : 15 - uploadedToday);
this.user = normalisedUser;
debug('Authenticated user: ' + this.user.email);
yield next;
};
}

View file

@ -60,7 +60,7 @@ export function* post(next) {
const fileId = yield hostrId(Files);
// Fire an event to let the frontend map the GUID it sent to the real ID. Allows immediate linking to the file
let acceptedEvent = `{"type": "file-accepted", "data": {"id": "${fileId}", "guid": "${tempGuid}", "href": "${fileHost}/${fileId}"}}`;
const acceptedEvent = `{"type": "file-accepted", "data": {"id": "${fileId}", "guid": "${tempGuid}", "href": "${fileHost}/${fileId}"}}`;
this.redis.publish('/user/' + this.user.id, acceptedEvent);
this.statsd.incr('file.upload.accepted', 1);
@ -82,20 +82,20 @@ export function* post(next) {
upload.pipe(s3Upload(key));
const thumbsPromises = [
new Promise((resolve, reject) => {
new Promise((resolve) => {
const small = gm(upload).resize(150, 150, '>').stream();
small.pipe(fs.createWriteStream(path.join(storePath, fileId[0], '150', fileId + '_' + upload.filename)));
small.pipe(s3Upload(path.join('150', fileId + '_' + upload.filename))).on('finish', resolve);
}),
new Promise((resolve, reject) => {
new Promise((resolve) => {
const medium = gm(upload).resize(970, '>').stream();
medium.pipe(fs.createWriteStream(path.join(storePath, fileId[0], '970', fileId + '_' + upload.filename)));
medium.pipe(s3Upload(path.join('970', fileId + '_' + upload.filename))).on('finish', resolve);
})
}),
];
let dimensionsPromise = new Promise((resolve, reject) => {
const dimensionsPromise = new Promise((resolve, reject) => {
gm(upload).size((err, size) => {
if (err) {
reject(err);
@ -142,7 +142,7 @@ export function* post(next) {
status: 'active',
'last_accessed': null,
s3: false,
type: sniff(upload.filename)
type: sniff(upload.filename),
};
yield Files.insertOne(dbFile);
@ -175,7 +175,7 @@ export function* post(next) {
if (process.env.VIRUSTOTAL) {
// Check in the background
process.nextTick(function*() {
process.nextTick(function* malwareScan() {
debug('Malware Scan');
const { positive, result } = yield malware(dbFile);
if (positive) {
@ -202,20 +202,20 @@ export function* list() {
let limit = 20;
if (this.request.query.perpage === '0') {
limit = false;
} else if(this.request.query.perpage > 0) {
limit = parseInt(this.request.query.perpage / 1);
} else if (this.request.query.perpage > 0) {
limit = parseInt(this.request.query.perpage / 1, 10);
}
let skip = 0;
if (this.request.query.page) {
skip = parseInt(this.request.query.page - 1) * limit;
skip = parseInt(this.request.query.page - 1, 10) * limit;
}
const queryOptions = {
limit: limit, skip: skip, sort: [['time_added', 'desc']],
hint: {
owner: 1, status: 1, 'time_added': -1
}
owner: 1, status: 1, 'time_added': -1,
},
};
const userFiles = yield Files.find({owner: this.user.id, status: status}, queryOptions).toArray();
@ -266,7 +266,7 @@ export function* events() {
pubsub.on('message', (channel, message) => {
this.websocket.send(message);
});
this.websocket.on('close', function() {
this.websocket.on('close', () => {
pubsub.quit();
});
}

View file

@ -8,28 +8,28 @@ const debug = debugname('hostr-api:user');
const redisUrl = process.env.REDIS_URL || process.env.REDISTOGO_URL || 'redis://localhost:6379';
export function* get (){
export function* get() {
this.body = this.user;
}
export function* token(){
export function* token() {
const token = uuid.v4(); // eslint-disable-line no-shadow
yield this.redis.set(token, this.user.id, 'EX', 86400);
this.body = {token: token};
}
export function* transaction(){
export function* transaction() {
const Transactions = this.db.Transactions;
const transactions = yield Transactions.find({'user_id': this.user.id}).toArray();
this.body = transactions.map(function(transaction) { // eslint-disable-line no-shadow
this.body = transactions.map((transaction) => { // eslint-disable-line no-shadow
const type = transaction.paypal ? 'paypal' : 'direct';
return {
id: transaction._id,
amount: transaction.paypal ? transaction.amount : transaction.amount / 100,
date: transaction.date,
description: transaction.desc,
type: type
type: type,
};
});
}
@ -61,9 +61,9 @@ export function* events() {
this.websocket.send(message);
});
pubsub.on('ready', () => {
this.websocket.on('message', co.wrap(function* (message) {
this.websocket.on('message', co.wrap(function* wsMessage(message) {
let json;
try{
try {
json = JSON.parse(message);
} catch(err) {
debug('Invalid JSON for socket auth');