@chevre/domain
Version:
Chevre Domain Library for Node.js
464 lines (463 loc) • 22.2 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.OfferCatalogItemRepo = void 0;
const mongoose_1 = require("mongoose");
const factory = require("../factory");
const offerCatalogItem_1 = require("./mongoose/schemas/offerCatalogItem");
const AVAILABLE_PROJECT_FIELDS = [
'name',
'description',
'project',
'typeOf',
'identifier',
'itemOffered',
'additionalProperty',
'numberOfItems',
'itemListElementTypeOf',
'dateSynced',
'relatedOffer'
];
const SLICE_ITEM_LIST_ELEMENT_MAX_LIMIT = 100;
/**
* サブカタログリポジトリ
*/
class OfferCatalogItemRepo {
constructor(connection) {
this.offerCatalogItemModel = connection.model(offerCatalogItem_1.modelName, (0, offerCatalogItem_1.createSchema)());
}
// tslint:disable-next-line:max-func-body-length
static CREATE_MONGO_CONDITIONS(params) {
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0;
// MongoDB検索条件
const andConditions = [];
const projectIdEq = (_b = (_a = params.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 = params.id) === null || _c === void 0 ? void 0 : _c.$in;
if (Array.isArray(idIn)) {
andConditions.push({ _id: { $in: idIn.map((id) => new mongoose_1.Types.ObjectId(id)) } });
}
// const idRegex = params.id?.$regex;
// if (typeof idRegex === 'string' && idRegex.length > 0) {
// andConditions.push({ _id: { $regex: new RegExp(idRegex) } });
// }
const identifierEq = (_d = params.identifier) === null || _d === void 0 ? void 0 : _d.$eq;
if (typeof identifierEq === 'string') {
andConditions.push({ identifier: { $eq: identifierEq } });
}
const identifierIn = (_e = params.identifier) === null || _e === void 0 ? void 0 : _e.$in;
if (Array.isArray(identifierIn)) {
andConditions.push({ identifier: { $in: identifierIn } });
}
const identifierRegex = (_f = params.identifier) === null || _f === void 0 ? void 0 : _f.$regex;
if (typeof identifierRegex === 'string' && identifierRegex.length > 0) {
andConditions.push({ identifier: { $regex: new RegExp(identifierRegex) } });
}
if (params.name !== undefined) {
andConditions.push({
$or: [
{ 'name.ja': new RegExp(params.name) },
{ 'name.en': new RegExp(params.name) }
]
});
}
const itemListElementTypeOfEq = (_h = (_g = params.itemListElement) === null || _g === void 0 ? void 0 : _g.typeOf) === null || _h === void 0 ? void 0 : _h.$eq;
if (typeof itemListElementTypeOfEq === 'string') {
andConditions.push({ 'itemListElement.typeOf': { $exists: true, $eq: itemListElementTypeOfEq } });
}
const itemListElementIdIn = (_k = (_j = params.itemListElement) === null || _j === void 0 ? void 0 : _j.id) === null || _k === void 0 ? void 0 : _k.$in;
if (Array.isArray(itemListElementIdIn)) {
andConditions.push({ 'itemListElement.id': { $exists: true, $in: itemListElementIdIn } });
}
const itemListElementIdNin = (_m = (_l = params.itemListElement) === null || _l === void 0 ? void 0 : _l.id) === null || _m === void 0 ? void 0 : _m.$nin;
if (Array.isArray(itemListElementIdNin)) {
andConditions.push({ 'itemListElement.id': { $nin: itemListElementIdNin } });
}
const itemListElementIdAll = (_p = (_o = params.itemListElement) === null || _o === void 0 ? void 0 : _o.id) === null || _p === void 0 ? void 0 : _p.$all;
if (Array.isArray(itemListElementIdAll)) {
andConditions.push({ 'itemListElement.id': { $exists: true, $all: itemListElementIdAll } });
}
const itemOfferedTypeOfEq = (_r = (_q = params.itemOffered) === null || _q === void 0 ? void 0 : _q.typeOf) === null || _r === void 0 ? void 0 : _r.$eq;
if (typeof itemOfferedTypeOfEq === 'string') {
andConditions.push({ 'itemOffered.typeOf': { $exists: true, $eq: itemOfferedTypeOfEq } });
}
const itemOfferedServiceTypeCodeValueEq = (_u = (_t = (_s = params.itemOffered) === null || _s === void 0 ? void 0 : _s.serviceType) === null || _t === void 0 ? void 0 : _t.codeValue) === null || _u === void 0 ? void 0 : _u.$eq;
if (typeof itemOfferedServiceTypeCodeValueEq === 'string') {
andConditions.push({ 'itemOffered.serviceType.codeValue': { $exists: true, $eq: itemOfferedServiceTypeCodeValueEq } });
}
const additionalPropertyElemMatch = (_v = params.additionalProperty) === null || _v === void 0 ? void 0 : _v.$elemMatch;
if (additionalPropertyElemMatch !== undefined && additionalPropertyElemMatch !== null) {
andConditions.push({ additionalProperty: { $exists: true, $elemMatch: additionalPropertyElemMatch } });
}
const appliesToMovieTicketServiceOutputTypeOfIn = (_0 = (_z = (_y = (_x = (_w = params.relatedOffer) === null || _w === void 0 ? void 0 : _w.priceSpecification) === null || _x === void 0 ? void 0 : _x.appliesToMovieTicket) === null || _y === void 0 ? void 0 : _y.serviceOutput) === null || _z === void 0 ? void 0 : _z.typeOf) === null || _0 === void 0 ? void 0 : _0.$in;
if (Array.isArray(appliesToMovieTicketServiceOutputTypeOfIn)) {
andConditions.push({
'relatedOffer.priceSpecification.appliesToMovieTicket.serviceOutput.typeOf': {
$exists: true,
$in: appliesToMovieTicketServiceOutputTypeOfIn
}
});
}
return andConditions;
}
save(params) {
return __awaiter(this, void 0, void 0, function* () {
let doc;
if (typeof params.id !== 'string' || params.id.length === 0) {
const { id, $unset } = params, creatingDoc = __rest(params, ["id", "$unset"]);
doc = yield this.offerCatalogItemModel.create(creatingDoc);
}
else {
const { id, identifier, project, typeOf, $unset } = params, updateFields = __rest(params, ["id", "identifier", "project", "typeOf", "$unset"]);
doc = yield this.offerCatalogItemModel.findOneAndUpdate({ _id: { $eq: params.id } }, Object.assign({ $set: updateFields }, (params.$unset !== undefined) ? { $unset: params.$unset } : undefined), { upsert: false, new: true, projection: { _id: 1 } })
.exec();
}
if (doc === null) {
throw new factory.errors.NotFound(this.offerCatalogItemModel.modelName);
}
return { id: doc.id };
});
}
/**
* プロジェクトとコードから冪等保管
*/
saveByIdentifier(params) {
return __awaiter(this, void 0, void 0, function* () {
const { id, identifier, project, typeOf } = params, updateFields = __rest(params, ["id", "identifier", "project", "typeOf"]);
const doc = yield this.offerCatalogItemModel.findOneAndUpdate({
identifier: { $eq: params.identifier },
'project.id': { $eq: params.project.id }
}, {
$set: updateFields,
$setOnInsert: { identifier, project, typeOf }
}, { upsert: true, new: true })
.exec();
return { id: doc.id };
});
}
/**
* コードをキーにして冪等置換(2023-12-14~)
*/
upsertManyByIdentifier(params
// options?: {
// }
) {
return __awaiter(this, void 0, void 0, function* () {
const bulkWriteOps = [];
const queryFilters = [];
if (Array.isArray(params)) {
params.forEach(({ $set, $unset }) => {
const { id, identifier, project, typeOf } = $set, setFields = __rest($set, ["id", "identifier", "project", "typeOf"]);
if (typeof identifier !== 'string' || identifier.length === 0) {
throw new factory.errors.ArgumentNull('identifier');
}
// リソースのユニークネスを保証するfilter
const filter = {
'project.id': { $eq: project.id },
identifier: { $eq: identifier }
};
queryFilters.push({
'project.id': { $eq: project.id },
identifier: { $eq: identifier }
});
const setOnInsert = {
identifier,
project,
typeOf
};
const updateOne = {
filter,
update: Object.assign({ $setOnInsert: setOnInsert, $set: setFields }, ($unset !== undefined) ? { $unset } : undefined),
upsert: true
};
bulkWriteOps.push({ updateOne });
});
}
if (bulkWriteOps.length > 0) {
const bulkWriteResult = yield this.offerCatalogItemModel.bulkWrite(bulkWriteOps, { ordered: false });
// modifiedの場合upsertedIdsに含まれないので、idを検索する
const modifiedCatalogs = yield this.offerCatalogItemModel.find({ $or: queryFilters }, { _id: 1 })
.exec();
return { bulkWriteResult, modifiedCatalogs };
}
});
}
/**
* 同期日時を更新する
*/
updateDateSynced(params) {
return __awaiter(this, void 0, void 0, function* () {
yield this.offerCatalogItemModel.updateOne({ _id: { $eq: params.id } }, { $set: { dateSynced: params.dateSynced } })
.exec();
});
}
updateManyById(params) {
return __awaiter(this, void 0, void 0, function* () {
if (!Array.isArray(params.id.$in) || params.id.$in.length === 0) {
return;
}
const pushItemListElementIds = params.$push.itemListElement.$each.map((element) => element.id);
yield this.offerCatalogItemModel.updateMany(Object.assign({ _id: { $in: params.id.$in } }, (pushItemListElementIds.length > 0)
// itemListElementのユニークネスを保証する
? {
'itemListElement.id': {
$nin: pushItemListElementIds
}
}
: undefined), Object.assign(Object.assign({}, (pushItemListElementIds.length > 0)
? {
$push: {
itemListElement: {
$each: params.$push.itemListElement.$each,
$slice: params.$push.itemListElement.$slice
}
}
}
: undefined), (params.$pull.itemListElement.$elemMatch.id.$in.length > 0)
? {
$pull: {
itemListElement: {
id: { $in: params.$pull.itemListElement.$elemMatch.id.$in }
}
}
}
: undefined))
.exec();
});
}
count(params) {
return __awaiter(this, void 0, void 0, function* () {
const conditions = OfferCatalogItemRepo.CREATE_MONGO_CONDITIONS(params);
const matchStages = conditions.map((condition) => {
return { $match: condition };
});
const result = yield this.offerCatalogItemModel.aggregate([
...matchStages,
{
$count: 'numItems'
}
])
.exec();
return (result.length > 0) ? result[0].numItems : 0;
});
}
projectFields(params, inclusion) {
return __awaiter(this, void 0, void 0, function* () {
var _a;
const conditions = OfferCatalogItemRepo.CREATE_MONGO_CONDITIONS(params);
const matchStages = conditions.map((condition) => {
return { $match: condition };
});
let positiveProjectionFields = AVAILABLE_PROJECT_FIELDS;
if (Array.isArray(inclusion) && inclusion.length > 0) {
positiveProjectionFields = inclusion.filter((key) => AVAILABLE_PROJECT_FIELDS.includes(key));
}
else {
// throw new factory.errors.ArgumentNull('inclusion', 'inclusion must be specified');
}
const projection = Object.assign({ _id: 0, id: { $toString: '$_id' } }, Object.fromEntries(positiveProjectionFields.map((key) => {
let value;
switch (key) {
case 'numberOfItems':
value = {
$cond: {
if: { $isArray: '$itemListElement' },
then: { $size: '$itemListElement' },
else: 0
}
};
break;
case 'itemListElementTypeOf':
value = { $first: '$itemListElement.typeOf' };
break;
default:
value = 1;
}
return [key, value];
})));
// let projectStage: { [field: string]: AnyExpression } = {
// _id: 0,
// name: '$name',
// description: '$description',
// project: '$project',
// typeOf: '$typeOf',
// id: { $toString: '$_id' },
// identifier: '$identifier',
// itemOffered: '$itemOffered',
// additionalProperty: '$additionalProperty',
// relatedOffer: '$relatedOffer',
// numberOfItems: {
// $cond: {
// if: { $isArray: '$itemListElement' },
// then: { $size: '$itemListElement' },
// else: 0
// }
// },
// itemListElementTypeOf: { $first: '$itemListElement.typeOf' },
// dateSynced: '$dateSynced'
// };
// const positiveProjectionFields: string[] = Object.keys(projection)
// .filter((key) => projection[<KeyOfOfferCatalogItem>key] !== 0);
// const negativeProjectionFields: string[] = Object.keys(projection)
// .filter((key) => projection[<KeyOfOfferCatalogItem>key] === 0);
// if (positiveProjectionFields.length > 0) {
// projectStage = {
// _id: 0,
// id: { $toString: '$_id' }
// };
// positiveProjectionFields.forEach((field) => {
// if (field !== '_id' && field !== 'id') {
// projectStage[field] = `$${field}`;
// }
// });
// } else if (negativeProjectionFields.length > 0) {
// negativeProjectionFields.forEach((field) => {
// if (projectStage[field] !== undefined && projectStage[field] !== null) {
// // tslint:disable-next-line:no-dynamic-delete
// delete projectStage[field];
// }
// });
// }
const aggregate = this.offerCatalogItemModel.aggregate([
...(((_a = params.sort) === null || _a === void 0 ? void 0 : _a.identifier) !== undefined) ? [{ $sort: { identifier: params.sort.identifier } }] : [],
...matchStages,
{ $project: projection }
]);
if (typeof params.limit === 'number' && params.limit > 0) {
const page = (typeof params.page === 'number' && params.page > 0) ? params.page : 1;
aggregate.limit(params.limit * page)
.skip(params.limit * (page - 1));
}
return aggregate.exec();
});
}
findItemListElementById(params) {
return __awaiter(this, void 0, void 0, function* () {
const doc = yield this.offerCatalogItemModel.findOne({
'project.id': { $eq: params.project.id },
_id: { $eq: params.id }
}, { 'itemListElement.id': 1, _id: 0 })
.lean() // lean(2024-09-24~)
.exec();
if (doc === null) {
throw new factory.errors.NotFound(this.offerCatalogItemModel.modelName);
}
return doc;
});
}
/**
* カタログのitemListElementをpaging有で検索する
* reimplement using $slice(2025-05-06=)
*/
sliceItemListElementById(params) {
return __awaiter(this, void 0, void 0, function* () {
const { id, limit, page } = params;
if (limit < 1 || limit > SLICE_ITEM_LIST_ELEMENT_MAX_LIMIT) {
throw new factory.errors.Argument('limit', `must be >=1 and <=${SLICE_ITEM_LIST_ELEMENT_MAX_LIMIT}`);
}
const pageMustBePositive = (typeof page === 'number' && page > 0) ? page : 1;
const skip = params.limit * (pageMustBePositive - 1);
const doc = yield this.offerCatalogItemModel.findOne({ _id: { $eq: id } }, {
_id: 1,
itemListElement: { $slice: [skip, limit] }
})
.lean()
.exec();
// console.log(doc);
return (doc !== null)
? doc.itemListElement.map((item, i) => ({ id: item.id, elementIndex: i + skip }))
: [];
});
}
deleteById(params) {
return __awaiter(this, void 0, void 0, function* () {
yield this.offerCatalogItemModel.findOneAndDelete({ _id: { $eq: params.id } }, { projection: { _id: 1 } })
.exec();
});
}
pullItemListElement(params) {
return __awaiter(this, void 0, void 0, function* () {
if (params.$pull.itemListElement.$elemMatch.id.$in.length === 0) {
return;
}
return this.offerCatalogItemModel.updateMany({
'project.id': { $eq: params.project.id },
'itemListElement.id': {
$exists: true,
$in: params.$pull.itemListElement.$elemMatch.id.$in
}
}, {
$pull: {
itemListElement: {
id: { $in: params.$pull.itemListElement.$elemMatch.id.$in }
}
}
})
.exec();
});
}
unsetUnnecessaryFields(params) {
return __awaiter(this, void 0, void 0, function* () {
return this.offerCatalogItemModel.updateMany(params.filter, { $unset: params.$unset }, { timestamps: false })
.exec();
});
}
aggregateItemList(params) {
return __awaiter(this, void 0, void 0, function* () {
const matchConditions = {
'itemListElement.typeOf': { $eq: params.itemListElement.typeOf.$eq }
};
const aggregations = yield this.offerCatalogItemModel.aggregate([
{ $match: matchConditions },
{
$project: {
numItemListElement: { $size: '$itemListElement' }
}
},
{
$group: {
_id: '$typeOf',
maxNumItemListElement: { $max: '$numItemListElement' },
minNumItemListElement: { $min: '$numItemListElement' }
}
},
{
$project: {
_id: 0,
maxNumItemListElement: '$maxNumItemListElement',
minNumItemListElement: '$minNumItemListElement'
}
}
])
.exec();
if (aggregations.length === 0) {
return {
aggregation: {}
};
}
return { aggregation: aggregations[0] };
});
}
}
exports.OfferCatalogItemRepo = OfferCatalogItemRepo;