@chevre/domain
Version:
Chevre Domain Library for Node.js
334 lines (333 loc) • 15 kB
JavaScript
"use strict";
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.CategoryCodeRepo = void 0;
const mongoose_1 = require("mongoose");
const categoryCode_1 = require("./mongoose/schemas/categoryCode");
const factory = require("../factory");
const settings_1 = require("../settings");
const AVAILABLE_PROJECT_FIELDS = [
'additionalProperty', 'codeValue', 'color', 'image', 'inCodeSet', 'name', 'paymentMethod', 'project', 'typeOf'
];
/**
* 区分リポジトリ
*/
class CategoryCodeRepo {
constructor(connection) {
this.categoryCodeModel = connection.model(categoryCode_1.modelName, (0, categoryCode_1.createSchema)());
}
// tslint:disable-next-line:cyclomatic-complexity max-func-body-length
static CREATE_MONGO_CONDITIONS(params) {
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
const andConditions = [];
// tslint:disable-next-line:no-single-line-block-comment
/* istanbul ignore else */
if (params.project !== undefined && params.project !== null) {
if (params.project.id !== undefined && params.project.id !== null) {
if (typeof params.project.id.$eq === 'string') {
andConditions.push({
'project.id': {
$eq: params.project.id.$eq
}
});
}
}
}
const idEq = (_a = params.id) === null || _a === void 0 ? void 0 : _a.$eq;
if (typeof idEq === 'string') {
// andConditions.push({ _id: { $eq: idEq } });
andConditions.push({ _id: { $eq: new mongoose_1.Types.ObjectId(idEq) } });
}
const idIn = (_b = params.id) === null || _b === void 0 ? void 0 : _b.$in;
if (Array.isArray(idIn)) {
// andConditions.push({ _id: { $in: idIn } });
andConditions.push({ _id: { $in: idIn.map((id) => new mongoose_1.Types.ObjectId(id)) } });
}
// tslint:disable-next-line:no-single-line-block-comment
/* istanbul ignore else */
if (params.name !== undefined && params.name !== null) {
if (typeof params.name.$regex === 'string' && params.name.$regex.length > 0) {
andConditions.push({
$or: [
{
'name.ja': {
$exists: true,
$regex: new RegExp(params.name.$regex)
}
},
{
'name.en': {
$exists: true,
$regex: new RegExp(params.name.$regex)
}
}
]
});
}
}
const codeValueEq = (_c = params.codeValue) === null || _c === void 0 ? void 0 : _c.$eq;
if (typeof codeValueEq === 'string') {
andConditions.push({ codeValue: { $eq: codeValueEq } });
}
const codeValueIn = (_d = params.codeValue) === null || _d === void 0 ? void 0 : _d.$in;
if (Array.isArray(codeValueIn)) {
andConditions.push({ codeValue: { $in: codeValueIn } });
}
// tslint:disable-next-line:no-single-line-block-comment
/* istanbul ignore else */
if (params.inCodeSet !== undefined && params.inCodeSet !== null) {
if (params.inCodeSet.identifier !== undefined && params.inCodeSet.identifier !== null) {
if (typeof params.inCodeSet.identifier.$eq === 'string') {
andConditions.push({
'inCodeSet.identifier': {
$exists: true,
$eq: params.inCodeSet.identifier.$eq
}
});
}
}
}
const inCodeSetIdentifierIn = (_f = (_e = params.inCodeSet) === null || _e === void 0 ? void 0 : _e.identifier) === null || _f === void 0 ? void 0 : _f.$in;
if (Array.isArray(inCodeSetIdentifierIn)) {
andConditions.push({
'inCodeSet.identifier': {
$exists: true,
$in: inCodeSetIdentifierIn
}
});
}
const paymentMethodTypeOfEq = (_h = (_g = params.paymentMethod) === null || _g === void 0 ? void 0 : _g.typeOf) === null || _h === void 0 ? void 0 : _h.$eq;
if (typeof paymentMethodTypeOfEq === 'string') {
andConditions.push({
'paymentMethod.typeOf': {
$exists: true,
$eq: paymentMethodTypeOfEq
}
});
}
const paymentMethodTypeOfIn = (_k = (_j = params.paymentMethod) === null || _j === void 0 ? void 0 : _j.typeOf) === null || _k === void 0 ? void 0 : _k.$in;
if (Array.isArray(paymentMethodTypeOfIn)) {
andConditions.push({
'paymentMethod.typeOf': {
$exists: true,
$in: paymentMethodTypeOfIn
}
});
}
const additionalPropertyElemMatch = (_l = params.additionalProperty) === null || _l === void 0 ? void 0 : _l.$elemMatch;
if (additionalPropertyElemMatch !== undefined && additionalPropertyElemMatch !== null) {
andConditions.push({
additionalProperty: {
$exists: true,
$elemMatch: additionalPropertyElemMatch
}
});
}
return andConditions;
}
static CREATE_AGGREGATE_PROJECTION(inclusion) {
let projectStage = {
_id: 0,
id: { $toString: '$_id' },
project: '$project',
typeOf: '$typeOf',
additionalProperty: '$additionalProperty',
color: '$color',
image: '$image',
codeValue: '$codeValue',
inCodeSet: '$inCodeSet',
name: '$name',
paymentMethod: '$paymentMethod'
};
if (inclusion.length > 0) {
projectStage = { _id: 0 };
inclusion.forEach((field) => {
switch (field) {
// case '_id':
case 'id':
projectStage.id = { $toString: '$_id' };
break;
default:
projectStage[field] = `$${field}`;
}
});
}
return projectStage;
}
/**
* 集計検索(publicな属性検索が目的)
*/
searchByAggregate(conditions, inclusion) {
return __awaiter(this, void 0, void 0, function* () {
var _a;
const matchStages = CategoryCodeRepo.CREATE_MONGO_CONDITIONS(conditions)
.map((c) => ({ $match: c }));
const projectStage = CategoryCodeRepo.CREATE_AGGREGATE_PROJECTION(inclusion);
const sortByCodeValue = (_a = conditions.sort) === null || _a === void 0 ? void 0 : _a.codeValue;
const aggregate = this.categoryCodeModel.aggregate([
...matchStages,
...(typeof sortByCodeValue === 'number')
? [{ $sort: { codeValue: sortByCodeValue } }]
: [],
{ $project: projectStage }
]);
// tslint:disable-next-line:no-single-line-block-comment
/* istanbul ignore else */
if (typeof conditions.limit === 'number' && conditions.limit > 0) {
const page = (typeof conditions.page === 'number' && conditions.page > 0) ? conditions.page : 1;
aggregate.limit(conditions.limit * page)
.skip(conditions.limit * (page - 1));
}
return aggregate.exec();
});
}
/**
* 検索
*/
projectFields(params,
/**
* 空の場合無効
*/
inclusion) {
return __awaiter(this, void 0, void 0, function* () {
const conditions = CategoryCodeRepo.CREATE_MONGO_CONDITIONS(params);
let positiveProjectionFields = AVAILABLE_PROJECT_FIELDS;
if (Array.isArray(inclusion) && inclusion.length > 0) {
positiveProjectionFields = inclusion.filter((key) => AVAILABLE_PROJECT_FIELDS.includes(key));
}
else {
// if (Array.isArray(exclusion) && exclusion.length > 0) {
// positiveProjectionFields = positiveProjectionFields.filter((key) => !exclusion.includes(key));
// }
}
const projection = Object.assign({ _id: 0, id: { $toString: '$_id' } }, Object.fromEntries(positiveProjectionFields.map((key) => ([key, 1]))));
const query = this.categoryCodeModel.find((conditions.length > 0) ? { $and: conditions } : {}, 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);
}
return query.setOptions({ maxTimeMS: settings_1.MONGO_MAX_TIME_MS })
.lean() // 2024-08-19~
.exec();
});
}
save(params) {
return __awaiter(this, void 0, void 0, function* () {
let savedId;
// let doc: HydratedDocument<{ _id: Types.ObjectId }> | null;
if (typeof params.id !== 'string') {
const _a = params.attributes, { id, $unset } = _a, creatingDoc = __rest(_a, ["id", "$unset"]);
const createResult = yield this.categoryCodeModel.create(creatingDoc);
// doc = createResult;
if (typeof createResult.id !== 'string') {
throw new factory.errors.Internal(`failed in creating ${creatingDoc.typeOf} unexpectedly`);
}
savedId = createResult.id;
}
else {
// 上書き禁止属性を除外(2022-08-24~)
const _b = params.attributes, { id, codeValue, inCodeSet, project, typeOf, $unset } = _b, updateFields = __rest(_b, ["id", "codeValue", "inCodeSet", "project", "typeOf", "$unset"]);
const doc = yield this.categoryCodeModel.findOneAndUpdate({ _id: { $eq: params.id } }, Object.assign({ $set: updateFields }, ($unset !== undefined) ? { $unset } : undefined), { upsert: false, new: true, projection: { _id: 1 } })
.exec();
if (doc === null) {
throw new factory.errors.NotFound(this.categoryCodeModel.modelName);
}
savedId = params.id;
}
// if (doc === null) {
// throw new factory.errors.NotFound(this.categoryCodeModel.modelName);
// }
return { id: savedId };
});
}
saveManyByCodeValue(params) {
return __awaiter(this, void 0, void 0, function* () {
const bulkWriteOps = [];
if (Array.isArray(params)) {
params.forEach((p) => {
const $set = Object.assign({}, p.attributes);
if (typeof $set.id === 'string') {
delete $set.id;
}
bulkWriteOps.push({
updateOne: {
filter: {
'project.id': { $eq: p.attributes.project.id },
codeValue: { $eq: p.attributes.codeValue },
'inCodeSet.identifier': {
$exists: true,
$eq: p.attributes.inCodeSet.identifier
}
},
update: {
$set
// $setOnInsert: {}
},
upsert: (p.upsert !== undefined) ? p.upsert : false
}
});
});
}
if (bulkWriteOps.length > 0) {
yield this.categoryCodeModel.bulkWrite(bulkWriteOps, { ordered: false });
}
});
}
/**
* 削除する
*/
deleteById(params) {
return __awaiter(this, void 0, void 0, function* () {
yield this.categoryCodeModel.findOneAndDelete({ _id: { $eq: params.id } }, { projection: { _id: 1 } })
.exec();
});
}
/**
* プロジェクト指定で削除する
*/
deleteByProject(params) {
return __awaiter(this, void 0, void 0, function* () {
yield this.categoryCodeModel.deleteMany({
'project.id': { $eq: params.project.id }
})
.exec();
});
}
getCursor(conditions, projection) {
return this.categoryCodeModel.find(conditions, projection)
.sort({ codeValue: factory.sortType.Ascending })
.cursor();
}
unsetUnnecessaryFields(params) {
return __awaiter(this, void 0, void 0, function* () {
return this.categoryCodeModel.updateMany(params.filter, { $unset: params.$unset }, { timestamps: false })
.exec();
});
}
}
exports.CategoryCodeRepo = CategoryCodeRepo;