@chevre/domain
Version:
Chevre Domain Library for Node.js
494 lines (493 loc) • 20.4 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());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.OwnershipInfoRepo = void 0;
const uuid = require("uuid");
const ownershipInfo_1 = require("./mongoose/schemas/ownershipInfo");
const errorHandler_1 = require("../errorHandler");
const factory = require("../factory");
const settings_1 = require("../settings");
/**
* 所有権リポジトリ
*/
class OwnershipInfoRepo {
constructor(connection) {
this.ownershipInfoModel = connection.model(ownershipInfo_1.modelName, (0, ownershipInfo_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, _m, _o, _p, _q, _r, _s, _t;
const andConditions = [];
// tslint:disable-next-line:no-single-line-block-comment
/* istanbul ignore else */
if (params.project !== undefined) {
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 typeOfGoodIdentifierEq = (_b = (_a = params.typeOfGood) === null || _a === void 0 ? void 0 : _a.identifier) === null || _b === void 0 ? void 0 : _b.$eq;
if (typeof typeOfGoodIdentifierEq === 'string') {
andConditions.push({
'typeOfGood.identifier': {
$exists: true,
$eq: typeOfGoodIdentifierEq
}
});
}
const typeOfGoodIssuedThroughIdEq = (_e = (_d = (_c = params.typeOfGood) === null || _c === void 0 ? void 0 : _c.issuedThrough) === null || _d === void 0 ? void 0 : _d.id) === null || _e === void 0 ? void 0 : _e.$eq;
if (typeof typeOfGoodIssuedThroughIdEq === 'string') {
andConditions.push({
'typeOfGood.issuedThrough.id': {
$exists: true,
$eq: typeOfGoodIssuedThroughIdEq
}
});
}
const typeOfGoodIssuedThroughTypeOfEq = (_h = (_g = (_f = params.typeOfGood) === null || _f === void 0 ? void 0 : _f.issuedThrough) === null || _g === void 0 ? void 0 : _g.typeOf) === null || _h === void 0 ? void 0 : _h.$eq;
if (typeof typeOfGoodIssuedThroughTypeOfEq === 'string') {
andConditions.push({
'typeOfGood.issuedThrough.typeOf': {
$exists: true,
$eq: typeOfGoodIssuedThroughTypeOfEq
}
});
}
const typeOfGoodTypeOf = (_j = params.typeOfGood) === null || _j === void 0 ? void 0 : _j.typeOf;
if (typeof typeOfGoodTypeOf === 'string') {
andConditions.push({
'typeOfGood.typeOf': {
$exists: true,
$eq: typeOfGoodTypeOf
}
});
}
else {
const typeOfGoodTypeOfEq = typeOfGoodTypeOf === null || typeOfGoodTypeOf === void 0 ? void 0 : typeOfGoodTypeOf.$eq;
if (typeof typeOfGoodTypeOfEq === 'string') {
andConditions.push({
'typeOfGood.typeOf': {
$exists: true,
$eq: typeOfGoodTypeOfEq
}
});
}
const typeOfGoodTypeOfIn = typeOfGoodTypeOf === null || typeOfGoodTypeOf === void 0 ? void 0 : typeOfGoodTypeOf.$in;
if (Array.isArray(typeOfGoodTypeOfIn)) {
andConditions.push({
'typeOfGood.typeOf': {
$exists: true,
$in: typeOfGoodTypeOfIn
}
});
}
}
// 互換性維持対応
// if (params.typeOfGood === undefined || params.typeOfGood === null) {
// params.typeOfGood = {};
// }
// if (typeof (<any>params.typeOfGood).id === 'string') {
// params.typeOfGood.id = { $eq: (<any>params.typeOfGood).id };
// }
// if (Array.isArray((<any>params.typeOfGood).ids)) {
// params.typeOfGood.id = { $in: (<any>params.typeOfGood).ids };
// }
const typeOfGoodIdEq = (_l = (_k = params.typeOfGood) === null || _k === void 0 ? void 0 : _k.id) === null || _l === void 0 ? void 0 : _l.$eq;
if (typeof typeOfGoodIdEq === 'string') {
andConditions.push({
'typeOfGood.id': {
$exists: true,
$eq: typeOfGoodIdEq
}
});
}
const typeOfGoodIdIn = (_o = (_m = params.typeOfGood) === null || _m === void 0 ? void 0 : _m.id) === null || _o === void 0 ? void 0 : _o.$in;
if (Array.isArray(typeOfGoodIdIn)) {
andConditions.push({
'typeOfGood.id': {
$exists: true,
$in: typeOfGoodIdIn
}
});
}
// tslint:disable-next-line:no-single-line-block-comment
/* istanbul ignore else */
if (Array.isArray(params.ids)) {
andConditions.push({
_id: { $in: params.ids }
});
}
// tslint:disable-next-line:no-single-line-block-comment
/* istanbul ignore else */
if (Array.isArray(params.identifiers)) {
andConditions.push({
identifier: {
$exists: true,
$in: params.identifiers
}
});
}
const ownedByTypeOfEq = (_q = (_p = params.ownedBy) === null || _p === void 0 ? void 0 : _p.typeOf) === null || _q === void 0 ? void 0 : _q.$eq;
if (typeof ownedByTypeOfEq === 'string') {
andConditions.push({
'ownedBy.typeOf': {
$exists: true,
$eq: ownedByTypeOfEq
}
});
}
// tslint:disable-next-line:no-single-line-block-comment
/* istanbul ignore else */
const ownedById = (_r = params.ownedBy) === null || _r === void 0 ? void 0 : _r.id;
if (typeof ownedById === 'string') {
andConditions.push({
'ownedBy.id': {
$exists: true,
$eq: ownedById
}
});
}
else {
const ownedByIdIn = ownedById === null || ownedById === void 0 ? void 0 : ownedById.$in;
if (Array.isArray(ownedByIdIn)) {
andConditions.push({
'ownedBy.id': {
$exists: true,
$in: ownedByIdIn
}
});
}
}
// discontinue(2024-12-26~)
// const ownedByMembershipNumberIn = params.ownedBy?.memberOf?.membershipNumber?.$in;
// if (Array.isArray(ownedByMembershipNumberIn)) {
// andConditions.push({
// 'ownedBy.memberOf.membershipNumber': {
// $exists: true,
// $in: ownedByMembershipNumberIn
// }
// });
// }
// tslint:disable-next-line:no-single-line-block-comment
/* istanbul ignore else */
if (params.ownedFrom instanceof Date) {
andConditions.push({
ownedThrough: { $gte: params.ownedFrom }
});
}
// tslint:disable-next-line:no-single-line-block-comment
/* istanbul ignore else */
if (params.ownedThrough instanceof Date) {
andConditions.push({
ownedFrom: { $lte: params.ownedThrough }
});
}
const ownedFromGte = params.ownedFromGte;
if (ownedFromGte instanceof Date) {
andConditions.push({
ownedFrom: { $gte: ownedFromGte }
});
}
const ownedFromLte = params.ownedFromLte;
if (ownedFromLte instanceof Date) {
andConditions.push({
ownedFrom: { $lte: ownedFromLte }
});
}
const acquiredFromIdIn = (_t = (_s = params.acquiredFrom) === null || _s === void 0 ? void 0 : _s.id) === null || _t === void 0 ? void 0 : _t.$in;
if (Array.isArray(acquiredFromIdIn)) {
andConditions.push({
'acquiredFrom.id': {
$exists: true,
$in: acquiredFromIdIn
}
});
}
return andConditions;
}
/**
* なければ作成する
*/
createIfNotExistByIdentifier(ownershipInfo) {
return __awaiter(this, void 0, void 0, function* () {
let doc;
let duplicate = false;
try {
doc = yield this.ownershipInfoModel.findOneAndUpdate({ identifier: { $eq: ownershipInfo.identifier } }, {
// insert時以外は何もしなくてもよい
$setOnInsert: Object.assign(Object.assign({}, ownershipInfo), { _id: uuid.v4() // 新規作成時は所有権ID発行
})
}, {
new: true,
upsert: true,
projection: {
_id: 0,
id: { $toString: '$_id' }
// __v: 0,
// createdAt: 0,
// updatedAt: 0
}
})
.lean()
.exec();
}
catch (error) {
if (yield (0, errorHandler_1.isMongoError)(error)) {
// すでに所有権が存在する場合ok
if (error.code === errorHandler_1.MongoErrorCode.DuplicateKey) {
duplicate = true;
}
}
if (!duplicate) {
throw error;
}
}
if (duplicate) {
// 重複の場合、再度取得
doc = yield this.ownershipInfoModel.findOne({ identifier: { $eq: ownershipInfo.identifier } }, {
_id: 0,
id: { $toString: '$_id' }
// __v: 0,
// createdAt: 0,
// updatedAt: 0
})
.lean()
.exec();
}
if (doc === undefined || doc === null) {
throw new factory.errors.NotFound(this.ownershipInfoModel.modelName);
}
return { id: doc.id };
});
}
projectFieldsById(params, inclusion) {
return __awaiter(this, void 0, void 0, function* () {
let projection = {
_id: 0,
id: { $toString: '$_id' },
project: 1,
typeOf: 1,
identifier: 1,
ownedBy: 1,
acquiredFrom: 1,
ownedFrom: 1,
ownedThrough: 1,
typeOfGood: 1
};
const positiveProjectionFields = (Array.isArray(inclusion))
? inclusion.filter((key) => key !== 'id' && String(key) !== '_id')
: undefined;
if (Array.isArray(positiveProjectionFields)) {
projection = Object.assign({ _id: 0, id: { $toString: '$_id' } }, Object.fromEntries(positiveProjectionFields.map((key) => ([key, 1]))));
}
const doc = yield this.ownershipInfoModel.findOne({ _id: { $eq: params.id } }, projection)
.lean() // lean(2024-08-15~)
.exec();
if (doc === null) {
throw new factory.errors.NotFound(this.ownershipInfoModel.modelName);
}
return doc;
});
}
/**
* 所有権を検索する
*/
projectFields(params, inclusion) {
return __awaiter(this, void 0, void 0, function* () {
var _a;
const conditions = OwnershipInfoRepo.CREATE_MONGO_CONDITIONS(params);
let projection = {
_id: 0,
id: { $toString: '$_id' },
project: 1,
typeOf: 1,
identifier: 1,
ownedBy: 1,
acquiredFrom: 1,
ownedFrom: 1,
ownedThrough: 1,
typeOfGood: 1
};
const positiveProjectionFields = (Array.isArray(inclusion))
? inclusion.filter((key) => key !== 'id' && String(key) !== '_id')
: undefined;
if (Array.isArray(positiveProjectionFields)) {
projection = Object.assign({ _id: 0, id: { $toString: '$_id' } }, Object.fromEntries(positiveProjectionFields.map((key) => ([key, 1]))));
}
const query = this.ownershipInfoModel.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 (((_a = params.sort) === null || _a === void 0 ? void 0 : _a.ownedFrom) !== undefined) {
query.sort({ ownedFrom: params.sort.ownedFrom });
}
return query.setOptions({ maxTimeMS: settings_1.MONGO_MAX_TIME_MS })
.lean() // lean(2024-08-19~)
.exec();
});
}
/**
* 識別子から所有期限を変更する
* 存在しない場合undefinedを返す
*/
findByIdentifierAndUpdateOwnedThrough(params) {
return __awaiter(this, void 0, void 0, function* () {
return this.ownershipInfoModel.findOneAndUpdate({
'project.id': { $eq: params.project.id },
identifier: { $eq: String(params.identifier) }
}, { ownedThrough: params.ownedThrough }, {
new: true,
projection: {
_id: 0,
id: { $toString: '$_id' },
identifier: 1
}
})
.lean()
.exec()
.then((doc) => {
// 存在しない場合も正常にハンドルする
if (doc === null) {
return;
}
else {
return doc;
}
});
});
}
/**
* 所有者の所有権を全て削除する
*/
deleteByOwnedById(params) {
return __awaiter(this, void 0, void 0, function* () {
return this.ownershipInfoModel.deleteMany({
'project.id': { $eq: params.project.id },
'ownedBy.id': { $exists: true, $eq: params.ownedBy.id }
})
.exec()
.then((deleteOneResult) => {
return {
// n: deleteOneResult?.n,
// ok: deleteOneResult?.ok,
deletedCount: deleteOneResult === null || deleteOneResult === void 0 ? void 0 : deleteOneResult.deletedCount
};
});
});
}
/**
* 特定所有者の特定所有権を削除する
*/
deleteByIdAndOwnedById(params) {
return __awaiter(this, void 0, void 0, function* () {
return this.ownershipInfoModel.deleteOne({
_id: { $eq: params.id },
'project.id': { $eq: params.project.id },
'ownedBy.id': { $exists: true, $eq: params.ownedBy.id }
})
.exec()
.then((deleteOneResult) => {
return {
// n: deleteOneResult?.n,
// ok: deleteOneResult?.ok,
deletedCount: deleteOneResult === null || deleteOneResult === void 0 ? void 0 : deleteOneResult.deletedCount
};
});
});
}
/**
* 識別子から所有期限切れの所有権を削除する
*/
deleteExpiredByIdentifiers(params) {
return __awaiter(this, void 0, void 0, function* () {
yield this.ownershipInfoModel.deleteMany({
'project.id': { $eq: params.project.id },
identifier: { $in: params.identifiers },
// 所有期限切れのもの(ownedThroughの存在しないものは削除してはいけない)
ownedThrough: { $exists: true, $lt: params.ownedThrough.$lt }
})
.exec();
});
}
getCursor(conditions, projection) {
return this.ownershipInfoModel.find(conditions, projection)
.sort({ ownedFrom: factory.sortType.Ascending })
.cursor();
}
/**
* 所有者を追加する
*/
addOwnerIfNotExist(params) {
return __awaiter(this, void 0, void 0, function* () {
if (typeof params.ownedBy.id !== 'string' || params.ownedBy.id.length === 0) {
throw new factory.errors.ArgumentNull('ownedBy.id');
}
let newOwner;
if (params.ownedBy.typeOf === factory.organizationType.Organization) {
newOwner = {
id: params.ownedBy.id,
typeOf: params.ownedBy.typeOf
};
}
else if (params.ownedBy.typeOf === factory.personType.Person
|| params.ownedBy.typeOf === factory.creativeWorkType.WebApplication) {
newOwner = {
id: params.ownedBy.id,
typeOf: params.ownedBy.typeOf
};
}
if (newOwner !== undefined) {
const doc = yield this.ownershipInfoModel.findOneAndUpdate({ _id: { $eq: params.id } }, { $addToSet: { ownedBy: newOwner } }, {
new: true,
projection: { _id: 1 }
})
.exec();
if (doc === null) {
throw new factory.errors.NotFound(this.ownershipInfoModel.modelName);
}
}
});
}
/**
* 所有者を削除する
*/
removeOwnerIfExist(params) {
return __awaiter(this, void 0, void 0, function* () {
if (typeof params.ownedBy.id !== 'string' || params.ownedBy.id.length === 0) {
throw new factory.errors.ArgumentNull('ownedBy.id');
}
const doc = yield this.ownershipInfoModel.findOneAndUpdate({ _id: { $eq: params.id } }, { $pull: { ownedBy: { id: params.ownedBy.id } } }, {
new: true,
projection: { _id: 1 }
})
.exec();
if (doc === null) {
throw new factory.errors.NotFound(this.ownershipInfoModel.modelName);
}
});
}
unsetUnnecessaryFields(params) {
return __awaiter(this, void 0, void 0, function* () {
return this.ownershipInfoModel.updateMany(params.filter, { $unset: params.$unset }, { timestamps: false })
.exec();
});
}
}
exports.OwnershipInfoRepo = OwnershipInfoRepo;