@chevre/domain
Version:
Chevre Domain Library for Node.js
546 lines (545 loc) • 26.1 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.EventSeriesRepo = void 0;
const factory = require("../factory");
const eventSeries_1 = require("./mongoose/schemas/eventSeries");
const errorHandler_1 = require("../errorHandler");
const settings_1 = require("../settings");
/**
* 施設コンテンツリポジトリ
*/
class EventSeriesRepo {
constructor(connection) {
this.eventSeriesModel = connection.model(eventSeries_1.modelName, (0, eventSeries_1.createSchema)());
}
// tslint:disable-next-line:cyclomatic-complexity max-func-body-length
static CREATE_MONGO_CONDITIONS(conditions) {
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;
const andConditions = [
{ typeOf: { $eq: factory.eventType.ScreeningEventSeries } } // fix(2024-09-08~)
];
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 organizerIdEq = (_d = (_c = conditions.organizer) === null || _c === void 0 ? void 0 : _c.id) === null || _d === void 0 ? void 0 : _d.$eq;
if (typeof organizerIdEq === 'string') {
andConditions.push({ 'organizer.id': { $exists: true, $eq: organizerIdEq } });
}
const idEq = (_e = conditions.id) === null || _e === void 0 ? void 0 : _e.$eq;
if (typeof idEq === 'string') {
andConditions.push({ _id: { $eq: idEq } });
}
const idIn = (_f = conditions.id) === null || _f === void 0 ? void 0 : _f.$in;
if (Array.isArray(idIn)) {
andConditions.push({ _id: { $in: idIn } });
}
// tslint:disable-next-line:no-single-line-block-comment
/* istanbul ignore else */
if (Array.isArray(conditions.eventStatuses)) {
andConditions.push({
eventStatus: { $in: conditions.eventStatuses }
});
}
// tslint:disable-next-line:no-single-line-block-comment
/* istanbul ignore else */
if (conditions.inSessionFrom !== undefined) {
andConditions.push({
endDate: { $gte: conditions.inSessionFrom }
});
}
// tslint:disable-next-line:no-single-line-block-comment
/* istanbul ignore else */
if (conditions.inSessionThrough !== undefined) {
andConditions.push({
startDate: { $lte: conditions.inSessionThrough }
});
}
// tslint:disable-next-line:no-single-line-block-comment
/* istanbul ignore else */
if (conditions.startFrom !== undefined) {
andConditions.push({
startDate: { $gte: conditions.startFrom }
});
}
// tslint:disable-next-line:no-single-line-block-comment
/* istanbul ignore else */
if (conditions.startThrough !== undefined) {
andConditions.push({
startDate: { $lte: conditions.startThrough }
});
}
// tslint:disable-next-line:no-single-line-block-comment
/* istanbul ignore else */
if (conditions.endFrom !== undefined) {
andConditions.push({
endDate: { $gte: conditions.endFrom }
});
}
// tslint:disable-next-line:no-single-line-block-comment
/* istanbul ignore else */
if (conditions.endThrough !== undefined) {
andConditions.push({
endDate: { $lte: conditions.endThrough }
});
}
const locationBranchCodeEq = (_h = (_g = conditions.location) === null || _g === void 0 ? void 0 : _g.branchCode) === null || _h === void 0 ? void 0 : _h.$eq;
if (typeof locationBranchCodeEq === 'string') {
andConditions.push({ 'location.branchCode': { $exists: true, $eq: locationBranchCodeEq } });
}
const locationBranchCodeIn = (_k = (_j = conditions.location) === null || _j === void 0 ? void 0 : _j.branchCode) === null || _k === void 0 ? void 0 : _k.$in;
if (Array.isArray(locationBranchCodeIn)) {
andConditions.push({ 'location.branchCode': { $exists: true, $in: locationBranchCodeIn } });
}
const additionalPropertyElemMatch = (_l = conditions.additionalProperty) === null || _l === void 0 ? void 0 : _l.$elemMatch;
if (additionalPropertyElemMatch !== undefined && additionalPropertyElemMatch !== null) {
andConditions.push({
additionalProperty: {
$exists: true,
$elemMatch: additionalPropertyElemMatch
}
});
}
// tslint:disable-next-line:no-single-line-block-comment
/* istanbul ignore else */
if (typeof conditions.name === 'string' && conditions.name.length > 0) {
andConditions.push({
$or: [
{
'name.ja': {
$exists: true,
$regex: new RegExp(conditions.name)
}
},
{
'name.en': {
$exists: true,
$regex: new RegExp(conditions.name)
}
},
{
kanaName: {
$exists: true,
$regex: new RegExp(conditions.name)
}
}
]
});
}
const locationIdEq = (_o = (_m = conditions.location) === null || _m === void 0 ? void 0 : _m.id) === null || _o === void 0 ? void 0 : _o.$eq;
// tslint:disable-next-line:no-single-line-block-comment
/* istanbul ignore else */
if (typeof locationIdEq === 'string') {
andConditions.push({
'location.id': { $exists: true, $eq: locationIdEq }
});
}
// tslint:disable-next-line:no-single-line-block-comment
/* istanbul ignore else */
if (conditions.location !== undefined) {
// tslint:disable-next-line:no-single-line-block-comment
/* istanbul ignore else */
if (Array.isArray(conditions.location.branchCodes)) {
andConditions.push({
'location.branchCode': {
$exists: true,
$in: conditions.location.branchCodes
}
});
}
}
const workPerformedIdentifierIn = (_p = conditions.workPerformed) === null || _p === void 0 ? void 0 : _p.identifiers;
// tslint:disable-next-line:no-single-line-block-comment
/* istanbul ignore else */
if (Array.isArray(workPerformedIdentifierIn)) {
andConditions.push({
'workPerformed.identifier': { $exists: true, $in: workPerformedIdentifierIn }
});
}
const workPerformedVersionEq = (_r = (_q = conditions.workPerformed) === null || _q === void 0 ? void 0 : _q.version) === null || _r === void 0 ? void 0 : _r.$eq;
if (typeof workPerformedVersionEq === 'string') {
andConditions.push({
'workPerformed.version': { $exists: true, $eq: workPerformedVersionEq }
});
}
const videoFormatTypeOfEq = (_t = (_s = conditions.videoFormat) === null || _s === void 0 ? void 0 : _s.typeOf) === null || _t === void 0 ? void 0 : _t.$eq;
if (typeof videoFormatTypeOfEq === 'string') {
andConditions.push({
'videoFormat.typeOf': {
$exists: true,
$eq: videoFormatTypeOfEq
}
});
}
const videoFormatTypeOfIn = (_v = (_u = conditions.videoFormat) === null || _u === void 0 ? void 0 : _u.typeOf) === null || _v === void 0 ? void 0 : _v.$in;
if (Array.isArray(videoFormatTypeOfIn)) {
andConditions.push({
'videoFormat.typeOf': {
$exists: true,
$in: videoFormatTypeOfIn
}
});
}
const soundFormatTypeOfEq = (_x = (_w = conditions.soundFormat) === null || _w === void 0 ? void 0 : _w.typeOf) === null || _x === void 0 ? void 0 : _x.$eq;
if (typeof soundFormatTypeOfEq === 'string') {
andConditions.push({
'soundFormat.typeOf': {
$exists: true,
$eq: soundFormatTypeOfEq
}
});
}
const soundFormatTypeOfIn = (_z = (_y = conditions.soundFormat) === null || _y === void 0 ? void 0 : _y.typeOf) === null || _z === void 0 ? void 0 : _z.$in;
if (Array.isArray(soundFormatTypeOfIn)) {
andConditions.push({
'soundFormat.typeOf': {
$exists: true,
$in: soundFormatTypeOfIn
}
});
}
return andConditions;
}
/**
* 複数イベントを作成する
*/
createManyEventSeries(params) {
return __awaiter(this, void 0, void 0, function* () {
const uniqid = yield Promise.resolve().then(() => require('uniqid'));
const insertingDocs = params.attributes.map((p) => {
return Object.assign({ _id: uniqid() }, p);
});
try {
yield this.eventSeriesModel.insertMany(insertingDocs, { rawResult: true } // rawResult(2024-08-02~)
);
// console.dir(insertResult, { depth: null });
}
catch (error) {
if (yield (0, errorHandler_1.isMongoError)(error)) {
if (error.code === errorHandler_1.MongoErrorCode.DuplicateKey) {
throw new factory.errors.AlreadyInUse(factory.eventType.ScreeningEventSeries, ['workPerformed.version']);
}
}
throw error;
}
if (params.expectsNoContent) {
return;
}
return insertingDocs.map(({ _id }) => _id);
});
}
/**
* コンテンツ+バージョンをキーにして、なければ作成する(複数対応)
*/
createIfNotExistByWorkPerformed(params) {
return __awaiter(this, void 0, void 0, function* () {
const uniqid = yield Promise.resolve().then(() => require('uniqid'));
const bulkWriteOps = [];
if (Array.isArray(params)) {
params.forEach((creatingEventParams) => {
const version = creatingEventParams.attributes.workPerformed.version;
if (typeof version !== 'string') {
throw new factory.errors.ArgumentNull('workPerformed.version');
}
const setOnInsertFields = creatingEventParams.attributes;
bulkWriteOps.push({
updateOne: {
filter: {
typeOf: creatingEventParams.attributes.typeOf,
'project.id': { $eq: creatingEventParams.attributes.project.id },
'location.branchCode': {
$exists: true,
$eq: creatingEventParams.attributes.location.branchCode
},
'workPerformed.identifier': {
$exists: true,
$eq: creatingEventParams.attributes.workPerformed.identifier
},
'workPerformed.version': {
$exists: true,
$eq: version
}
},
update: {
$setOnInsert: Object.assign(Object.assign({}, setOnInsertFields), { _id: uniqid() })
},
upsert: true
}
});
});
}
if (bulkWriteOps.length > 0) {
return this.eventSeriesModel.bulkWrite(bulkWriteOps, { ordered: false });
}
});
}
/**
* コンテンツ+バージョンをキーにして冪等置換
*/
// tslint:disable-next-line:max-func-body-length
upsertByVersion(params) {
return __awaiter(this, void 0, void 0, function* () {
const uniqid = yield Promise.resolve().then(() => require('uniqid'));
const bulkWriteOps4insert = [];
const queryFilters = [];
if (Array.isArray(params)) {
params.forEach(({ $set, $unset }) => {
const version = $set.workPerformed.version;
if (typeof version !== 'string' || version.length === 0) {
throw new factory.errors.ArgumentNull('workPerformed.version');
}
// リソースのユニークネスを保証するfilter
const filter = {
typeOf: $set.typeOf,
'project.id': { $eq: $set.project.id },
'location.branchCode': { $exists: true, $eq: $set.location.branchCode },
'workPerformed.identifier': { $exists: true, $eq: $set.workPerformed.identifier },
'workPerformed.version': { $exists: true, $eq: version }
};
queryFilters.push({
typeOf: $set.typeOf,
'project.id': { $eq: $set.project.id },
'location.branchCode': { $exists: true, $eq: $set.location.branchCode },
'workPerformed.identifier': { $exists: true, $eq: $set.workPerformed.identifier },
'workPerformed.version': { $exists: true, $eq: version }
});
const { identifier, project, typeOf } = $set, setFields = __rest($set, ["identifier", "project", "typeOf"]);
const setOnInsert = {
project,
typeOf,
_id: uniqid()
};
const updateOne = {
filter,
update: Object.assign({ $setOnInsert: setOnInsert, $set: setFields }, ($unset !== undefined) ? { $unset } : undefined),
upsert: true
};
bulkWriteOps4insert.push({ updateOne });
});
}
if (bulkWriteOps4insert.length > 0) {
const bulkWriteResult4insert = yield this.eventSeriesModel.bulkWrite(bulkWriteOps4insert, { ordered: false });
// modifiedの場合upsertedIdsに含まれないので、idを検索する
const modifiedEvents = yield this.eventSeriesModel.find({ $or: queryFilters }, { _id: 1 })
.exec();
return { bulkWriteResult4insert, modifiedEvents };
}
});
}
saveEventSeries(params) {
return __awaiter(this, void 0, void 0, function* () {
let savedEventId;
let doc;
const _a = params.attributes, { identifier, project, typeOf } = _a, updateFields = __rest(_a, ["identifier", "project", "typeOf"]);
if (typeof typeOf !== 'string' || typeOf.length === 0) {
throw new factory.errors.ArgumentNull('attributes.typeOf');
}
try {
if (params.id === undefined) {
const uniqid = yield Promise.resolve().then(() => require('uniqid'));
const id = uniqid();
doc = yield this.eventSeriesModel.create(Object.assign(Object.assign({}, params.attributes), { _id: id }));
savedEventId = id;
}
else {
// const upsert: boolean = params.upsert === true;
const upsert = false;
doc = yield this.eventSeriesModel.findOneAndUpdate({
_id: { $eq: params.id },
typeOf: { $eq: typeOf }
}, Object.assign({
// 上書き禁止属性を除外(2022-08-24~)
$setOnInsert: Object.assign({ typeOf,
project }, (identifier !== undefined) ? { identifier } : undefined), $set: updateFields }, (params.$unset !== undefined) ? { $unset: params.$unset } : undefined), {
upsert,
new: true,
projection: { _id: 1 }
})
.lean()
.exec();
savedEventId = params.id;
}
}
catch (error) {
if (yield (0, errorHandler_1.isMongoError)(error)) {
if (error.code === errorHandler_1.MongoErrorCode.DuplicateKey) {
throw new factory.errors.AlreadyInUse(factory.eventType.ScreeningEventSeries, ['workPerformed.version']);
}
}
throw error;
}
if (doc === null) {
throw new factory.errors.NotFound(this.eventSeriesModel.modelName);
}
return { id: savedEventId }; // optimize(2024-07-31~)
});
}
/**
* sskts施設コンテンツ保管
*/
upsertManyEventSeriesById4sskts(params) {
return __awaiter(this, void 0, void 0, function* () {
const bulkWriteOps = [];
if (Array.isArray(params)) {
params.forEach((p) => {
// 上書き禁止属性を除外(2022-08-24~)
const _a = p.attributes, { identifier, project, typeOf } = _a, updateFields = __rest(_a, ["identifier", "project", "typeOf"]);
bulkWriteOps.push({
updateOne: {
filter: {
_id: { $eq: p.id },
typeOf: { $eq: factory.eventType.ScreeningEventSeries }
},
update: {
$setOnInsert: Object.assign({ typeOf: factory.eventType.ScreeningEventSeries, project: p.attributes.project }, (typeof p.attributes.identifier === 'string')
? { identifier: p.attributes.identifier } : undefined),
$set: updateFields
// $unsetに対応(2022-08-31~)
// ...(p.$unset !== undefined) ? { $unset: p.$unset } : undefined
},
upsert: true
}
});
});
}
if (bulkWriteOps.length > 0) {
yield this.eventSeriesModel.bulkWrite(bulkWriteOps, { ordered: false });
}
});
}
/**
* イベントを検索する(inclusion projection)
*/
projectEventSeriesFields(params, inclusion) {
return __awaiter(this, void 0, void 0, function* () {
var _a;
const conditions = EventSeriesRepo.CREATE_MONGO_CONDITIONS(params);
let projection = {};
const positiveProjectionFields = (Array.isArray(inclusion))
? inclusion.filter((key) => key !== 'id' && key !== '_id')
: [];
if (Array.isArray(inclusion) && inclusion.length > 0) {
projection = Object.assign({ _id: 0, id: { $toString: '$_id' } }, Object.fromEntries(positiveProjectionFields.map((key) => ([key, 1]))));
}
else {
// discontinue(2024-07-24~)
throw new factory.errors.ArgumentNull('inclusion', 'inclusion must be specified');
}
const query = this.eventSeriesModel.find({ $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 (((_a = params.sort) === null || _a === void 0 ? void 0 : _a.startDate) !== undefined) {
query.sort({ startDate: params.sort.startDate });
}
// 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 })
.lean() // lean(2024-08-01~)
.exec();
});
}
deleteEventSeriesById(params) {
return __awaiter(this, void 0, void 0, function* () {
yield this.eventSeriesModel.findOneAndDelete({
_id: { $eq: params.id },
'project.id': { $eq: params.project.id },
typeOf: { $eq: factory.eventType.ScreeningEventSeries }
}, { projection: { _id: 1 } })
.exec();
});
}
deleteManyByOrganizerId(params) {
return __awaiter(this, void 0, void 0, function* () {
return this.eventSeriesModel.deleteMany({
'project.id': { $eq: params.project.id },
'organizer.id': { $exists: true, $eq: params.organizer.id },
typeOf: { $eq: factory.eventType.ScreeningEventSeries }
})
.exec();
});
}
deleteManyByLocationId(params) {
return __awaiter(this, void 0, void 0, function* () {
return this.eventSeriesModel.deleteMany({
'project.id': { $eq: params.project.id },
'location.id': { $exists: true, $eq: params.location.id },
typeOf: { $eq: factory.eventType.ScreeningEventSeries }
})
.exec();
});
}
/**
* 既存施設コンテンツの最大バージョンを集計する
*/
aggregateMaxVersion(params) {
return __awaiter(this, void 0, void 0, function* () {
var _a;
const aggregations = yield this.eventSeriesModel.aggregate([
{
$match: {
typeOf: { $eq: factory.eventType.ScreeningEventSeries },
'project.id': { $eq: params.project.id.$eq },
'workPerformed.identifier': { $exists: true, $eq: params.workPerformed.identifier.$eq },
'workPerformed.version': { $exists: true },
'location.branchCode': { $exists: true, $in: params.location.branchCode.$in }
}
},
{
$project: {
workPerformed: '$workPerformed',
// version: { $toInt: '$workPerformed.version' }
version: { $toLong: '$workPerformed.version' } // support YYYYMMDDHHmmss
}
},
{
$group: {
_id: '$typeOf',
maxVersion: { $max: '$version' }
}
}
])
.exec();
const maxVersion = (aggregations.length > 0)
? String((_a = aggregations.shift()) === null || _a === void 0 ? void 0 : _a.maxVersion)
: '0';
return { maxVersion };
});
}
getCursor(conditions, projection) {
return this.eventSeriesModel.find(conditions, projection)
.sort({ startDate: factory.sortType.Descending })
.cursor();
}
}
exports.EventSeriesRepo = EventSeriesRepo;