Node 8 (WIP) (#9946)

* start upgrade to node 8

* upgrade travis

* improve travis

* Remove bluebird, babel (except for modules) from server (WIP) (#9947)

* remove bluebird, babel from server (except for modules)

* fixes

* fix path

* fix path

* fix export

* fix export

* fix test

* fix tests

* remove plugin for transform-object-rest-spread since it is supported in node8

* babel: correct syntax rest spread

* remove bluebird

* update migrations archive readme

* fix package-lock.json

* fix typo

* add package-loc
This commit is contained in:
Matteo Pagliazzi
2018-03-15 19:59:36 +01:00
committed by GitHub
parent b1b1e512f5
commit cb42a31c43
68 changed files with 786 additions and 1536 deletions

View File

@@ -1,10 +1,6 @@
{ {
"presets": ["es2015"],
"plugins": [ "plugins": [
"transform-object-rest-spread", "transform-es2015-modules-commonjs",
["transform-async-to-module-method", { "syntax-object-rest-spread",
"module": "bluebird",
"method": "coroutine"
}]
] ]
} }

View File

@@ -4,6 +4,7 @@ node_modules/**
.bower-registry/** .bower-registry/**
website/client-old/** website/client-old/**
website/client/** website/client/**
website/client/store/**
website/views/** website/views/**
website/build/** website/build/**
dist/** dist/**

2
.nvmrc
View File

@@ -1 +1 @@
6 8

View File

@@ -1,6 +1,6 @@
language: node_js language: node_js
node_js: node_js:
- '6' - '8'
services: services:
- mongodb - mongodb
cache: cache:
@@ -8,8 +8,6 @@ cache:
- 'node_modules' - 'node_modules'
addons: addons:
chrome: stable chrome: stable
before_install:
- npm install -g npm@5
before_script: before_script:
- npm run test:build - npm run test:build
- cp config.json.example config.json - cp config.json.example config.json

View File

@@ -1,4 +1,4 @@
FROM node:boron FROM node:8
# Upgrade NPM to v5 (Yarn is needed because of this bug https://github.com/npm/npm/issues/16807) # Upgrade NPM to v5 (Yarn is needed because of this bug https://github.com/npm/npm/issues/16807)
# The used solution is suggested here https://github.com/npm/npm/issues/16807#issuecomment-313591975 # The used solution is suggested here https://github.com/npm/npm/issues/16807#issuecomment-313591975

View File

@@ -1,4 +1,4 @@
FROM node:boron FROM node:8
ENV ADMIN_EMAIL admin@habitica.com ENV ADMIN_EMAIL admin@habitica.com
ENV AMAZON_PAYMENTS_CLIENT_ID amzn1.application-oa2-client.68ed9e6904ef438fbc1bf86bf494056e ENV AMAZON_PAYMENTS_CLIENT_ID amzn1.application-oa2-client.68ed9e6904ef438fbc1bf86bf494056e

View File

@@ -2,7 +2,6 @@ import { exec } from 'child_process';
import psTree from 'ps-tree'; import psTree from 'ps-tree';
import nconf from 'nconf'; import nconf from 'nconf';
import net from 'net'; import net from 'net';
import Bluebird from 'bluebird';
import { post } from 'superagent'; import { post } from 'superagent';
import { sync as glob } from 'glob'; import { sync as glob } from 'glob';
import Mocha from 'mocha'; import Mocha from 'mocha';
@@ -45,7 +44,7 @@ export function kill (proc) {
* before failing. * before failing.
*/ */
export function awaitPort (port, max = 60) { export function awaitPort (port, max = 60) {
return new Bluebird((rej, res) => { return new Promise((rej, res) => {
let socket; let socket;
let timeout; let timeout;
let interval; let interval;

View File

@@ -16,7 +16,6 @@
const authorName = 'Blade'; const authorName = 'Blade';
const authorUuid = '75f270e8-c5db-4722-a5e6-a83f1b23f76b'; const authorUuid = '75f270e8-c5db-4722-a5e6-a83f1b23f76b';
global.Promise = require('bluebird');
const MongoClient = require('mongodb').MongoClient; const MongoClient = require('mongodb').MongoClient;
const TaskQueue = require('cwait').TaskQueue; const TaskQueue = require('cwait').TaskQueue;
const logger = require('./utils/logger'); const logger = require('./utils/logger');

View File

@@ -11,7 +11,6 @@
* pm'ed each user asking if they would like their tasks reset to the previous day * pm'ed each user asking if they would like their tasks reset to the previous day
***************************************/ ***************************************/
global.Promise = require('bluebird');
const MongoClient = require('mongodb').MongoClient; const MongoClient = require('mongodb').MongoClient;
const TaskQueue = require('cwait').TaskQueue; const TaskQueue = require('cwait').TaskQueue;
const logger = require('./utils/logger'); const logger = require('./utils/logger');

View File

@@ -12,7 +12,6 @@
* from an object to a number, hence this migration. * from an object to a number, hence this migration.
***************************************/ ***************************************/
global.Promise = require('bluebird');
const TaskQueue = require('cwait').TaskQueue; const TaskQueue = require('cwait').TaskQueue;
const logger = require('./utils/logger'); const logger = require('./utils/logger');
const Timer = require('./utils/timer'); const Timer = require('./utils/timer');

View File

@@ -9,7 +9,6 @@
* and transfers a group's progress to it * and transfers a group's progress to it
***************************************/ ***************************************/
global.Promise = require('bluebird');
const TaskQueue = require('cwait').TaskQueue; const TaskQueue = require('cwait').TaskQueue;
const logger = require('./utils/logger'); const logger = require('./utils/logger');
const Timer = require('./utils/timer'); const Timer = require('./utils/timer');

View File

@@ -12,7 +12,6 @@
* <userid>@example.com * <userid>@example.com
***************************************/ ***************************************/
global.Promise = require('bluebird');
const TaskQueue = require('cwait').TaskQueue; const TaskQueue = require('cwait').TaskQueue;
const logger = require('./utils/logger'); const logger = require('./utils/logger');
const Timer = require('./utils/timer'); const Timer = require('./utils/timer');

View File

@@ -9,7 +9,6 @@
* they support a type and options and label * they support a type and options and label
* ***************************************/ * ***************************************/
global.Promise = require('bluebird');
const TaskQueue = require('cwait').TaskQueue; const TaskQueue = require('cwait').TaskQueue;
const logger = require('./utils/logger'); const logger = require('./utils/logger');
const Timer = require('./utils/timer'); const Timer = require('./utils/timer');

View File

@@ -12,7 +12,6 @@
* message into the chat for affected parties. * message into the chat for affected parties.
***************************************/ ***************************************/
global.Promise = require('bluebird');
const uuid = require('uuid'); const uuid = require('uuid');
const TaskQueue = require('cwait').TaskQueue; const TaskQueue = require('cwait').TaskQueue;
const logger = require('./utils/logger'); const logger = require('./utils/logger');

View File

@@ -1,4 +1,6 @@
If you need to use a migration from this folder, move it to /migrations. If you need to use a migration from this folder, move it to /migrations.
Note that /migrations files (excluding /archive) are linted, so to pass test you'll have to make sure Note that /migrations files (excluding /archive) are linted, so to pass test you'll have to make sure
that the file is written correctly. that the file is written correctly.
They might also be using some old deps that we don't use anymore like Bluebird, mongoskin, ...

View File

@@ -1,5 +1,3 @@
import Bluebird from 'Bluebird';
import { model as Challenges } from '../../website/server/models/challenge'; import { model as Challenges } from '../../website/server/models/challenge';
import { model as User } from '../../website/server/models/user'; import { model as User } from '../../website/server/models/user';
@@ -17,10 +15,10 @@ async function syncChallengeToMembers (challenges) {
promises.push(user.save()); promises.push(user.save());
}); });
return Bluebird.all(promises); return Promise.all(promises);
}); });
return await Bluebird.all(challengSyncPromises); return await Promise.all(challengSyncPromises);
} }
async function syncChallenges (lastChallengeDate) { async function syncChallenges (lastChallengeDate) {

View File

@@ -1,5 +1,3 @@
import Bluebird from 'bluebird';
import { model as Group } from '../../website/server/models/group'; import { model as Group } from '../../website/server/models/group';
import { model as User } from '../../website/server/models/user'; import { model as User } from '../../website/server/models/user';
@@ -16,7 +14,7 @@ async function createGroup (name, privacy, type, leaderId) {
group.leader = user._id; group.leader = user._id;
user.guilds.push(group._id); user.guilds.push(group._id);
return Bluebird.all([group.save(), user.save()]); return Promise.all([group.save(), user.save()]);
} }
module.exports = async function groupCreator () { module.exports = async function groupCreator () {

View File

@@ -3,7 +3,6 @@
/* /*
* This migration will find users with unlimited subscriptions who are also eligible for Jackalope mounts, and award them * This migration will find users with unlimited subscriptions who are also eligible for Jackalope mounts, and award them
*/ */
import Bluebird from 'bluebird';
import { model as Group } from '../../website/server/models/group'; import { model as Group } from '../../website/server/models/group';
import { model as User } from '../../website/server/models/user'; import { model as User } from '../../website/server/models/user';
@@ -38,7 +37,7 @@ async function handOutJackalopes () {
cursor.on('close', async () => { cursor.on('close', async () => {
console.log('done'); console.log('done');
return await Bluebird.all(promises); return await Promise.all(promises);
}); });
} }

View File

@@ -9,8 +9,6 @@ let authorUuid = ''; // ... own data is done
* subscription to all members * subscription to all members
*/ */
import Bluebird from 'bluebird';
import { model as Group } from '../../website/server/models/group'; import { model as Group } from '../../website/server/models/group';
import * as payments from '../../website/server/libs/payments'; import * as payments from '../../website/server/libs/payments';
@@ -28,7 +26,7 @@ async function updateGroupsWithGroupPlans () {
}); });
cursor.on('close', async () => { cursor.on('close', async () => {
return await Bluebird.all(promises); return await Promise.all(promises);
}); });
} }

View File

