@chevre/domain
Version:
Chevre Domain Library for Node.js
289 lines (288 loc) • 14.9 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.CreativeWorkRepo = void 0;
const mongoose_1 = require("mongoose");
const factory = require("../factory");
const settings_1 = require("../settings");
const creativeWork_1 = require("./mongoose/schemas/creativeWork");
const AVAILABLE_PROJECT_FIELDS = [
'project',
'typeOf',
'identifier',
'name',
'alternativeHeadline',
// 'description',
'datePublished',
'distributor',
'headline',
'thumbnailUrl',
'duration',
'contentRating',
'offers',
'additionalProperty'
];
/**
* コンテンツリポジトリ
*/
class CreativeWorkRepo {
constructor(connection) {
this.creativeWorkModel = connection.model(creativeWork_1.modelName, (0, creativeWork_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;
const andConditions = [
{ typeOf: { $eq: factory.creativeWorkType.Movie } }
];
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 contentRatingEq = (_c = params.contentRating) === null || _c === void 0 ? void 0 : _c.$eq;
if (typeof contentRatingEq === 'string') {
andConditions.push({ contentRating: { $exists: true, $eq: contentRatingEq } });
}
const distributorCodeValueEq = (_e = (_d = params.distributor) === null || _d === void 0 ? void 0 : _d.codeValue) === null || _e === void 0 ? void 0 : _e.$eq;
if (typeof distributorCodeValueEq === 'string') {
andConditions.push({ 'distributor.codeValue': { $exists: true, $eq: distributorCodeValueEq } });
}
const idEq = (_f = params.id) === null || _f === void 0 ? void 0 : _f.$eq;
if (typeof idEq === 'string') {
// andConditions.push({ _id: { $eq: idEq } });
andConditions.push({ _id: { $eq: new mongoose_1.Types.ObjectId(idEq) } });
}
const idIn = (_g = params.id) === null || _g === void 0 ? void 0 : _g.$in;
if (Array.isArray(idIn)) {
// andConditions.push({ _id: { $in: idIn } });
andConditions.push({ _id: { $in: idIn.map((id) => new mongoose_1.Types.ObjectId(id)) } });
}
if (typeof params.identifier === 'string') {
if (params.identifier.length > 0) {
andConditions.push({ identifier: { $regex: new RegExp(params.identifier) } });
}
}
else {
const identifierEq = (_h = params.identifier) === null || _h === void 0 ? void 0 : _h.$eq;
if (typeof identifierEq === 'string') {
andConditions.push({ identifier: { $eq: identifierEq } });
}
const identifierIn = (_j = params.identifier) === null || _j === void 0 ? void 0 : _j.$in;
if (Array.isArray(identifierIn)) {
andConditions.push({ identifier: { $in: identifierIn } });
}
}
if (typeof params.name === 'string' && params.name.length > 0) {
// 多言語名称対応(2022-07-11~)
andConditions.push({
$or: [
{ name: { $exists: true, $regex: new RegExp(params.name) } },
{ 'name.ja': { $exists: true, $regex: new RegExp(params.name) } },
{ 'name.en': { $exists: true, $regex: new RegExp(params.name) } }
]
});
}
// tslint:disable-next-line:no-single-line-block-comment
/* istanbul ignore else */
if (params.datePublishedFrom !== undefined) {
andConditions.push({ datePublished: { $exists: true, $gte: params.datePublishedFrom } });
}
// tslint:disable-next-line:no-single-line-block-comment
/* istanbul ignore else */
if (params.datePublishedThrough !== undefined) {
andConditions.push({ datePublished: { $exists: true, $lte: params.datePublishedThrough } });
}
const offersAvailableFrom = (_k = params.offers) === null || _k === void 0 ? void 0 : _k.availableFrom;
if (offersAvailableFrom instanceof Date) {
andConditions.push({ 'offers.availabilityEnds': { $exists: true, $gte: offersAvailableFrom } });
}
const offersAvailableThrough = (_l = params.offers) === null || _l === void 0 ? void 0 : _l.availableThrough;
if (offersAvailableThrough instanceof Date) {
andConditions.push({ 'offers.availabilityStarts': { $exists: true, $lte: offersAvailableThrough } });
}
const additionalPropertyElemMatch = (_m = params.additionalProperty) === null || _m === void 0 ? void 0 : _m.$elemMatch;
if (additionalPropertyElemMatch !== undefined && additionalPropertyElemMatch !== null) {
andConditions.push({
additionalProperty: {
$exists: true,
$elemMatch: additionalPropertyElemMatch
}
});
}
return andConditions;
}
/**
* コンテンツを保管する
*/
saveMovie(params) {
return __awaiter(this, void 0, void 0, function* () {
let savedId;
let doc;
if (typeof params.id !== 'string' || params.id === '') {
const { $unset, id } = params, createParams = __rest(params, ["$unset", "id"]); // omit id(2024-09-12~)
doc = yield this.creativeWorkModel.create(createParams);
savedId = doc.id;
}
else {
// 上書き禁止属性を除外
const { id, identifier, project, typeOf, $unset } = params, setFields = __rest(params, ["id", "identifier", "project", "typeOf", "$unset"]);
doc = yield this.creativeWorkModel.findOneAndUpdate({ _id: { $eq: params.id } }, Object.assign({ $set: setFields }, ($unset !== undefined) ? { $unset } : undefined), { upsert: false, new: true, projection: { _id: 1 } })
.exec();
savedId = params.id;
}
if (doc === null) {
throw new factory.errors.NotFound(this.creativeWorkModel.modelName);
}
return { id: savedId };
});
}
/**
* コードをキーにして冪等作成
*/
// tslint:disable-next-line:max-func-body-length
upsertMoviesByIdentifier(params, options) {
return __awaiter(this, void 0, void 0, function* () {
const bulkWriteOps = [];
if (Array.isArray(params)) {
// tslint:disable-next-line:cyclomatic-complexity max-func-body-length
params.forEach(({ $set, $unset }) => {
// リソースのユニークネスを保証するfilter
const filter = {
typeOf: $set.typeOf,
'project.id': { $eq: $set.project.id },
identifier: { $eq: $set.identifier }
};
if ((options === null || options === void 0 ? void 0 : options.replace) === true) {
// updateOneで再実装
// const replacement: WithoutId<factory.creativeWork.movie.ICreativeWork> = replaceFields;
// const replaceOne: ReplaceOneModel<factory.creativeWork.movie.ICreativeWork> = {
// filter,
// replacement,
// upsert: true
// };
// bulkWriteOps.push({ replaceOne });
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');
}
const setOnInsert = {
typeOf,
project,
identifier
};
const updateFilter = Object.assign({ $setOnInsert: setOnInsert, $set: setFields }, ($unset !== undefined) ? { $unset } : undefined);
const updateOne = {
filter,
update: updateFilter,
upsert: true
};
bulkWriteOps.push({ updateOne });
}
else {
const { typeOf, project, identifier, duration, name, additionalProperty, contentRating, headline, distributor, thumbnailUrl, datePublished } = $set, setOnInsertFields = __rest($set, ["typeOf", "project", "identifier", "duration", "name", "additionalProperty", "contentRating", "headline", "distributor", "thumbnailUrl", "datePublished"]);
if (typeof identifier !== 'string' || identifier.length === 0) {
throw new factory.errors.ArgumentNull('identifier');
}
const setOnInsert = Object.assign(Object.assign({}, setOnInsertFields), { typeOf,
project,
identifier });
const updateFilter = {
$setOnInsert: setOnInsert,
// 変更可能な属性のみ上書き
$set: Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, (name !== undefined) ? { name } : undefined), (contentRating !== undefined) ? { contentRating } : undefined), (duration !== undefined) ? { duration } : undefined), (headline !== undefined) ? { headline } : undefined), (datePublished !== undefined) ? { datePublished } : undefined), (distributor !== undefined) ? { distributor } : undefined), (typeof thumbnailUrl === 'string') ? { thumbnailUrl } : undefined), (Array.isArray(additionalProperty)) ? { additionalProperty } : [])
};
const updateOne = {
filter,
update: updateFilter,
upsert: true
};
bulkWriteOps.push({ updateOne });
}
});
}
if (bulkWriteOps.length > 0) {
const bulkWriteResult = yield this.creativeWorkModel.bulkWrite(bulkWriteOps, { ordered: false });
return { bulkWriteResult };
}
});
}
/**
* コンテンツを検索する
*/
projectFields(params, inclusion) {
return __awaiter(this, void 0, void 0, function* () {
var _a;
const conditions = CreativeWorkRepo.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 {
throw new factory.errors.ArgumentNull('inclusion', 'inclusion must be specified');
}
const projection = Object.assign({ _id: 0, id: { $toString: '$_id' } }, Object.fromEntries(positiveProjectionFields.map((key) => ([key, 1]))));
const query = this.creativeWorkModel.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.identifier) !== undefined) {
query.sort({ identifier: params.sort.identifier });
}
return query.setOptions({ maxTimeMS: settings_1.MONGO_MAX_TIME_MS })
.lean() // 2024-09-19~
.exec();
});
}
/**
* コンテンツを削除する
*/
deleteMovie(params) {
return __awaiter(this, void 0, void 0, function* () {
yield this.creativeWorkModel.findOneAndDelete({ _id: { $eq: params.id } }, { projection: { _id: 1 } })
.exec();
});
}
deleteByProject(params) {
return __awaiter(this, void 0, void 0, function* () {
yield this.creativeWorkModel.deleteMany({
'project.id': { $eq: params.project.id }
})
.exec();
});
}
getCursor(conditions, projection) {
return this.creativeWorkModel.find(conditions, projection)
.sort({ identifier: factory.sortType.Ascending })
.cursor();
}
unsetUnnecessaryFields(params) {
return __awaiter(this, void 0, void 0, function* () {
return this.creativeWorkModel.updateMany(params.filter, { $unset: params.$unset }, { timestamps: false })
.exec();
});
}
}
exports.CreativeWorkRepo = CreativeWorkRepo;