@chevre/domain
Version:
Chevre Domain Library for Node.js
353 lines (352 loc) • 15.8 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.SellerRepo = void 0;
const mongoose_1 = require("mongoose");
const seller_1 = require("./mongoose/schemas/seller");
const factory = require("../factory");
const settings_1 = require("../settings");
const AVAILABLE_PROJECT_FIELDS = [
'additionalProperty',
'branchCode',
'hasMerchantReturnPolicy',
'makesOffer',
'name',
'project',
'typeOf',
'url',
'telephone'
];
/**
* 販売者リポジトリ
* 対応決済方法については
* see SellerPaymentAcceptedRepo
*/
class SellerRepo {
constructor(connection) {
this.sellerModel = connection.model(seller_1.modelName, (0, seller_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;
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 idEq = (_c = params.id) === null || _c === void 0 ? void 0 : _c.$eq;
if (typeof idEq === 'string') {
// andConditions.push({ _id: { $eq: idEq } });
andConditions.push({ _id: { $eq: new mongoose_1.Types.ObjectId(idEq) } });
}
// メンバー条件追加(2023-07-24~)
const memberMemberOfIdIn = (_f = (_e = (_d = params.member) === null || _d === void 0 ? void 0 : _d.memberOf) === null || _e === void 0 ? void 0 : _e.id) === null || _f === void 0 ? void 0 : _f.$in;
if (Array.isArray(memberMemberOfIdIn)) {
// andConditions.push({ _id: { $in: memberMemberOfIdIn } });
andConditions.push({ _id: { $in: memberMemberOfIdIn.map((memberMemberOfId) => new mongoose_1.Types.ObjectId(memberMemberOfId)) } });
}
const nameRegex = params.name;
if (typeof nameRegex === 'string' && nameRegex.length > 0) {
andConditions.push({
$or: [
{
'name.ja': {
$exists: true,
$regex: new RegExp(nameRegex)
}
},
{
'name.en': {
$exists: true,
$regex: new RegExp(nameRegex)
}
}
]
});
}
const branchCodeEq = (_g = params.branchCode) === null || _g === void 0 ? void 0 : _g.$eq;
if (typeof branchCodeEq === 'string') {
andConditions.push({
branchCode: {
$eq: branchCodeEq
}
});
}
const branchCodeRegex = (_h = params.branchCode) === null || _h === void 0 ? void 0 : _h.$regex;
if (typeof branchCodeRegex === 'string' && branchCodeRegex.length > 0) {
andConditions.push({
branchCode: {
$regex: new RegExp(branchCodeRegex)
}
});
}
const additionalPropertyAll = (_j = params.additionalProperty) === null || _j === void 0 ? void 0 : _j.$all;
if (Array.isArray(additionalPropertyAll)) {
andConditions.push({
additionalProperty: {
$exists: true,
$all: additionalPropertyAll
}
});
}
const additionalPropertyIn = (_k = params.additionalProperty) === null || _k === void 0 ? void 0 : _k.$in;
if (Array.isArray(additionalPropertyIn)) {
andConditions.push({
additionalProperty: {
$exists: true,
$in: additionalPropertyIn
}
});
}
const additionalPropertyNin = (_l = params.additionalProperty) === null || _l === void 0 ? void 0 : _l.$nin;
if (Array.isArray(additionalPropertyNin)) {
andConditions.push({
additionalProperty: {
$nin: additionalPropertyNin
}
});
}
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
}
});
}
const paymentAcceptedEq = (_p = (_o = params.paymentAccepted) === null || _o === void 0 ? void 0 : _o.paymentMethodType) === null || _p === void 0 ? void 0 : _p.$eq;
if (typeof paymentAcceptedEq === 'string') {
andConditions.push({
'paymentAccepted.paymentMethodType': { $exists: true, $eq: paymentAcceptedEq }
});
}
const hasMerchantReturnPolicyIdentifierEq = (_r = (_q = params.hasMerchantReturnPolicy) === null || _q === void 0 ? void 0 : _q.identifier) === null || _r === void 0 ? void 0 : _r.$eq;
if (typeof hasMerchantReturnPolicyIdentifierEq === 'string') {
andConditions.push({
'hasMerchantReturnPolicy.identifier': { $exists: true, $eq: hasMerchantReturnPolicyIdentifierEq }
});
}
// discontinue(2025-01-22~)
// const hasMerchantReturnApplicablePaymentMethodEq = params.hasMerchantReturnPolicy?.applicablePaymentMethod?.$eq;
// if (typeof hasMerchantReturnApplicablePaymentMethodEq === 'string') {
// andConditions.push({
// 'hasMerchantReturnPolicy.applicablePaymentMethod': { $exists: true, $eq: hasMerchantReturnApplicablePaymentMethodEq }
// });
// }
// discontinue(2025-01-22~)
// const hasMerchantReturnPolicyItemConditionIdEq = params.hasMerchantReturnPolicy?.itemCondition?.id?.$eq;
// if (typeof hasMerchantReturnPolicyItemConditionIdEq === 'string') {
// andConditions.push({
// 'hasMerchantReturnPolicy.itemCondition.id': {
// $exists: true,
// $eq: hasMerchantReturnPolicyItemConditionIdEq
// }
// });
// }
return andConditions;
}
static CREATE_AGGREGATE_SELLERS_PROJECTION(exclusion) {
const projectStage = {
_id: 0,
id: { $toString: '$_id' },
additionalProperty: '$additionalProperty',
branchCode: '$branchCode',
hasMerchantReturnPolicy: {
$cond: {
if: { $isArray: '$hasMerchantReturnPolicy' },
then: {
$cond: {
if: { $eq: [{ $size: '$hasMerchantReturnPolicy' }, 0] },
then: [],
else: [{
url: { $first: '$hasMerchantReturnPolicy.url' }
// typeOf: { $first: '$hasMerchantReturnPolicy.typeOf' }
}]
}
},
else: []
}
},
name: '$name',
project: '$project',
typeOf: '$typeOf',
url: '$url',
telephone: '$telephone'
};
// if (inclusion.length > 0) {
// // no op
// } else
if (exclusion.length > 0) {
exclusion.forEach((field) => {
if (typeof projectStage[field] === 'string' || typeof projectStage[field] === 'object') {
// tslint:disable-next-line:no-dynamic-delete
delete projectStage[field];
}
});
}
return projectStage;
}
/**
* 販売者を保管する
*/
save(params) {
return __awaiter(this, void 0, void 0, function* () {
var _a, _b;
let doc;
let savedId;
const savingId = params.id;
if (typeof savingId === 'string') {
if (savingId === '') {
throw new factory.errors.ArgumentNull('id');
}
// 上書き禁止属性を除外(2022-08-24~)
const _c = params.attributes, { id, branchCode, project, typeOf, $unset } = _c, updateFields = __rest(_c, ["id", "branchCode", "project", "typeOf", "$unset"]);
const filter = {
_id: { $eq: savingId },
'project.id': { $eq: project.id }
};
const update = Object.assign({ $set: updateFields }, ($unset !== undefined && $unset !== null) ? { $unset } : undefined);
const options = {
upsert: false,
new: true,
projection: { _id: 1, id: { $toString: '$_id' } }
};
doc = yield this.sellerModel.findOneAndUpdate(filter, update, options)
.lean()
.exec();
if (doc === null) {
throw new factory.errors.NotFound(this.sellerModel.modelName);
}
savedId = savingId;
}
else {
const _d = params.attributes, { id, $unset } = _d, createParams = __rest(_d, ["id", "$unset"]);
// doc = await this.sellerModel.create<ISavingSeller>(createParams);
const result = yield this.sellerModel.insertMany(createParams, { rawResult: true });
const insertedId = (_b = (_a = result.insertedIds) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.toHexString();
if (typeof insertedId !== 'string') {
throw new factory.errors.Internal(`seller not saved unexpectedly. result:${JSON.stringify(result)}`);
}
savedId = insertedId;
}
return { id: savedId };
});
}
/**
* 集計検索(publicな属性検索が目的)
*/
searchByAggregate(conditions, exclusion) {
return __awaiter(this, void 0, void 0, function* () {
var _a;
const matchStages = SellerRepo.CREATE_MONGO_CONDITIONS(conditions)
.map((c) => ({ $match: c }));
const projectStage = SellerRepo.CREATE_AGGREGATE_SELLERS_PROJECTION(exclusion);
const sortByBranchCode = (_a = conditions.sort) === null || _a === void 0 ? void 0 : _a.branchCode;
const aggregate = this.sellerModel.aggregate([
...matchStages,
...(typeof sortByBranchCode === 'number')
? [{ $sort: { branchCode: sortByBranchCode } }]
: [],
{ $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(conditions, inclusion) {
return __awaiter(this, void 0, void 0, function* () {
var _a;
const andConditions = SellerRepo.CREATE_MONGO_CONDITIONS(conditions);
let positiveProjectionFields = AVAILABLE_PROJECT_FIELDS;
if (Array.isArray(inclusion) && inclusion.length > 0) {
positiveProjectionFields = inclusion.filter((key) => AVAILABLE_PROJECT_FIELDS.includes(key));
}
else {
// discontinue(2024-10-19~)
}
const projection = Object.assign({ _id: 0, id: { $toString: '$_id' } }, Object.fromEntries(positiveProjectionFields.map((key) => ([key, 1]))));
const query = this.sellerModel.find((andConditions.length > 0) ? { $and: andConditions } : {}, projection);
if (typeof conditions.limit === 'number' && conditions.limit > 0) {
const page = (typeof conditions.page === 'number' && conditions.page > 0) ? conditions.page : 1;
query.limit(conditions.limit)
.skip(conditions.limit * (page - 1));
}
if (((_a = conditions.sort) === null || _a === void 0 ? void 0 : _a.branchCode) !== undefined) {
query.sort({ branchCode: conditions.sort.branchCode });
}
return query.setOptions({ maxTimeMS: settings_1.MONGO_MAX_TIME_MS })
.lean() // 2024-08-22~
.exec();
});
}
/**
* 販売者を削除する
*/
deleteById(params) {
return __awaiter(this, void 0, void 0, function* () {
yield this.sellerModel.findOneAndDelete({
_id: { $eq: params.id },
'project.id': { $eq: params.project.id }
}, { projection: { _id: 1 } })
.exec();
});
}
/**
* プロジェクト指定で削除する
*/
deleteByProject(params) {
return __awaiter(this, void 0, void 0, function* () {
yield this.sellerModel.deleteMany({
'project.id': { $eq: params.project.id }
})
.exec();
});
}
addAvailableAtOrFrom(params) {
return __awaiter(this, void 0, void 0, function* () {
yield this.sellerModel.findOneAndUpdate({ _id: { $eq: params.id } }, { $push: { makesOffer: params.makesOffer } }, { projection: { _id: 1 } })
.exec();
});
}
getCursor(conditions, projection) {
return this.sellerModel.find(conditions, projection)
.sort({ branchCode: factory.sortType.Ascending })
.cursor();
}
unsetUnnecessaryFields(params) {
return __awaiter(this, void 0, void 0, function* () {
return this.sellerModel.updateMany(params.filter, { $unset: params.$unset }, { timestamps: false })
.exec();
});
}
}
exports.SellerRepo = SellerRepo;