@@ -1,14 +1,14 @@
require('babel-register'); require('babel-register');
require('babel-polyfill');
// This file must use ES5, everything required can be in ES6 // This file must use ES5, everything required can be in ES6
function setUpServer () { function setUpServer () {
const nconf = require('nconf'); // eslint-disable-line global-require, no-unused-vars const nconf = require('nconf'); // eslint-disable-line global-require, no-unused-vars
const mongoose = require('mongoose'); // eslint-disable-line global-require, no-unused-vars const mongoose = require('mongoose'); // eslint-disable-line global-require, no-unused-vars
const Bluebird = require('bluebird'); // eslint-disable-line global-require, no-unused-vars
const setupNconf = require('../website/server/libs/setupNconf'); // eslint-disable-line global-require const setupNconf = require('../website/server/libs/setupNconf'); // eslint-disable-line global-require
setupNconf(); setupNconf();
// We require src/server and npt src/index because // We require src/server and npt src/index because
// 1. nconf is already setup // 1. nconf is already setup
// 2. we don't need clustering // 2. we don't need clustering

View File

@@ -1,4 +1,3 @@
let Bluebird = require('bluebird');
let request = require('superagent'); let request = require('superagent');
let last = require('lodash/last'); let last = require('lodash/last');
let AWS = require('aws-sdk'); let AWS = require('aws-sdk');
@@ -74,7 +73,7 @@ function uploadToS3 (start, end, filesUrls) {
}); });
console.log(promises.length); console.log(promises.length);
return Bluebird.all(promises) return Promise.all(promises)
.then(() => { .then(() => {
currentIndex += 50; currentIndex += 50;
uploadToS3(currentIndex, currentIndex + 50, filesUrls); uploadToS3(currentIndex, currentIndex + 50, filesUrls);

1914
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -18,7 +18,7 @@
"babel-loader": "^7.1.4", "babel-loader": "^7.1.4",
"babel-plugin-syntax-async-functions": "^6.13.0", "babel-plugin-syntax-async-functions": "^6.13.0",
"babel-plugin-syntax-dynamic-import": "^6.18.0", "babel-plugin-syntax-dynamic-import": "^6.18.0",
"babel-plugin-transform-async-to-module-method": "^6.8.0", "babel-plugin-transform-es2015-modules-commonjs": "^6.26.0",
"babel-plugin-transform-object-rest-spread": "^6.16.0", "babel-plugin-transform-object-rest-spread": "^6.16.0",
"babel-plugin-transform-regenerator": "^6.16.1", "babel-plugin-transform-regenerator": "^6.16.1",
"babel-polyfill": "^6.6.1", "babel-polyfill": "^6.6.1",
@@ -26,7 +26,6 @@
"babel-register": "^6.6.0", "babel-register": "^6.6.0",
"babel-runtime": "^6.11.6", "babel-runtime": "^6.11.6",
"bcrypt": "^1.0.2", "bcrypt": "^1.0.2",
"bluebird": "^3.3.5",
"body-parser": "^1.15.0", "body-parser": "^1.15.0",
"bootstrap": "^4.0.0", "bootstrap": "^4.0.0",
"bootstrap-vue": "^2.0.0-rc.2", "bootstrap-vue": "^2.0.0-rc.2",
@@ -113,8 +112,8 @@
}, },
"private": true, "private": true,
"engines": { "engines": {
"node": "^6.9.1", "node": "^8.9.4",
"npm": "^5.0.0" "npm": "^5.6.0"
}, },
"scripts": { "scripts": {
"lint": "eslint --ext .js,.vue .", "lint": "eslint --ext .js,.vue .",
@@ -141,6 +140,7 @@
"apidoc": "gulp apidoc" "apidoc": "gulp apidoc"
}, },
"devDependencies": { "devDependencies": {
"babel-plugin-syntax-object-rest-spread": "^6.13.0",
"babel-plugin-istanbul": "^4.1.6", "babel-plugin-istanbul": "^4.1.6",
"chai": "^4.1.2", "chai": "^4.1.2",
"chai-as-promised": "^7.1.1", "chai-as-promised": "^7.1.1",

View File

@@ -1,5 +1,4 @@
require('babel-register'); require('babel-register');
require('babel-polyfill');
// This file is used for creating paypal billing plans. PayPal doesn't have a web interface for setting up recurring // This file is used for creating paypal billing plans. PayPal doesn't have a web interface for setting up recurring
// payment plan definitions, instead you have to create it via their REST SDK and keep it updated the same way. So this // payment plan definitions, instead you have to create it via their REST SDK and keep it updated the same way. So this

View File

@@ -2,9 +2,9 @@ import {
generateUser, generateUser,
} from '../../../../helpers/api-v3-integration.helper'; } from '../../../../helpers/api-v3-integration.helper';
import xml2js from 'xml2js'; import xml2js from 'xml2js';
import Bluebird from 'bluebird'; import util from 'util';
let parseStringAsync = Bluebird.promisify(xml2js.parseString, {context: xml2js}); let parseStringAsync = util.promisify(xml2js.parseString).bind(xml2js);
describe('GET /export/userdata.xml', () => { describe('GET /export/userdata.xml', () => {
// TODO disabled because it randomly causes the build to fail // TODO disabled because it randomly causes the build to fail

View File

@@ -2,8 +2,8 @@ import {
createAndPopulateGroup, createAndPopulateGroup,
translate as t, translate as t,
generateUser, generateUser,
sleep,
} from '../../../../helpers/api-v3-integration.helper'; } from '../../../../helpers/api-v3-integration.helper';
import Bluebird from 'bluebird';
describe('POST /groups/:groupId/quests/accept', () => { describe('POST /groups/:groupId/quests/accept', () => {
const PET_QUEST = 'whale'; const PET_QUEST = 'whale';
@@ -140,7 +140,7 @@ describe('POST /groups/:groupId/quests/accept', () => {
// quest will start after everyone has accepted // quest will start after everyone has accepted
await partyMembers[1].post(`/groups/${questingGroup._id}/quests/accept`); await partyMembers[1].post(`/groups/${questingGroup._id}/quests/accept`);
await Bluebird.delay(500); await sleep(0.5);
await rejectingMember.sync(); await rejectingMember.sync();

View File

@@ -2,8 +2,8 @@ import {
createAndPopulateGroup, createAndPopulateGroup,
translate as t, translate as t,
generateUser, generateUser,
sleep,
} from '../../../../helpers/api-v3-integration.helper'; } from '../../../../helpers/api-v3-integration.helper';
import Bluebird from 'bluebird';
describe('POST /groups/:groupId/quests/force-start', () => { describe('POST /groups/:groupId/quests/force-start', () => {
const PET_QUEST = 'whale'; const PET_QUEST = 'whale';
@@ -135,7 +135,7 @@ describe('POST /groups/:groupId/quests/force-start', () => {
await leader.post(`/groups/${questingGroup._id}/quests/force-start`); await leader.post(`/groups/${questingGroup._id}/quests/force-start`);
await Bluebird.delay(500); await sleep(0.5);
await Promise.all([ await Promise.all([
partyMemberThatRejects.sync(), partyMemberThatRejects.sync(),
@@ -161,7 +161,7 @@ describe('POST /groups/:groupId/quests/force-start', () => {
await leader.post(`/groups/${questingGroup._id}/quests/force-start`); await leader.post(`/groups/${questingGroup._id}/quests/force-start`);
await Bluebird.delay(500); await sleep(0.5);
await questingGroup.sync(); await questingGroup.sync();
@@ -184,7 +184,7 @@ describe('POST /groups/:groupId/quests/force-start', () => {
await leader.post(`/groups/${questingGroup._id}/quests/force-start`); await leader.post(`/groups/${questingGroup._id}/quests/force-start`);
await Bluebird.delay(500); await sleep(0.5);
await questingGroup.sync(); await questingGroup.sync();
@@ -201,7 +201,7 @@ describe('POST /groups/:groupId/quests/force-start', () => {
await leader.post(`/groups/${questingGroup._id}/quests/force-start`); await leader.post(`/groups/${questingGroup._id}/quests/force-start`);
await Bluebird.delay(500); await sleep(0.5);
await questingGroup.sync(); await questingGroup.sync();
@@ -222,7 +222,7 @@ describe('POST /groups/:groupId/quests/force-start', () => {
await leader.post(`/groups/${questingGroup._id}/quests/force-start`); await leader.post(`/groups/${questingGroup._id}/quests/force-start`);
await Bluebird.delay(500); await sleep(0.5);
await questingGroup.sync(); await questingGroup.sync();

View File

@@ -2,9 +2,9 @@ import {
createAndPopulateGroup, createAndPopulateGroup,
translate as t, translate as t,
generateUser, generateUser,
sleep,
} from '../../../../helpers/api-v3-integration.helper'; } from '../../../../helpers/api-v3-integration.helper';
import { v4 as generateUUID } from 'uuid'; import { v4 as generateUUID } from 'uuid';
import Bluebird from 'bluebird';
describe('POST /groups/:groupId/quests/reject', () => { describe('POST /groups/:groupId/quests/reject', () => {
let questingGroup; let questingGroup;
@@ -168,7 +168,7 @@ describe('POST /groups/:groupId/quests/reject', () => {
// quest will start after everyone has accepted or rejected // quest will start after everyone has accepted or rejected
await rejectingMember.post(`/groups/${questingGroup._id}/quests/reject`); await rejectingMember.post(`/groups/${questingGroup._id}/quests/reject`);
await Bluebird.delay(500); await sleep(0.5);
await questingGroup.sync(); await questingGroup.sync();

View File

@@ -2,7 +2,6 @@ import {
generateUser, generateUser,
translate as t, translate as t,
} from '../../../../helpers/api-integration/v3'; } from '../../../../helpers/api-integration/v3';
import Bluebird from 'bluebird';
describe('GET /shops/market', () => { describe('GET /shops/market', () => {
let user; let user;
@@ -42,13 +41,13 @@ describe('GET /shops/market', () => {
return array; return array;
}, []); }, []);
let results = await Bluebird.each(items, (item) => { let results = await Promise.all(items.map((item) => {
let { purchaseType, key } = item; let { purchaseType, key } = item;
return user.post(`/user/purchase/${purchaseType}/${key}`); return user.post(`/user/purchase/${purchaseType}/${key}`);
}); }));
expect(results.length).to.be.greaterThan(0); expect(results.length).to.be.greaterThan(0);
results.forEach((item) => { items.forEach((item) => {
expect(item).to.include.keys('key', 'text', 'notes', 'class', 'value', 'currency'); expect(item).to.include.keys('key', 'text', 'notes', 'class', 'value', 'currency');
}); });
}); });

View File

@@ -2,8 +2,8 @@ import {
generateUser, generateUser,
generateGroup, generateGroup,
generateChallenge, generateChallenge,
sleep,
} from '../../../../../helpers/api-integration/v3'; } from '../../../../../helpers/api-integration/v3';
import Bluebird from 'bluebird';
import { find } from 'lodash'; import { find } from 'lodash';
describe('POST /tasks/:id/score/:direction', () => { describe('POST /tasks/:id/score/:direction', () => {
@@ -27,7 +27,7 @@ describe('POST /tasks/:id/score/:direction', () => {
text: 'test habit', text: 'test habit',
type: 'habit', type: 'habit',
}); });
await Bluebird.delay(1000); await sleep(1);
let updatedUser = await user.get('/user'); let updatedUser = await user.get('/user');
usersChallengeTaskId = updatedUser.tasksOrder.habits[0]; usersChallengeTaskId = updatedUser.tasksOrder.habits[0];
}); });
@@ -65,7 +65,7 @@ describe('POST /tasks/:id/score/:direction', () => {
text: 'test daily', text: 'test daily',
type: 'daily', type: 'daily',
}); });
await Bluebird.delay(1000); await sleep(1);
let updatedUser = await user.get('/user'); let updatedUser = await user.get('/user');
usersChallengeTaskId = updatedUser.tasksOrder.dailys[0]; usersChallengeTaskId = updatedUser.tasksOrder.dailys[0];
}); });
@@ -109,7 +109,7 @@ describe('POST /tasks/:id/score/:direction', () => {
text: 'test todo', text: 'test todo',
type: 'todo', type: 'todo',
}); });
await Bluebird.delay(1000); await sleep(1);
let updatedUser = await user.get('/user'); let updatedUser = await user.get('/user');
usersChallengeTaskId = updatedUser.tasksOrder.todos[0]; usersChallengeTaskId = updatedUser.tasksOrder.todos[0];
}); });
@@ -134,7 +134,7 @@ describe('POST /tasks/:id/score/:direction', () => {
text: 'test reward', text: 'test reward',
type: 'reward', type: 'reward',
}); });
await Bluebird.delay(1000); await sleep(1);
let updatedUser = await user.get('/user'); let updatedUser = await user.get('/user');
usersChallengeTaskId = updatedUser.tasksOrder.todos[0]; usersChallengeTaskId = updatedUser.tasksOrder.todos[0];
}); });

View File

@@ -11,7 +11,6 @@ import {
each, each,
map, map,
} from 'lodash'; } from 'lodash';
import Bluebird from 'bluebird';
import { import {
sha1MakeSalt, sha1MakeSalt,
sha1Encrypt as sha1EncryptPassword, sha1Encrypt as sha1EncryptPassword,
@@ -104,7 +103,7 @@ describe('DELETE /user', () => {
password, password,
}); });
await Bluebird.all(map(ids, id => { await Promise.all(map(ids, id => {
return expect(checkExistence('tasks', id)).to.eventually.eql(false); return expect(checkExistence('tasks', id)).to.eventually.eql(false);
})); }));
}); });

View File

@@ -1,7 +1,6 @@
/* eslint-disable global-require */ /* eslint-disable global-require */
import moment from 'moment'; import moment from 'moment';
import nconf from 'nconf'; import nconf from 'nconf';
import Bluebird from 'bluebird';
import requireAgain from 'require-again'; import requireAgain from 'require-again';
import { recoverCron, cron } from '../../../../../website/server/libs/cron'; import { recoverCron, cron } from '../../../../../website/server/libs/cron';
import { model as User } from '../../../../../website/server/models/user'; import { model as User } from '../../../../../website/server/models/user';
@@ -1363,7 +1362,7 @@ describe('recoverCron', () => {
}); });
it('throws an error if user cannot be found', async () => { it('throws an error if user cannot be found', async () => {
execStub.returns(Bluebird.resolve(null)); execStub.returns(Promise.resolve(null));
try { try {
await recoverCron(status, locals); await recoverCron(status, locals);
@@ -1374,8 +1373,8 @@ describe('recoverCron', () => {
}); });
it('increases status.times count and reruns up to 4 times', async () => { it('increases status.times count and reruns up to 4 times', async () => {
execStub.returns(Bluebird.resolve({_cronSignature: 'RUNNING_CRON'})); execStub.returns(Promise.resolve({_cronSignature: 'RUNNING_CRON'}));
execStub.onCall(4).returns(Bluebird.resolve({_cronSignature: 'NOT_RUNNING'})); execStub.onCall(4).returns(Promise.resolve({_cronSignature: 'NOT_RUNNING'}));
await recoverCron(status, locals); await recoverCron(status, locals);
@@ -1384,7 +1383,7 @@ describe('recoverCron', () => {
}); });
it('throws an error if recoverCron runs 5 times', async () => { it('throws an error if recoverCron runs 5 times', async () => {
execStub.returns(Bluebird.resolve({_cronSignature: 'RUNNING_CRON'})); execStub.returns(Promise.resolve({_cronSignature: 'RUNNING_CRON'}));
try { try {
await recoverCron(status, locals); await recoverCron(status, locals);

View File

@@ -8,7 +8,6 @@ import {
attachTranslateFunction, attachTranslateFunction,
} from '../../../../../website/server/middlewares/language'; } from '../../../../../website/server/middlewares/language';
import common from '../../../../../website/common'; import common from '../../../../../website/common';
import Bluebird from 'bluebird';
import { model as User } from '../../../../../website/server/models/user'; import { model as User } from '../../../../../website/server/models/user';
const i18n = common.i18n; const i18n = common.i18n;
@@ -162,7 +161,7 @@ describe('language middleware', () => {
return this; return this;
}, },
exec () { exec () {
return Bluebird.resolve({ return Promise.resolve({
preferences: { preferences: {
language: 'it', language: 'it',
}, },

View File

@@ -1,4 +1,3 @@
import Bluebird from 'bluebird';
import moment from 'moment'; import moment from 'moment';
import { model as User } from '../../../../../website/server/models/user'; import { model as User } from '../../../../../website/server/models/user';
import { model as Group } from '../../../../../website/server/models/group'; import { model as Group } from '../../../../../website/server/models/group';
@@ -123,7 +122,7 @@ describe('User Model', () => {
it('adds notifications without data for all given users via static method', async () => { it('adds notifications without data for all given users via static method', async () => {
let user = new User(); let user = new User();
let otherUser = new User(); let otherUser = new User();
await Bluebird.all([user.save(), otherUser.save()]); await Promise.all([user.save(), otherUser.save()]);
await User.pushNotification({_id: {$in: [user._id, otherUser._id]}}, 'CRON'); await User.pushNotification({_id: {$in: [user._id, otherUser._id]}}, 'CRON');
@@ -149,7 +148,7 @@ describe('User Model', () => {
it('adds notifications with data and seen status for all given users via static method', async () => { it('adds notifications with data and seen status for all given users via static method', async () => {
let user = new User(); let user = new User();
let otherUser = new User(); let otherUser = new User();
await Bluebird.all([user.save(), otherUser.save()]); await Promise.all([user.save(), otherUser.save()]);
await User.pushNotification({_id: {$in: [user._id, otherUser._id]}}, 'CRON', {field: 1}, true); await User.pushNotification({_id: {$in: [user._id, otherUser._id]}}, 'CRON', {field: 1}, true);

View File

@@ -1,7 +1,6 @@
import { import {
times, times,
} from 'lodash'; } from 'lodash';
import Bluebird from 'bluebird';
import { v4 as generateUUID } from 'uuid'; import { v4 as generateUUID } from 'uuid';
import { ApiUser, ApiGroup, ApiChallenge } from '../api-classes'; import { ApiUser, ApiGroup, ApiChallenge } from '../api-classes';
import { requester } from '../requester'; import { requester } from '../requester';
@@ -106,7 +105,7 @@ export async function createAndPopulateGroup (settings = {}) {
guild: { guilds: [group._id] }, guild: { guilds: [group._id] },
}; };
let members = await Bluebird.all( let members = await Promise.all(
times(numberOfMembers, () => { times(numberOfMembers, () => {
return generateUser(groupMembershipTypes[group.type]); return generateUser(groupMembershipTypes[group.type]);
}) })
@@ -114,7 +113,7 @@ export async function createAndPopulateGroup (settings = {}) {
await group.update({ memberCount: numberOfMembers + 1}); await group.update({ memberCount: numberOfMembers + 1});
let invitees = await Bluebird.all( let invitees = await Promise.all(
times(numberOfInvites, () => { times(numberOfInvites, () => {
return generateUser(); return generateUser();
}) })
@@ -126,9 +125,9 @@ export async function createAndPopulateGroup (settings = {}) {
}); });
}); });
await Bluebird.all(invitationPromises); await Promise.all(invitationPromises);
await Bluebird.map(invitees, (invitee) => invitee.sync()); await Promise.all(invitees.map((invitee) => invitee.sync()));
return { return {
groupLeader, groupLeader,

View File

@@ -2,8 +2,6 @@
/* eslint-disable global-require */ /* eslint-disable global-require */
/* eslint-disable no-process-env */ /* eslint-disable no-process-env */
import Bluebird from 'bluebird';
//------------------------------ //------------------------------
// Global modules // Global modules
//------------------------------ //------------------------------
@@ -16,7 +14,6 @@ global.sinon = require('sinon');
let sinonStubPromise = require('sinon-stub-promise'); let sinonStubPromise = require('sinon-stub-promise');
sinonStubPromise(global.sinon); sinonStubPromise(global.sinon);
global.sandbox = sinon.sandbox.create(); global.sandbox = sinon.sandbox.create();
global.Promise = Bluebird;
import setupNconf from '../../website/server/libs/setupNconf'; import setupNconf from '../../website/server/libs/setupNconf';
setupNconf('./config.json.example'); setupNconf('./config.json.example');

View File

@@ -1,7 +1 @@
export async function sleep (seconds = 1) { export { default as sleep } from '../../website/server/libs/sleep';
let milliseconds = seconds * 1000;
return new Promise((resolve) => {
setTimeout(resolve, milliseconds);
});
}

View File

@@ -1,13 +1,11 @@
/* eslint-disable no-process-env */ /* eslint-disable no-process-env */
import nconf from 'nconf'; import nconf from 'nconf';
import mongoose from 'mongoose'; import mongoose from 'mongoose';
import Bluebird from 'bluebird';
import setupNconf from '../../website/server/libs/setupNconf'; import setupNconf from '../../website/server/libs/setupNconf';
if (process.env.LOAD_SERVER === '0') { // when the server is in a different process we simply connect to mongoose if (process.env.LOAD_SERVER === '0') { // when the server is in a different process we simply connect to mongoose
setupNconf('./config.json'); setupNconf('./config.json');
// Use Q promises instead of mpromise in mongoose // Use Q promises instead of mpromise in mongoose
mongoose.Promise = Bluebird;
mongoose.connect(nconf.get('TEST_DB_URI')); mongoose.connect(nconf.get('TEST_DB_URI'));
} else { // When running tests and the server in the same process } else { // When running tests and the server in the same process
setupNconf('./config.json.example'); setupNconf('./config.json.example');

View File

@@ -3,7 +3,6 @@
--timeout 8000 --timeout 8000
--check-leaks --check-leaks
--globals io --globals io
-r babel-polyfill
--require babel-register --require babel-register
--require ./test/helpers/globals.helper --require ./test/helpers/globals.helper
--exit --exit

View File

@@ -11,12 +11,12 @@ source /home/vagrant/.profile
echo Setting up node... echo Setting up node...
cd /vagrant cd /vagrant
nvm install nvm install 8
nvm use nvm use 8
nvm alias default current nvm alias default current
echo Update npm... echo Update npm...
npm install -g npm@4 npm install -g npm@5
echo Installing global modules... echo Installing global modules...
npm install -g gulp mocha node-pre-gyp npm install -g gulp mocha node-pre-gyp

View File

@@ -16,7 +16,6 @@ import {
NotAuthorized, NotAuthorized,
} from '../../libs/errors'; } from '../../libs/errors';
import * as Tasks from '../../models/task'; import * as Tasks from '../../models/task';
import Bluebird from 'bluebird';
import csvStringify from '../../libs/csvStringify'; import csvStringify from '../../libs/csvStringify';
import { import {
createTasks, createTasks,
@@ -254,7 +253,7 @@ api.joinChallenge = {
addUserJoinChallengeNotification(user); addUserJoinChallengeNotification(user);
// Add all challenge's tasks to user's tasks and save the challenge // Add all challenge's tasks to user's tasks and save the challenge
let results = await Bluebird.all([challenge.syncToUser(user), challenge.save()]); let results = await Promise.all([challenge.syncToUser(user), challenge.save()]);
let response = results[1].toJSON(); let response = results[1].toJSON();
response.group = getChallengeGroupResponse(group); response.group = getChallengeGroupResponse(group);
@@ -306,7 +305,7 @@ api.leaveChallenge = {
if (!challenge.isMember(user)) throw new NotAuthorized(res.t('challengeMemberNotFound')); if (!challenge.isMember(user)) throw new NotAuthorized(res.t('challengeMemberNotFound'));
// Unlink challenge's tasks from user's tasks and save the challenge // Unlink challenge's tasks from user's tasks and save the challenge
await Bluebird.all([challenge.unlinkTasks(user, keep), challenge.save()]); await Promise.all([challenge.unlinkTasks(user, keep), challenge.save()]);
res.analytics.track('challenge leave', { res.analytics.track('challenge leave', {
uuid: user._id, uuid: user._id,
@@ -364,8 +363,8 @@ api.getUserChallenges = {
let resChals = challenges.map(challenge => challenge.toJSON()); let resChals = challenges.map(challenge => challenge.toJSON());
// Instead of populate we make a find call manually because of https://github.com/Automattic/mongoose/issues/3833 // Instead of populate we make a find call manually because of https://github.com/Automattic/mongoose/issues/3833
await Bluebird.all(resChals.map((chal, index) => { await Promise.all(resChals.map((chal, index) => {
return Bluebird.all([ return Promise.all([
User.findById(chal.leader).select(nameFields).exec(), User.findById(chal.leader).select(nameFields).exec(),
Group.findById(chal.group).select(basicGroupFields).exec(), Group.findById(chal.group).select(basicGroupFields).exec(),
]).then(populatedData => { ]).then(populatedData => {
@@ -419,7 +418,7 @@ api.getGroupChallenges = {
let resChals = challenges.map(challenge => challenge.toJSON()); let resChals = challenges.map(challenge => challenge.toJSON());
// Instead of populate we make a find call manually because of https://github.com/Automattic/mongoose/issues/3833 // Instead of populate we make a find call manually because of https://github.com/Automattic/mongoose/issues/3833
await Bluebird.all(resChals.map((chal, index) => { await Promise.all(resChals.map((chal, index) => {
return User return User
.findById(chal.leader) .findById(chal.leader)
.select(nameFields) .select(nameFields)
@@ -511,7 +510,7 @@ api.exportChallengeCsv = {
// In v2 this used the aggregation framework to run some computation on MongoDB but then iterated through all // In v2 this used the aggregation framework to run some computation on MongoDB but then iterated through all
// results on the server so the perf difference isn't that big (hopefully) // results on the server so the perf difference isn't that big (hopefully)
let [members, tasks] = await Bluebird.all([ let [members, tasks] = await Promise.all([
User.find({challenges: challengeId}) User.find({challenges: challengeId})
.select(nameFields) .select(nameFields)
.sort({_id: 1}) .sort({_id: 1})

View File

@@ -14,7 +14,6 @@ import pusher from '../../libs/pusher';
import { getAuthorEmailFromMessage } from '../../libs/chat'; import { getAuthorEmailFromMessage } from '../../libs/chat';
import { chatReporterFactory } from '../../libs/chatReporting/chatReporterFactory'; import { chatReporterFactory } from '../../libs/chatReporting/chatReporterFactory';
import nconf from 'nconf'; import nconf from 'nconf';
import Bluebird from 'bluebird';
import bannedWords from '../../libs/bannedWords'; import bannedWords from '../../libs/bannedWords';
import guildsAllowingBannedWords from '../../libs/guildsAllowingBannedWords'; import guildsAllowingBannedWords from '../../libs/guildsAllowingBannedWords';
import { getMatchesByWordArray } from '../../libs/stringUtils'; import { getMatchesByWordArray } from '../../libs/stringUtils';
@@ -184,7 +183,7 @@ api.postChat = {
toSave.push(user.save()); toSave.push(user.save());
} }
let [savedGroup] = await Bluebird.all(toSave); let [savedGroup] = await Promise.all(toSave);
// realtime chat is only enabled for private groups (for now only for parties) // realtime chat is only enabled for private groups (for now only for parties)
if (savedGroup.privacy === 'private' && savedGroup.type === 'party') { if (savedGroup.privacy === 'private' && savedGroup.type === 'party') {

View File

@@ -1,17 +1,17 @@
import common from '../../../common'; import common from '../../../common';
import _ from 'lodash'; import _ from 'lodash';
import { langCodes } from '../../libs/i18n'; import { langCodes } from '../../libs/i18n';
import Bluebird from 'bluebird';
import fsCallback from 'fs'; import fsCallback from 'fs';
import path from 'path'; import path from 'path';
import logger from '../../libs/logger'; import logger from '../../libs/logger';
import util from 'util';
// Transform fs methods that accept callbacks in ones that return promises // Transform fs methods that accept callbacks in ones that return promises
const fs = { const fs = {
readFile: Bluebird.promisify(fsCallback.readFile, {context: fsCallback}), readFile: util.promisify(fsCallback.readFile).bind(fsCallback),
writeFile: Bluebird.promisify(fsCallback.writeFile, {context: fsCallback}), writeFile: util.promisify(fsCallback.writeFile).bind(fsCallback),
stat: Bluebird.promisify(fsCallback.stat, {context: fsCallback}), stat: util.promisify(fsCallback.stat).bind(fsCallback),
mkdir: Bluebird.promisify(fsCallback.mkdir, {context: fsCallback}), mkdir: util.promisify(fsCallback.mkdir).bind(fsCallback),
}; };
let api = {}; let api = {};

View File

@@ -1,5 +1,4 @@
import { authWithHeaders } from '../../middlewares/auth'; import { authWithHeaders } from '../../middlewares/auth';
import Bluebird from 'bluebird';
import _ from 'lodash'; import _ from 'lodash';
import nconf from 'nconf'; import nconf from 'nconf';
import { import {
@@ -137,7 +136,7 @@ api.createGroup = {
user.party._id = group._id; user.party._id = group._id;
} }
let results = await Bluebird.all([user.save(), group.save()]); let results = await Promise.all([user.save(), group.save()]);
let savedGroup = results[1]; let savedGroup = results[1];
// Instead of populate we make a find call manually because of https://github.com/Automattic/mongoose/issues/3833 // Instead of populate we make a find call manually because of https://github.com/Automattic/mongoose/issues/3833
@@ -194,7 +193,7 @@ api.createGroupPlan = {
group.leader = user._id; group.leader = user._id;
user.guilds.push(group._id); user.guilds.push(group._id);
let results = await Bluebird.all([user.save(), group.save()]); let results = await Promise.all([user.save(), group.save()]);
let savedGroup = results[1]; let savedGroup = results[1];
// Analytics // Analytics
@@ -617,7 +616,7 @@ api.joinGroup = {
} }
} }
promises = await Bluebird.all(promises); promises = await Promise.all(promises);
let response = Group.toJSONCleanChat(promises[0], user); let response = Group.toJSONCleanChat(promises[0], user);
let leader = await User.findById(response.leader).select(nameFields).exec(); let leader = await User.findById(response.leader).select(nameFields).exec();
@@ -915,7 +914,7 @@ api.removeGroupMember = {
let message = req.query.message || req.body.message; let message = req.query.message || req.body.message;
_sendMessageToRemoved(group, member, message, isInGroup); _sendMessageToRemoved(group, member, message, isInGroup);
await Bluebird.all([ await Promise.all([
member.save(), member.save(),
group.save(), group.save(),
]); ]);
@@ -1167,7 +1166,7 @@ api.inviteToGroup = {
if (uuids) { if (uuids) {
let uuidInvites = uuids.map((uuid) => _inviteByUUID(uuid, group, user, req, res)); let uuidInvites = uuids.map((uuid) => _inviteByUUID(uuid, group, user, req, res));
let uuidResults = await Bluebird.all(uuidInvites); let uuidResults = await Promise.all(uuidInvites);
results.push(...uuidResults); results.push(...uuidResults);
} }
@@ -1175,7 +1174,7 @@ api.inviteToGroup = {
let emailInvites = emails.map((invite) => _inviteByEmail(invite, group, user, req, res)); let emailInvites = emails.map((invite) => _inviteByEmail(invite, group, user, req, res));
user.invitesSent += emails.length; user.invitesSent += emails.length;
await user.save(); await user.save();
let emailResults = await Bluebird.all(emailInvites); let emailResults = await Promise.all(emailInvites);
results.push(...emailResults); results.push(...emailResults);
} }

View File

@@ -18,7 +18,6 @@ import {
getUserInfo, getUserInfo,
sendTxn as sendTxnEmail, sendTxn as sendTxnEmail,
} from '../../libs/email'; } from '../../libs/email';
import Bluebird from 'bluebird';
import { sendNotification as sendPushNotification } from '../../libs/pushNotifications'; import { sendNotification as sendPushNotification } from '../../libs/pushNotifications';
import { achievements } from '../../../../website/common/'; import { achievements } from '../../../../website/common/';
@@ -552,7 +551,7 @@ api.transferGems = {
receiver.balance += amount; receiver.balance += amount;
sender.balance -= amount; sender.balance -= amount;
let promises = [receiver.save(), sender.save()]; let promises = [receiver.save(), sender.save()];
await Bluebird.all(promises); await Promise.all(promises);
// generate the message in both languages, so both users can understand it // generate the message in both languages, so both users can understand it
let receiverLang = receiver.preferences.language; let receiverLang = receiver.preferences.language;

View File

@@ -1,5 +1,4 @@
import _ from 'lodash'; import _ from 'lodash';
import Bluebird from 'bluebird';
import { authWithHeaders } from '../../middlewares/auth'; import { authWithHeaders } from '../../middlewares/auth';
import analytics from '../../libs/analyticsService'; import analytics from '../../libs/analyticsService';
import { import {
@@ -109,7 +108,7 @@ api.inviteToQuest = {
await group.startQuest(user); await group.startQuest(user);
} }
let [savedGroup] = await Bluebird.all([ let [savedGroup] = await Promise.all([
group.save(), group.save(),
user.save(), user.save(),
]); ]);
@@ -312,7 +311,7 @@ api.forceStart = {
await group.startQuest(user); await group.startQuest(user);
let [savedGroup] = await Bluebird.all([ let [savedGroup] = await Promise.all([
group.save(), group.save(),
user.save(), user.save(),
]); ]);
@@ -372,7 +371,7 @@ api.cancelQuest = {
group.quest = Group.cleanGroupQuest(); group.quest = Group.cleanGroupQuest();
group.markModified('quest'); group.markModified('quest');
let [savedGroup] = await Bluebird.all([ let [savedGroup] = await Promise.all([
group.save(), group.save(),
User.update( User.update(
{'party._id': groupId}, {'party._id': groupId},
@@ -441,7 +440,7 @@ api.abortQuest = {
group.quest = Group.cleanGroupQuest(); group.quest = Group.cleanGroupQuest();
group.markModified('quest'); group.markModified('quest');
let [groupSaved] = await Bluebird.all([group.save(), memberUpdates, questLeaderUpdate]); let [groupSaved] = await Promise.all([group.save(), memberUpdates, questLeaderUpdate]);
res.respond(200, groupSaved.quest); res.respond(200, groupSaved.quest);
}, },
@@ -486,7 +485,7 @@ api.leaveQuest = {
user.party.quest = Group.cleanQuestProgress(); user.party.quest = Group.cleanQuestProgress();
user.markModified('party.quest'); user.markModified('party.quest');
let [savedGroup] = await Bluebird.all([ let [savedGroup] = await Promise.all([
group.save(), group.save(),
user.save(), user.save(),
]); ]);

View File

@@ -20,7 +20,6 @@ import {
setNextDue, setNextDue,
} from '../../libs/taskManager'; } from '../../libs/taskManager';
import common from '../../../common'; import common from '../../../common';
import Bluebird from 'bluebird';
import _ from 'lodash'; import _ from 'lodash';
import logger from '../../libs/logger'; import logger from '../../libs/logger';
import moment from 'moment'; import moment from 'moment';
@@ -598,7 +597,7 @@ api.scoreTask = {
}); });
managerPromises.push(task.save()); managerPromises.push(task.save());
await Bluebird.all(managerPromises); await Promise.all(managerPromises);
throw new NotAuthorized(res.t('taskApprovalHasBeenRequested')); throw new NotAuthorized(res.t('taskApprovalHasBeenRequested'));
} }
@@ -647,7 +646,7 @@ api.scoreTask = {
task.save(), task.save(),
]; ];
if (taskOrderPromise) promises.push(taskOrderPromise); if (taskOrderPromise) promises.push(taskOrderPromise);
let results = await Bluebird.all(promises); let results = await Promise.all(promises);
let savedUser = results[0]; let savedUser = results[0];
@@ -1132,7 +1131,7 @@ api.unlinkAllTasks = {
if (!validTasks) throw new BadRequest(res.t('cantOnlyUnlinkChalTask')); if (!validTasks) throw new BadRequest(res.t('cantOnlyUnlinkChalTask'));
if (keep === 'keep-all') { if (keep === 'keep-all') {
await Bluebird.all(tasks.map(task => { await Promise.all(tasks.map(task => {
task.challenge = {}; task.challenge = {};
return task.save(); return task.save();
})); }));
@@ -1149,7 +1148,7 @@ api.unlinkAllTasks = {
toSave.push(user.save()); toSave.push(user.save());
await Bluebird.all(toSave); await Promise.all(toSave);
} }
res.respond(200, {}); res.respond(200, {});
@@ -1199,7 +1198,7 @@ api.unlinkOneTask = {
} else { // remove } else { // remove
if (task.type !== 'todo' || !task.completed) { // eslint-disable-line no-lonely-if if (task.type !== 'todo' || !task.completed) { // eslint-disable-line no-lonely-if
removeFromArray(user.tasksOrder[`${task.type}s`], taskId); removeFromArray(user.tasksOrder[`${task.type}s`], taskId);
await Bluebird.all([user.save(), task.remove()]); await Promise.all([user.save(), task.remove()]);
} else { } else {
await task.remove(); await task.remove();
} }
@@ -1317,7 +1316,7 @@ api.deleteTask = {
// See https://github.com/HabitRPG/habitica/pull/9321#issuecomment-354187666 for more info // See https://github.com/HabitRPG/habitica/pull/9321#issuecomment-354187666 for more info
if (!challenge) user._v++; if (!challenge) user._v++;
await Bluebird.all([taskOrderUpdate, task.remove()]); await Promise.all([taskOrderUpdate, task.remove()]);
} else { } else {
await task.remove(); await task.remove();
} }

View File

@@ -1,5 +1,4 @@
import { authWithHeaders } from '../../../middlewares/auth'; import { authWithHeaders } from '../../../middlewares/auth';
import Bluebird from 'bluebird';
import * as Tasks from '../../../models/task'; import * as Tasks from '../../../models/task';
import { model as Group } from '../../../models/group'; import { model as Group } from '../../../models/group';
import { model as User } from '../../../models/user'; import { model as User } from '../../../models/user';
@@ -205,7 +204,7 @@ api.assignTask = {
let promises = []; let promises = [];
promises.push(group.syncTask(task, assignedUser)); promises.push(group.syncTask(task, assignedUser));
promises.push(group.save()); promises.push(group.save());
await Bluebird.all(promises); await Promise.all(promises);
res.respond(200, task); res.respond(200, task);
}, },
@@ -350,7 +349,7 @@ api.approveTask = {
managerPromises.push(task.save()); managerPromises.push(task.save());
managerPromises.push(assignedUser.save()); managerPromises.push(assignedUser.save());
await Bluebird.all(managerPromises); await Promise.all(managerPromises);
res.respond(200, task); res.respond(200, task);
}, },

View File

@@ -9,7 +9,6 @@ import {
model as Group, model as Group,
} from '../../models/group'; } from '../../models/group';
import * as Tasks from '../../models/task'; import * as Tasks from '../../models/task';
import Bluebird from 'bluebird';
import _ from 'lodash'; import _ from 'lodash';
import * as passwordUtils from '../../libs/password'; import * as passwordUtils from '../../libs/password';
import { import {
@@ -415,7 +414,7 @@ api.deleteUser = {
return group.leave(user, 'remove-all'); return group.leave(user, 'remove-all');
}); });
await Bluebird.all(groupLeavePromises); await Promise.all(groupLeavePromises);
await Tasks.Task.remove({ await Tasks.Task.remove({
userId: user._id, userId: user._id,
@@ -1470,7 +1469,7 @@ api.userRebirth = {
toSave.push(user.save()); toSave.push(user.save());
await Bluebird.all(toSave); await Promise.all(toSave);
res.respond(200, ...rebirthRes); res.respond(200, ...rebirthRes);
}, },
@@ -1627,7 +1626,7 @@ api.userReroll = {
let promises = tasks.map(task => task.save()); let promises = tasks.map(task => task.save());
promises.push(user.save()); promises.push(user.save());
await Bluebird.all(promises); await Promise.all(promises);
res.respond(200, ...rerollRes); res.respond(200, ...rerollRes);
}, },
@@ -1668,7 +1667,7 @@ api.userReset = {
let resetRes = common.ops.reset(user, tasks); let resetRes = common.ops.reset(user, tasks);
await Bluebird.all([ await Promise.all([
Tasks.Task.remove({_id: {$in: resetRes[0].tasksToRemove}, userId: user._id}), Tasks.Task.remove({_id: {$in: resetRes[0].tasksToRemove}, userId: user._id}),
user.save(), user.save(),
]); ]);

View File

@@ -11,7 +11,6 @@ import js2xml from 'js2xmlparser';
import Pageres from 'pageres'; import Pageres from 'pageres';
import nconf from 'nconf'; import nconf from 'nconf';
import got from 'got'; import got from 'got';
import Bluebird from 'bluebird';
import md from 'habitica-markdown'; import md from 'habitica-markdown';
import { import {
S3, S3,
@@ -244,7 +243,7 @@ api.exportUserAvatarPng = {
Body: stream, Body: stream,
}); });
let s3res = await new Bluebird((resolve, reject) => { let s3res = await new Promise((resolve, reject) => {
s3upload.send((err, s3uploadRes) => { s3upload.send((err, s3uploadRes) => {
if (err) { if (err) {
reject(err); reject(err);

View File

@@ -7,12 +7,6 @@ if (process.env.NODE_ENV !== 'production') {
require('babel-register'); require('babel-register');
} }
// The BabelJS polyfill is needed in production too
require('babel-polyfill');
// Setup Bluebird as the global promise library
global.Promise = require('bluebird');
// Initialize configuration BEFORE anything // Initialize configuration BEFORE anything
const setupNconf = require('./libs/setupNconf'); const setupNconf = require('./libs/setupNconf');
setupNconf(); setupNconf();

View File

@@ -1,9 +1,9 @@
import amazonPayments from 'amazon-payments'; import amazonPayments from 'amazon-payments';
import nconf from 'nconf'; import nconf from 'nconf';
import Bluebird from 'bluebird';
import moment from 'moment'; import moment from 'moment';
import cc from 'coupon-code'; import cc from 'coupon-code';
import uuid from 'uuid'; import uuid from 'uuid';
import util from 'util';
import common from '../../common'; import common from '../../common';
import { import {
@@ -51,15 +51,15 @@ api.constants = {
PAYMENT_METHOD_GIFT: 'Amazon Payments (Gift)', PAYMENT_METHOD_GIFT: 'Amazon Payments (Gift)',
}; };
api.getTokenInfo = Bluebird.promisify(amzPayment.api.getTokenInfo, {context: amzPayment.api}); api.getTokenInfo = util.promisify(amzPayment.api.getTokenInfo).bind(amzPayment.api);
api.createOrderReferenceId = Bluebird.promisify(amzPayment.offAmazonPayments.createOrderReferenceForId, {context: amzPayment.offAmazonPayments}); api.createOrderReferenceId = util.promisify(amzPayment.offAmazonPayments.createOrderReferenceForId).bind(amzPayment.offAmazonPayments);
api.setOrderReferenceDetails = Bluebird.promisify(amzPayment.offAmazonPayments.setOrderReferenceDetails, {context: amzPayment.offAmazonPayments}); api.setOrderReferenceDetails = util.promisify(amzPayment.offAmazonPayments.setOrderReferenceDetails).bind(amzPayment.offAmazonPayments);
api.confirmOrderReference = Bluebird.promisify(amzPayment.offAmazonPayments.confirmOrderReference, {context: amzPayment.offAmazonPayments}); api.confirmOrderReference = util.promisify(amzPayment.offAmazonPayments.confirmOrderReference).bind(amzPayment.offAmazonPayments);
api.closeOrderReference = Bluebird.promisify(amzPayment.offAmazonPayments.closeOrderReference, {context: amzPayment.offAmazonPayments}); api.closeOrderReference = util.promisify(amzPayment.offAmazonPayments.closeOrderReference).bind(amzPayment.offAmazonPayments);
api.setBillingAgreementDetails = Bluebird.promisify(amzPayment.offAmazonPayments.setBillingAgreementDetails, {context: amzPayment.offAmazonPayments}); api.setBillingAgreementDetails = util.promisify(amzPayment.offAmazonPayments.setBillingAgreementDetails).bind(amzPayment.offAmazonPayments);
api.getBillingAgreementDetails = Bluebird.promisify(amzPayment.offAmazonPayments.getBillingAgreementDetails, {context: amzPayment.offAmazonPayments}); api.getBillingAgreementDetails = util.promisify(amzPayment.offAmazonPayments.getBillingAgreementDetails).bind(amzPayment.offAmazonPayments);
api.confirmBillingAgreement = Bluebird.promisify(amzPayment.offAmazonPayments.confirmBillingAgreement, {context: amzPayment.offAmazonPayments}); api.confirmBillingAgreement = util.promisify(amzPayment.offAmazonPayments.confirmBillingAgreement).bind(amzPayment.offAmazonPayments);
api.closeBillingAgreement = Bluebird.promisify(amzPayment.offAmazonPayments.closeBillingAgreement, {context: amzPayment.offAmazonPayments}); api.closeBillingAgreement = util.promisify(amzPayment.offAmazonPayments.closeBillingAgreement).bind(amzPayment.offAmazonPayments);
api.authorizeOnBillingAgreement = function authorizeOnBillingAgreement (inputSet) { api.authorizeOnBillingAgreement = function authorizeOnBillingAgreement (inputSet) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {

View File

@@ -1,7 +1,6 @@
/* eslint-disable camelcase */ /* eslint-disable camelcase */
import nconf from 'nconf'; import nconf from 'nconf';
import Amplitude from 'amplitude'; import Amplitude from 'amplitude';
import Bluebird from 'bluebird';
import googleAnalytics from 'universal-analytics'; import googleAnalytics from 'universal-analytics';
import useragent from 'useragent'; import useragent from 'useragent';
import { import {
@@ -171,7 +170,7 @@ let _sendDataToAmplitude = (eventType, data) => {
amplitudeData.event_type = eventType; amplitudeData.event_type = eventType;
return new Bluebird((resolve, reject) => { return new Promise((resolve, reject) => {
amplitude.track(amplitudeData) amplitude.track(amplitudeData)
.then(resolve) .then(resolve)
.catch(() => reject('Error while sending data to Amplitude.')); .catch(() => reject('Error while sending data to Amplitude.'));
@@ -222,7 +221,7 @@ let _sendDataToGoogle = (eventType, data) => {
eventData.ev = value; eventData.ev = value;
} }
return new Bluebird((resolve, reject) => { return new Promise((resolve, reject) => {
ga.event(eventData, (err) => { ga.event(eventData, (err) => {
if (err) return reject(err); if (err) return reject(err);
resolve(); resolve();
@@ -236,7 +235,7 @@ let _sendPurchaseDataToAmplitude = (data) => {
amplitudeData.event_type = 'purchase'; amplitudeData.event_type = 'purchase';
amplitudeData.revenue = data.purchaseValue; amplitudeData.revenue = data.purchaseValue;
return new Bluebird((resolve, reject) => { return new Promise((resolve, reject) => {
amplitude.track(amplitudeData) amplitude.track(amplitudeData)
.then(resolve) .then(resolve)
.catch(reject); .catch(reject);
@@ -261,7 +260,7 @@ let _sendPurchaseDataToGoogle = (data) => {
ev: price, ev: price,
}; };
return new Bluebird((resolve) => { return new Promise((resolve) => {
ga.event(eventData).send(); ga.event(eventData).send();
ga.transaction(data.uuid, price) ga.transaction(data.uuid, price)
@@ -273,14 +272,14 @@ let _sendPurchaseDataToGoogle = (data) => {
}; };
function track (eventType, data) { function track (eventType, data) {
return Bluebird.all([ return Promise.all([
_sendDataToAmplitude(eventType, data), _sendDataToAmplitude(eventType, data),
_sendDataToGoogle(eventType, data), _sendDataToGoogle(eventType, data),
]); ]);
} }
function trackPurchase (data) { function trackPurchase (data) {
return Bluebird.all([ return Promise.all([
_sendPurchaseDataToAmplitude(data), _sendPurchaseDataToAmplitude(data),
_sendPurchaseDataToGoogle(data), _sendPurchaseDataToGoogle(data),
]); ]);

View File

@@ -1,7 +1,6 @@
// Currently this holds helpers for challenge api, but we should break this up into submodules as it expands // Currently this holds helpers for challenge api, but we should break this up into submodules as it expands
import omit from 'lodash/omit'; import omit from 'lodash/omit';
import uuid from 'uuid'; import uuid from 'uuid';
import Bluebird from 'bluebird';
import { model as Challenge } from '../../models/challenge'; import { model as Challenge } from '../../models/challenge';
import { import {
model as Group, model as Group,
@@ -82,7 +81,7 @@ export async function createChallenge (user, req, res) {
addUserJoinChallengeNotification(user); addUserJoinChallengeNotification(user);
let results = await Bluebird.all([challenge.save({ let results = await Promise.all([challenge.save({
validateBeforeSave: false, // already validate validateBeforeSave: false, // already validate
}), group.save()]); }), group.save()]);
let savedChal = results[0]; let savedChal = results[0];

View File

@@ -1,8 +1,8 @@
import moment from 'moment'; import moment from 'moment';
import Bluebird from 'bluebird';
import { model as User } from '../models/user'; import { model as User } from '../models/user';
import common from '../../common/'; import common from '../../common/';
import { preenUserHistory } from '../libs/preening'; import { preenUserHistory } from '../libs/preening';
import sleep from '../libs/sleep';
import _ from 'lodash'; import _ from 'lodash';
import cloneDeep from 'lodash/cloneDeep'; import cloneDeep from 'lodash/cloneDeep';
import nconf from 'nconf'; import nconf from 'nconf';
@@ -29,7 +29,7 @@ function setIsDueNextDue (task, user, now) {
export async function recoverCron (status, locals) { export async function recoverCron (status, locals) {
let {user} = locals; let {user} = locals;
await Bluebird.delay(300); await sleep(0.3);
let reloadedUser = await User.findOne({_id: user._id}).exec(); let reloadedUser = await User.findOne({_id: user._id}).exec();

View File

@@ -1,8 +1,7 @@
import csvStringify from 'csv-stringify'; import csvStringify from 'csv-stringify';
import Bluebird from 'bluebird';
module.exports = (input) => { module.exports = (input) => {
return new Bluebird((resolve, reject) => { return new Promise((resolve, reject) => {
csvStringify(input, (err, output) => { csvStringify(input, (err, output) => {
if (err) return reject(err); if (err) return reject(err);
return resolve(output); return resolve(output);

View File

@@ -1,6 +1,6 @@
import nconf from 'nconf'; import nconf from 'nconf';
import util from 'util';
import iap from 'in-app-purchase'; import iap from 'in-app-purchase';
import Bluebird from 'bluebird';
// Validation ERROR Codes // Validation ERROR Codes
// const INVALID_PAYLOAD = 6778001; // const INVALID_PAYLOAD = 6778001;
@@ -18,8 +18,8 @@ iap.config({
}); });
module.exports = { module.exports = {
setup: Bluebird.promisify(iap.setup, { context: iap }), setup: util.promisify(iap.setup.bind(iap)),
validate: Bluebird.promisify(iap.validate, { context: iap }), validate: util.promisify(iap.validate.bind(iap)),
isValidated: iap.isValidated, isValidated: iap.isValidated,
getPurchaseData: iap.getPurchaseData, getPurchaseData: iap.getPurchaseData,
GOOGLE: iap.GOOGLE, GOOGLE: iap.GOOGLE,

View File

@@ -1,13 +1,13 @@
/* eslint-disable camelcase */ /* eslint-disable camelcase */
import nconf from 'nconf'; import nconf from 'nconf';
import moment from 'moment'; import moment from 'moment';
import util from 'util';
import _ from 'lodash'; import _ from 'lodash';
import payments from './payments'; import payments from './payments';
import ipn from 'paypal-ipn'; import ipn from 'paypal-ipn';
import paypal from 'paypal-rest-sdk'; import paypal from 'paypal-rest-sdk';
import shared from '../../common'; import shared from '../../common';
import cc from 'coupon-code'; import cc from 'coupon-code';
import Bluebird from 'bluebird';
import { model as Coupon } from '../models/coupon'; import { model as Coupon } from '../models/coupon';
import { model as User } from '../models/user'; import { model as User } from '../models/user';
import { import {
@@ -60,14 +60,14 @@ api.constants = {
// PAYMENT_METHOD_GIFT: 'Amazon Payments (Gift)', // PAYMENT_METHOD_GIFT: 'Amazon Payments (Gift)',
}; };
api.paypalPaymentCreate = Bluebird.promisify(paypal.payment.create, {context: paypal.payment}); api.paypalPaymentCreate = util.promisify(paypal.payment.create.bind(paypal.payment));
api.paypalPaymentExecute = Bluebird.promisify(paypal.payment.execute, {context: paypal.payment}); api.paypalPaymentExecute = util.promisify(paypal.payment.execute.bind(paypal.payment));
api.paypalBillingAgreementCreate = Bluebird.promisify(paypal.billingAgreement.create, {context: paypal.billingAgreement}); api.paypalBillingAgreementCreate = util.promisify(paypal.billingAgreement.create.bind(paypal.billingAgreement));
api.paypalBillingAgreementExecute = Bluebird.promisify(paypal.billingAgreement.execute, {context: paypal.billingAgreement}); api.paypalBillingAgreementExecute = util.promisify(paypal.billingAgreement.execute.bind(paypal.billingAgreement));
api.paypalBillingAgreementGet = Bluebird.promisify(paypal.billingAgreement.get, {context: paypal.billingAgreement}); api.paypalBillingAgreementGet = util.promisify(paypal.billingAgreement.get.bind(paypal.billingAgreement));
api.paypalBillingAgreementCancel = Bluebird.promisify(paypal.billingAgreement.cancel, {context: paypal.billingAgreement}); api.paypalBillingAgreementCancel = util.promisify(paypal.billingAgreement.cancel.bind(paypal.billingAgreement));
api.ipnVerifyAsync = Bluebird.promisify(ipn.verify, {context: ipn}); api.ipnVerifyAsync = util.promisify(ipn.verify.bind(ipn));
api.checkout = async function checkout (options = {}) { api.checkout = async function checkout (options = {}) {
let {gift, user} = options; let {gift, user} = options;

View File

@@ -3,7 +3,6 @@ import nconf from 'nconf';
// @TODO remove this lib and use directly the apn module // @TODO remove this lib and use directly the apn module
import pushNotify from 'push-notify'; import pushNotify from 'push-notify';
import logger from './logger'; import logger from './logger';
import Bluebird from 'bluebird';
import { import {
S3, S3,
} from './aws'; } from './aws';
@@ -20,7 +19,7 @@ const APN_ENABLED = nconf.get('PUSH_CONFIGS:APN_ENABLED') === 'true';
const S3_BUCKET = nconf.get('S3:bucket'); const S3_BUCKET = nconf.get('S3:bucket');
if (APN_ENABLED) { if (APN_ENABLED) {
Bluebird.all([ Promise.all([
S3.getObject({ S3.getObject({
Bucket: S3_BUCKET, Bucket: S3_BUCKET,
Key: 'apple_apn/cert.pem', Key: 'apple_apn/cert.pem',

View File

@@ -0,0 +1,7 @@
export default async function (seconds = 1) {
let milliseconds = seconds * 1000;
return new Promise((resolve) => {
setTimeout(resolve, milliseconds);
});
}

View File

@@ -1,5 +1,3 @@
import Bluebird from 'bluebird';
import { model as User } from '../models/user'; import { model as User } from '../models/user';
import * as Tasks from '../models/task'; import * as Tasks from '../models/task';
import { import {
@@ -24,7 +22,7 @@ async function castTaskSpell (res, req, targetId, user, spell, quantity = 1) {
spell.cast(user, task, req); spell.cast(user, task, req);
} }
const results = await Bluebird.all([ const results = await Promise.all([
user.save(), user.save(),
task.save(), task.save(),
]); ]);
@@ -46,7 +44,7 @@ async function castMultiTaskSpell (req, user, spell, quantity = 1) {
.filter(t => t.isModified()) .filter(t => t.isModified())
.map(t => t.save()); .map(t => t.save());
toSave.unshift(user.save()); toSave.unshift(user.save());
const saved = await Bluebird.all(toSave); const saved = await Promise.all(toSave);
const response = { const response = {
tasks: saved, tasks: saved,
@@ -82,7 +80,7 @@ async function castPartySpell (req, party, partyMembers, user, spell, quantity =
for (let i = 0; i < quantity; i += 1) { for (let i = 0; i < quantity; i += 1) {
spell.cast(user, partyMembers, req); spell.cast(user, partyMembers, req);
} }
await Bluebird.all(partyMembers.map(m => m.save())); await Promise.all(partyMembers.map(m => m.save()));
return partyMembers; return partyMembers;
} }
@@ -107,7 +105,7 @@ async function castUserSpell (res, req, party, partyMembers, targetId, user, spe
} }
if (partyMembers !== user) { if (partyMembers !== user) {
await Bluebird.all([ await Promise.all([
user.save(), user.save(),
partyMembers.save(), partyMembers.save(),
]); ]);

View File

@@ -3,7 +3,6 @@ import * as Tasks from '../models/task';
import { import {
BadRequest, BadRequest,
} from './errors'; } from './errors';
import Bluebird from 'bluebird';
import _ from 'lodash'; import _ from 'lodash';
import shared from '../../common'; import shared from '../../common';
@@ -18,9 +17,9 @@ async function _validateTaskAlias (tasks, res) {
throw new BadRequest(res.t('taskAliasAlreadyUsed')); throw new BadRequest(res.t('taskAliasAlreadyUsed'));
} }
await Bluebird.map(tasksWithAliases, (task) => { await Promise.all(tasksWithAliases.map((task) => {
return task.validate(); return task.validate();
}); }));
} }
export function setNextDue (task, user, dueDateOption) { export function setNextDue (task, user, dueDateOption) {
@@ -137,7 +136,7 @@ export async function createTasks (req, res, options = {}) {
toSave.unshift(owner.save()); toSave.unshift(owner.save());
let tasks = await Bluebird.all(toSave); let tasks = await Promise.all(toSave);
tasks.splice(0, 1); // Remove user, challenge, or group promise tasks.splice(0, 1); // Remove user, challenge, or group promise
return tasks; return tasks;
} }

View File

@@ -1,6 +1,5 @@
import moment from 'moment'; import moment from 'moment';
import * as Tasks from '../models/task'; import * as Tasks from '../models/task';
import Bluebird from 'bluebird';
import { model as Group } from '../models/group'; import { model as Group } from '../models/group';
import { model as User } from '../models/user'; import { model as User } from '../models/user';
import { recoverCron, cron } from '../libs/cron'; import { recoverCron, cron } from '../libs/cron';
@@ -99,7 +98,7 @@ async function cronAsync (req, res) {
tasks.forEach(task => { tasks.forEach(task => {
if (task.isModified()) toSave.push(task.save()); if (task.isModified()) toSave.push(task.save());
}); });
await Bluebird.all(toSave); await Promise.all(toSave);
await Group.processQuestProgress(user, progress); await Group.processQuestProgress(user, progress);

View File

@@ -1,5 +1,4 @@
import mongoose from 'mongoose'; import mongoose from 'mongoose';
import Bluebird from 'bluebird';
import validator from 'validator'; import validator from 'validator';
import baseModel from '../libs/baseModel'; import baseModel from '../libs/baseModel';
import _ from 'lodash'; import _ from 'lodash';
@@ -120,7 +119,7 @@ schema.methods.syncToUser = async function syncChallengeToUser (user) {
}); });
} }
let [challengeTasks, userTasks] = await Bluebird.all([ let [challengeTasks, userTasks] = await Promise.all([
// Find original challenge tasks // Find original challenge tasks
Tasks.Task.find({ Tasks.Task.find({
userId: {$exists: false}, userId: {$exists: false},
@@ -165,7 +164,7 @@ schema.methods.syncToUser = async function syncChallengeToUser (user) {
}); });
toSave.push(user.save()); toSave.push(user.save());
return Bluebird.all(toSave); return Promise.all(toSave);
}; };
async function _fetchMembersIds (challengeId) { async function _fetchMembersIds (challengeId) {
@@ -202,7 +201,7 @@ async function _addTaskFn (challenge, tasks, memberId) {
// Update the user // Update the user
toSave.unshift(User.update({_id: memberId}, updateTasksOrderQ).exec()); toSave.unshift(User.update({_id: memberId}, updateTasksOrderQ).exec());
return await Bluebird.all(toSave); return await Promise.all(toSave);
} }
// Add a new task to challenge members // Add a new task to challenge members
@@ -210,11 +209,11 @@ schema.methods.addTasks = async function challengeAddTasks (tasks) {
let challenge = this; let challenge = this;
let membersIds = await _fetchMembersIds(challenge._id); let membersIds = await _fetchMembersIds(challenge._id);
let queue = new TaskQueue(Bluebird, 25); // process only 5 users concurrently let queue = new TaskQueue(Promise, 25); // process only 5 users concurrently
await Bluebird.map(membersIds, queue.wrap((memberId) => { await Promise.all(membersIds.map(queue.wrap((memberId) => {
return _addTaskFn(challenge, tasks, memberId); return _addTaskFn(challenge, tasks, memberId);
})); })));
}; };
// Sync updated task to challenge members // Sync updated task to challenge members
@@ -267,7 +266,7 @@ schema.methods.unlinkTasks = async function challengeUnlinkTasks (user, keep) {
$set: {challenge: {}}, $set: {challenge: {}},
}, {multi: true}).exec(); }, {multi: true}).exec();
return Bluebird.all([user.save(), this.save()]); return Promise.all([user.save(), this.save()]);
} else { // keep = 'remove-all' } else { // keep = 'remove-all'
let tasks = await Tasks.Task.find(findQuery).select('_id type completed').exec(); let tasks = await Tasks.Task.find(findQuery).select('_id type completed').exec();
let taskPromises = tasks.map(task => { let taskPromises = tasks.map(task => {
@@ -280,7 +279,7 @@ schema.methods.unlinkTasks = async function challengeUnlinkTasks (user, keep) {
}); });
user.markModified('tasksOrder'); user.markModified('tasksOrder');
taskPromises.push(user.save(), this.save()); taskPromises.push(user.save(), this.save());
return Bluebird.all(taskPromises); return Promise.all(taskPromises);
} }
}; };
@@ -358,7 +357,7 @@ schema.methods.closeChal = async function closeChal (broken = {}) {
}, {multi: true}).exec(), }, {multi: true}).exec(),
]; ];
Bluebird.all(backgroundTasks); Promise.all(backgroundTasks);
}; };
export let model = mongoose.model('Challenge', schema); export let model = mongoose.model('Challenge', schema);

View File

@@ -19,7 +19,6 @@ import {
} from '../libs/errors'; } from '../libs/errors';
import baseModel from '../libs/baseModel'; import baseModel from '../libs/baseModel';
import { sendTxn as sendTxnEmail } from '../libs/email'; import { sendTxn as sendTxnEmail } from '../libs/email';
import Bluebird from 'bluebird';
import nconf from 'nconf'; import nconf from 'nconf';
import { sendNotification as sendPushNotification } from '../libs/pushNotifications'; import { sendNotification as sendPushNotification } from '../libs/pushNotifications';
import pusher from '../libs/pusher'; import pusher from '../libs/pusher';
@@ -308,7 +307,7 @@ schema.statics.getGroups = async function getGroups (options = {}) {
} }
}); });
let groupsArray = _.reduce(await Bluebird.all(queries), (previousValue, currentValue) => { let groupsArray = _.reduce(await Promise.all(queries), (previousValue, currentValue) => {
if (_.isEmpty(currentValue)) return previousValue; // don't add anything to the results if the query returned null or an empty array if (_.isEmpty(currentValue)) return previousValue; // don't add anything to the results if the query returned null or an empty array
return previousValue.concat(Array.isArray(currentValue) ? currentValue : [currentValue]); // otherwise concat the new results to the previousValue return previousValue.concat(Array.isArray(currentValue) ? currentValue : [currentValue]); // otherwise concat the new results to the previousValue
}, []); }, []);
@@ -427,7 +426,7 @@ schema.methods.removeGroupInvitations = async function removeGroupInvitations ()
return user.save(); return user.save();
}); });
return Bluebird.all(userUpdates); return Promise.all(userUpdates);
}; };
// Return true if user is a member of the group // Return true if user is a member of the group
@@ -628,13 +627,18 @@ schema.methods.startQuest = async function startQuest (user) {
// remove any users from quest.members who aren't in the party // remove any users from quest.members who aren't in the party
let partyId = this._id; let partyId = this._id;
let questMembers = this.quest.members; let questMembers = this.quest.members;
await Bluebird.map(Object.keys(this.quest.members), async (memberId) => { await Promise.all(Object.keys(this.quest.members).map(memberId => {
let member = await User.findOne({_id: memberId, 'party._id': partyId}).select('_id').lean().exec(); return User.findOne({_id: memberId, 'party._id': partyId})
.select('_id')
if (!member) { .lean()
delete questMembers[memberId]; .exec()
} .then((member) => {
}); if (!member) {
delete questMembers[memberId];
}
return;
});
}));
if (userIsParticipating) { if (userIsParticipating) {
user.party.quest.key = this.quest.key; user.party.quest.key = this.quest.key;
@@ -871,7 +875,7 @@ schema.methods.finishQuest = async function finishQuest (quest) {
})); }));
} }
return Bluebird.all(promises); return Promise.all(promises);
}; };
function _isOnQuest (user, progress, group) { function _isOnQuest (user, progress, group) {
@@ -1123,7 +1127,7 @@ schema.methods.leave = async function leaveGroup (user, keep = 'keep-all', keepC
let challengesToRemoveUserFrom = challenges.map(chal => { let challengesToRemoveUserFrom = challenges.map(chal => {
return chal.unlinkTasks(user, keep); return chal.unlinkTasks(user, keep);
}); });
await Bluebird.all(challengesToRemoveUserFrom); await Promise.all(challengesToRemoveUserFrom);
} }
// Unlink group tasks) // Unlink group tasks)
@@ -1135,7 +1139,7 @@ schema.methods.leave = async function leaveGroup (user, keep = 'keep-all', keepC
let assignedTasksToRemoveUserFrom = assignedTasks.map(task => { let assignedTasksToRemoveUserFrom = assignedTasks.map(task => {
return this.unlinkTask(task, user, keep); return this.unlinkTask(task, user, keep);
}); });
await Bluebird.all(assignedTasksToRemoveUserFrom); await Promise.all(assignedTasksToRemoveUserFrom);
let promises = []; let promises = [];
@@ -1171,7 +1175,7 @@ schema.methods.leave = async function leaveGroup (user, keep = 'keep-all', keepC
if (members.length === 0) { if (members.length === 0) {
promises.push(group.remove()); promises.push(group.remove());
return await Bluebird.all(promises); return await Promise.all(promises);
} }
} else if (group.leader === user._id) { // otherwise If the leader is leaving (or if the leader previously left, and this wasn't accounted for) } else if (group.leader === user._id) { // otherwise If the leader is leaving (or if the leader previously left, and this wasn't accounted for)
let query = group.type === 'party' ? {'party._id': group._id} : {guilds: group._id}; let query = group.type === 'party' ? {'party._id': group._id} : {guilds: group._id};
@@ -1193,7 +1197,7 @@ schema.methods.leave = async function leaveGroup (user, keep = 'keep-all', keepC
} }
promises.push(group.update(update).exec()); promises.push(group.update(update).exec());
return await Bluebird.all(promises); return await Promise.all(promises);
}; };
/** /**
@@ -1327,7 +1331,7 @@ schema.methods.syncTask = async function groupSyncTask (taskToSync, user) {
if (matchingTask.tags.indexOf(group._id) === -1) matchingTask.tags.push(group._id); // add tag if missing if (matchingTask.tags.indexOf(group._id) === -1) matchingTask.tags.push(group._id); // add tag if missing
toSave.push(matchingTask.save(), taskToSync.save(), user.save()); toSave.push(matchingTask.save(), taskToSync.save(), user.save());
return Bluebird.all(toSave); return Promise.all(toSave);
}; };
schema.methods.unlinkTask = async function groupUnlinkTask (unlinkingTask, user, keep) { schema.methods.unlinkTask = async function groupUnlinkTask (unlinkingTask, user, keep) {
@@ -1353,7 +1357,7 @@ schema.methods.unlinkTask = async function groupUnlinkTask (unlinkingTask, user,
user.markModified('tasksOrder'); user.markModified('tasksOrder');
} }
return Bluebird.all([task.remove(), user.save(), unlinkingTask.save()]); return Promise.all([task.remove(), user.save(), unlinkingTask.save()]);
} }
}; };

View File

@@ -1,7 +1,6 @@
import common from '../../../common'; import common from '../../../common';
import _ from 'lodash'; import _ from 'lodash';
import moment from 'moment'; import moment from 'moment';
import Bluebird from 'bluebird';
import baseModel from '../../libs/baseModel'; import baseModel from '../../libs/baseModel';
import * as Tasks from '../task'; import * as Tasks from '../task';
import { import {
@@ -58,7 +57,7 @@ function _populateDefaultTasks (user, taskTypes) {
// @TODO: default tasks are handled differently now, and not during registration. We should move this code // @TODO: default tasks are handled differently now, and not during registration. We should move this code
let tasksToCreate = []; let tasksToCreate = [];
if (user.registeredThrough === 'habitica-web') return Bluebird.all(tasksToCreate); if (user.registeredThrough === 'habitica-web') return Promise.all(tasksToCreate);
if (tagsI !== -1) { if (tagsI !== -1) {
taskTypes = _.clone(taskTypes); taskTypes = _.clone(taskTypes);
@@ -89,7 +88,7 @@ function _populateDefaultTasks (user, taskTypes) {
tasksToCreate.push(...tasksOfType); tasksToCreate.push(...tasksOfType);
}); });
return Bluebird.all(tasksToCreate) return Promise.all(tasksToCreate)
.then((tasksCreated) => { .then((tasksCreated) => {
_.each(tasksCreated, (task) => { _.each(tasksCreated, (task) => {
user.tasksOrder[`${task.type}s`].push(task._id); user.tasksOrder[`${task.type}s`].push(task._id);

View File

@@ -1,7 +1,6 @@
import moment from 'moment'; import moment from 'moment';
import common from '../../../common'; import common from '../../../common';
import Bluebird from 'bluebird';
import { import {
chatDefaults, chatDefaults,
TAVERN_ID, TAVERN_ID,
@@ -132,7 +131,7 @@ schema.methods.sendMessage = async function sendMessage (userToReceiveMessage, o
sender.markModified('inbox.messages'); sender.markModified('inbox.messages');
let promises = [userToReceiveMessage.save(), sender.save()]; let promises = [userToReceiveMessage.save(), sender.save()];
await Bluebird.all(promises); await Promise.all(promises);
}; };
/** /**

View File

@@ -2,9 +2,6 @@ import nconf from 'nconf';
import logger from './libs/logger'; import logger from './libs/logger';
import express from 'express'; import express from 'express';
import http from 'http'; import http from 'http';
import Bluebird from 'bluebird';
global.Promise = Bluebird;
const server = http.createServer(); const server = http.createServer();
const app = express(); const app = express();