Skip to content

Commit e881850

Browse files
refactor: migrate project to async/await syntax (#580)
1 parent 0539758 commit e881850

29 files changed

+1019
-763
lines changed

src/adapters/mongoose.js

Lines changed: 14 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
const P = require('bluebird');
21
const _ = require('lodash');
32
const Interface = require('forest-express');
43
const utils = require('../utils/schema');
@@ -23,7 +22,7 @@ function unflatten(data) {
2322
}
2423
/* eslint-enable */
2524

26-
module.exports = (model, opts) => {
25+
module.exports = async (model, opts) => {
2726
const fields = [];
2827
const paths = unflatten(model.schema.paths);
2928
const { Mongoose } = opts;
@@ -299,17 +298,17 @@ module.exports = (model, opts) => {
299298
return schema;
300299
}
301300

302-
return P
303-
.each(Object.keys(paths), (path) => {
304-
if (path === '__v') { return; }
305-
const field = getFieldSchema(path);
306-
fields.push(field);
307-
})
308-
.then(() => ({
309-
name: utils.getModelName(model),
310-
// TODO: Remove nameOld attribute once the lianas versions older than 2.0.0 are minority.
311-
nameOld: model.collection.name.replace(' ', ''),
312-
idField: '_id',
313-
fields,
314-
}));
301+
Object.keys(paths).forEach(async (path) => {
302+
if (path === '__v') { return; }
303+
const field = getFieldSchema(path);
304+
fields.push(field);
305+
});
306+
307+
return {
308+
name: utils.getModelName(model),
309+
// TODO: Remove nameOld attribute once the lianas versions older than 2.0.0 are minority.
310+
nameOld: model.collection.name.replace(' ', ''),
311+
idField: '_id',
312+
fields,
313+
};
315314
};

src/services/belongs-to-updater.js

Lines changed: 12 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,18 @@
1-
const P = require('bluebird');
21

32
function BelongsToUpdater(model, association, opts, params, data) {
4-
this.perform = () =>
5-
new P(((resolve, reject) => {
6-
const updateParams = {};
7-
updateParams[params.associationName] = data.data ? data.data.id : null;
3+
this.perform = async () => {
4+
const updateParams = {};
5+
updateParams[params.associationName] = data.data ? data.data.id : null;
86

9-
model
10-
.findByIdAndUpdate(params.recordId, {
11-
$set: updateParams,
12-
}, {
13-
new: true,
14-
})
15-
.lean()
16-
.exec((err, record) => {
17-
if (err) { return reject(err); }
18-
return resolve(record);
19-
});
20-
}));
7+
return model
8+
.findByIdAndUpdate(params.recordId, {
9+
$set: updateParams,
10+
}, {
11+
new: true,
12+
})
13+
.lean()
14+
.exec();
15+
};
2116
}
2217

2318
module.exports = BelongsToUpdater;

src/services/filters-parser.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -230,8 +230,8 @@ function FiltersParser(model, timezone, options) {
230230
};
231231
const query = await subModelFilterParser.perform(JSON.stringify(newCondition));
232232
const [, referencedKey] = field.reference.split('.');
233-
const subModelIds = await subModel.find(query)
234-
.then((records) => records.map((record) => record[referencedKey]));
233+
const subModelRecords = await subModel.find(query);
234+
const subModelIds = subModelRecords.map((record) => record[referencedKey]);
235235

236236
const resultCondition = {
237237
field: fieldName,
Lines changed: 14 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,20 @@
1-
const P = require('bluebird');
21

32
function HasManyAssociator(model, association, opts, params, data) {
4-
this.perform = () =>
5-
new P(((resolve, reject) => {
6-
const updateParams = {};
7-
updateParams[params.associationName] = {
8-
$each: data.data.map((document) => document.id),
9-
};
3+
this.perform = () => {
4+
const updateParams = {};
5+
updateParams[params.associationName] = {
6+
$each: data.data.map((document) => document.id),
7+
};
108

11-
model
12-
.findByIdAndUpdate(params.recordId, {
13-
$push: updateParams,
14-
}, {
15-
new: true,
16-
})
17-
.lean()
18-
.exec((err, record) => {
19-
if (err) { return reject(err); }
20-
return resolve(record);
21-
});
22-
}));
9+
return model
10+
.findByIdAndUpdate(params.recordId, {
11+
$push: updateParams,
12+
}, {
13+
new: true,
14+
})
15+
.lean()
16+
.exec();
17+
};
2318
}
2419

2520
module.exports = HasManyAssociator;
Lines changed: 16 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,25 @@
1-
const P = require('bluebird');
21

32
function HasManyDissociator(model, association, opts, params, data) {
43
const isDelete = Boolean(params.delete);
54

6-
this.perform = () =>
7-
new P(((resolve, reject) => {
8-
const documentIds = data.data.map((document) => document.id);
5+
this.perform = async () => {
6+
const documentIds = data.data.map((document) => document.id);
7+
if (isDelete) {
8+
await association.deleteMany({ _id: { $in: documentIds } });
9+
}
910

10-
if (isDelete) {
11-
association.deleteMany({
12-
_id: { $in: documentIds },
13-
}, (error) => {
14-
if (error) { return reject(error); }
15-
return resolve();
16-
});
17-
}
18-
const updateParams = {};
19-
updateParams[params.associationName] = { $in: documentIds };
11+
const updateParams = {};
12+
updateParams[params.associationName] = { $in: documentIds };
2013

21-
model
22-
.findByIdAndUpdate(params.recordId, {
23-
$pull: updateParams,
24-
}, {
25-
new: true,
26-
})
27-
.lean()
28-
.exec((error, record) => {
29-
if (error) { return reject(error); }
30-
return resolve(record);
31-
});
32-
}));
14+
return model
15+
.findByIdAndUpdate(params.recordId, {
16+
$pull: updateParams,
17+
}, {
18+
new: true,
19+
})
20+
.lean()
21+
.exec();
22+
};
3323
}
3424

3525
module.exports = HasManyDissociator;

src/services/has-many-getter.js

Lines changed: 60 additions & 67 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,14 @@
11
const _ = require('lodash');
2-
const P = require('bluebird');
32
const Interface = require('forest-express');
43
const SearchBuilder = require('./search-builder');
54
const utils = require('../utils/schema');
65
const FiltersParser = require('./filters-parser');
76

8-
function HasManyGetter(model, association, opts, params) {
7+
function HasManyGetter(parentModel, childModel, opts, params) {
98
const OBJECTID_REGEXP = /^[0-9a-fA-F]{24}$/;
10-
const schema = Interface.Schemas.schemas[utils.getModelName(association)];
11-
const searchBuilder = new SearchBuilder(association, opts, params);
12-
const filtersParser = new FiltersParser(association, params.timezone, opts);
9+
const schema = Interface.Schemas.schemas[utils.getModelName(childModel)];
10+
const searchBuilder = new SearchBuilder(childModel, opts, params);
11+
const filtersParser = new FiltersParser(childModel, params.timezone, opts);
1312

1413
function hasPagination() {
1514
return params.page && params.page.number;
@@ -66,71 +65,65 @@ function HasManyGetter(model, association, opts, params) {
6665
return conditions;
6766
}
6867

69-
function getRecordsAndRecordIds() {
70-
return new P((resolve, reject) => {
71-
let id = params.recordId;
72-
if (OBJECTID_REGEXP.test(params.recordId)) {
73-
id = opts.Mongoose.Types.ObjectId(id);
74-
}
68+
async function getRecordsAndRecordIds() {
69+
let id = params.recordId;
70+
if (OBJECTID_REGEXP.test(params.recordId)) {
71+
id = opts.Mongoose.Types.ObjectId(id);
72+
}
7573

76-
return model
77-
.aggregate()
78-
.match({ _id: id })
79-
.unwind(params.associationName)
80-
.project(getProjection())
81-
.exec((error, records) => {
82-
if (error) { return reject(error); }
83-
return resolve(_.map(records, (record) => record[params.associationName]));
84-
});
85-
})
86-
.then(async (recordIds) => {
87-
const conditions = await buildConditions(recordIds);
88-
const query = association.find(conditions);
89-
handlePopulate(query);
90-
91-
return query.then((records) => [records, recordIds]);
92-
});
74+
const parentRecords = await parentModel
75+
.aggregate()
76+
.match({ _id: id })
77+
.unwind(params.associationName)
78+
.project(getProjection())
79+
.exec();
80+
81+
const childRecordIds = _.map(parentRecords, (record) => record[params.associationName]);
82+
const conditions = await buildConditions(childRecordIds);
83+
const query = childModel.find(conditions);
84+
handlePopulate(query);
85+
86+
const childRecords = await query;
87+
return [childRecords, childRecordIds];
9388
}
9489

95-
this.perform = () =>
96-
getRecordsAndRecordIds()
97-
.then((recordsAndRecordIds) => {
98-
const records = recordsAndRecordIds[0];
99-
let fieldSort = params.sort;
100-
let descending = false;
101-
102-
if (params.sort && (params.sort[0] === '-')) {
103-
fieldSort = params.sort.substring(1);
104-
descending = true;
105-
}
106-
107-
let recordsSorted;
108-
if (fieldSort) {
109-
recordsSorted = _.sortBy(records, (record) => record[fieldSort]);
110-
} else {
111-
const recordIds = recordsAndRecordIds[1];
112-
// NOTICE: Convert values to strings, so ObjectIds could be easily searched and compared.
113-
const recordIdStrings = recordIds.map((recordId) => String(recordId));
114-
// NOTICE: indexOf could be improved by making a Map from record-ids to their index.
115-
recordsSorted = _.sortBy(records, record => recordIdStrings.indexOf(String(record._id))); // eslint-disable-line
116-
}
117-
return descending ? recordsSorted.reverse() : recordsSorted;
118-
})
119-
.then((records) => {
120-
let fieldsSearched = null;
121-
122-
if (params.search) {
123-
fieldsSearched = searchBuilder.getFieldsSearched();
124-
}
125-
126-
records = _.slice(records, getSkip(), getSkip() + getLimit());
127-
128-
return [records, fieldsSearched];
129-
});
130-
131-
this.count = () =>
132-
getRecordsAndRecordIds()
133-
.then((recordsAndRecordIds) => recordsAndRecordIds[0].length);
90+
this.perform = async () => {
91+
const [childRecords, childRecordIds] = await getRecordsAndRecordIds();
92+
93+
let fieldSort = params.sort;
94+
let descending = false;
95+
96+
if (params.sort && (params.sort[0] === '-')) {
97+
fieldSort = params.sort.substring(1);
98+
descending = true;
99+
}
100+
101+
let recordsSorted;
102+
if (fieldSort) {
103+
recordsSorted = _.sortBy(childRecords, (record) => record[fieldSort]);
104+
} else {
105+
// NOTICE: Convert values to strings, so ObjectIds could be easily searched and compared.
106+
const recordIdStrings = childRecordIds.map((recordId) => String(recordId));
107+
// NOTICE: indexOf could be improved by making a Map from record-ids to their index.
108+
recordsSorted = _.sortBy(childRecords, record => recordIdStrings.indexOf(String(record._id))); // eslint-disable-line
109+
}
110+
111+
let sortedChildRecords = descending ? recordsSorted.reverse() : recordsSorted;
112+
let fieldsSearched = null;
113+
114+
if (params.search) {
115+
fieldsSearched = searchBuilder.getFieldsSearched();
116+
}
117+
118+
sortedChildRecords = _.slice(sortedChildRecords, getSkip(), getSkip() + getLimit());
119+
120+
return [sortedChildRecords, fieldsSearched];
121+
};
122+
123+
this.count = async () => {
124+
const recordsAndRecordIds = await getRecordsAndRecordIds();
125+
return recordsAndRecordIds[0].length;
126+
};
134127
}
135128

136129
module.exports = HasManyGetter;

0 commit comments

Comments
 (0)