@chevre/domain
Version:
Chevre Domain Library for Node.js
236 lines (235 loc) • 10.7 kB
JavaScript
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.TripRepo = void 0;
const factory = require("../factory");
const trip_1 = require("./mongoose/schemas/trip");
const settings_1 = require("../settings");
/**
* トリップリポジトリ
*/
class TripRepo {
constructor(connection) {
this.tripModel = connection.model(trip_1.modelName, (0, trip_1.createSchema)());
}
// tslint:disable-next-line:cyclomatic-complexity max-func-body-length
static CREATE_MONGO_CONDITIONS(conditions) {
var _a, _b, _c, _d, _e, _f;
const andConditions = [{ typeOf: { $eq: conditions.typeOf } }];
const projectIdEq = (_b = (_a = conditions.project) === null || _a === void 0 ? void 0 : _a.id) === null || _b === void 0 ? void 0 : _b.$eq;
if (typeof projectIdEq === 'string') {
andConditions.push({ 'project.id': { $eq: projectIdEq } });
}
const idIn = (_c = conditions.id) === null || _c === void 0 ? void 0 : _c.$in;
if (Array.isArray(idIn)) {
andConditions.push({ _id: { $in: idIn } });
}
const identifierEq = (_d = conditions.identifier) === null || _d === void 0 ? void 0 : _d.$eq;
if (typeof identifierEq === 'string') {
andConditions.push({ identifier: { $eq: identifierEq } });
}
const nameRegex = (_e = conditions.name) === null || _e === void 0 ? void 0 : _e.$regex;
if (typeof nameRegex === 'string' && nameRegex.length > 0) {
andConditions.push({
$or: [
{
'name.ja': {
$exists: true,
$regex: new RegExp(nameRegex)
}
},
{
'name.en': {
$exists: true,
$regex: new RegExp(nameRegex)
}
}
]
});
}
const additionalPropertyElemMatch = (_f = conditions.additionalProperty) === null || _f === void 0 ? void 0 : _f.$elemMatch;
if (additionalPropertyElemMatch !== undefined && additionalPropertyElemMatch !== null) {
andConditions.push({
additionalProperty: {
$exists: true,
$elemMatch: additionalPropertyElemMatch
}
});
}
return andConditions;
}
createMany(params) {
return __awaiter(this, void 0, void 0, function* () {
const docs = yield this.tripModel.insertMany(params.map((p) => {
return Object.assign({}, p);
}));
return docs.map((doc) => doc.toObject());
});
}
updatePartiallyById(params) {
return __awaiter(this, void 0, void 0, function* () {
let doc;
const _a = params.attributes, { typeOf } = _a, updateFields = __rest(_a, ["typeOf"]);
doc = yield this.tripModel.findOneAndUpdate({
_id: params.id,
typeOf: params.attributes.typeOf
}, {
$set: updateFields
}, { upsert: false, new: true })
.exec();
if (doc === null) {
throw new factory.errors.NotFound(this.tripModel.modelName);
}
return doc.toObject();
});
}
/**
* イベントを保管する
*/
save(params) {
return __awaiter(this, void 0, void 0, function* () {
let doc;
if (typeof params.id !== 'string') {
doc = yield this.tripModel.create(Object.assign({}, params.attributes));
}
else {
const upsert = params.upsert === true;
// 上書き禁止属性を除外
const _a = params.attributes, { identifier, project, typeOf } = _a, updateFields = __rest(_a, ["identifier", "project", "typeOf"]);
doc = yield this.tripModel.findOneAndUpdate({
_id: params.id,
typeOf: params.attributes.typeOf
}, Object.assign({ $setOnInsert: {
typeOf: params.attributes.typeOf,
project: params.attributes.project,
identifier: params.attributes.identifier
}, $set: updateFields }, (params.$unset !== undefined) ? { $unset: params.$unset } : undefined), { upsert, new: true })
.exec();
}
if (doc === null) {
throw new factory.errors.NotFound(this.tripModel.modelName);
}
return doc.toObject();
});
}
saveMany(params) {
return __awaiter(this, void 0, void 0, function* () {
const bulkWriteOps = [];
if (Array.isArray(params)) {
params.forEach((p) => {
if (typeof p.id !== 'string') {
bulkWriteOps.push({
insertOne: {
document: Object.assign({}, p.attributes)
}
});
}
else {
const upsert = p.upsert === true;
if (p.attributes.typeOf === factory.tripType.BusTrip) {
// 上書き禁止属性を除外
const _a = p.attributes, { identifier, project, typeOf } = _a, updateFields = __rest(_a, ["identifier", "project", "typeOf"]);
bulkWriteOps.push({
updateOne: {
filter: {
_id: p.id,
typeOf: p.attributes.typeOf
},
// upsertの場合、createがありうるので属性を除外しない
update: Object.assign({ $setOnInsert: {
typeOf: p.attributes.typeOf,
project: p.attributes.project,
identifier: p.attributes.identifier
}, $set: updateFields }, (p.$unset !== undefined) ? { $unset: p.$unset } : undefined),
upsert
}
});
}
}
});
}
if (bulkWriteOps.length > 0) {
yield this.tripModel.bulkWrite(bulkWriteOps, { ordered: false });
}
});
}
search(params, projection) {
return __awaiter(this, void 0, void 0, function* () {
const conditions = TripRepo.CREATE_MONGO_CONDITIONS(params);
const query = this.tripModel.find({ $and: conditions }, Object.assign({ __v: 0, createdAt: 0, updatedAt: 0 }, projection));
if (typeof params.limit === 'number' && params.limit > 0) {
const page = (typeof params.page === 'number' && params.page > 0) ? params.page : 1;
query.limit(params.limit)
.skip(params.limit * (page - 1));
}
// tslint:disable-next-line:no-single-line-block-comment
/* istanbul ignore else */
if (params.sort !== undefined) {
query.sort(params.sort);
}
// const explainResult = await query.explain()
// .exec();
// console.log(explainResult[0].executionStats.allPlansExecution.map((e: any) => e.executionStages.inputStage));
// console.log(explainResult[0].executionStats.allPlansExecution);
// console.log(explainResult[0].queryPlanner?.winningPlan);
// console.log(explainResult[0].queryPlanner?.winningPlan?.inputStage?.inputStage?.inputStage);
// console.log(explainResult);
// return [];
return query.setOptions({ maxTimeMS: settings_1.MONGO_MAX_TIME_MS })
.exec()
.then((docs) => docs.map((doc) => doc.toObject()));
});
}
findById(params, projection) {
return __awaiter(this, void 0, void 0, function* () {
const doc = yield this.tripModel.findOne({
_id: params.id
}, Object.assign({ __v: 0, createdAt: 0, updatedAt: 0 }, projection))
.exec();
if (doc === null) {
throw new factory.errors.NotFound(this.tripModel.modelName);
}
return doc.toObject();
});
}
deleteById(params) {
return __awaiter(this, void 0, void 0, function* () {
yield this.tripModel.findOneAndDelete({ _id: params.id })
.exec();
});
}
deleteByProject(params) {
return __awaiter(this, void 0, void 0, function* () {
yield this.tripModel.deleteMany({
'project.id': { $eq: params.project.id }
})
.exec();
});
}
unsetUnnecessaryFields(params) {
return __awaiter(this, void 0, void 0, function* () {
return this.tripModel.updateMany(params.filter, { $unset: params.$unset }, { timestamps: false })
.exec();
});
}
}
exports.TripRepo = TripRepo;
;