UNPKG

@chevre/domain

Version:

Chevre Domain Library for Node.js

430 lines (429 loc) 19 kB
"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.ProductRepo = void 0; const mongoose_1 = require("mongoose"); const factory = require("../factory"); const settings_1 = require("../settings"); const product_1 = require("./mongoose/schemas/product"); const AVAILABLE_PROJECT_FIELDS = [ 'project', 'typeOf', 'additionalProperty', 'availableChannel', 'description', 'hasOfferCatalog', 'name', 'productID', 'serviceOutput', 'serviceType', 'hasOfferCatalog.id', 'potentialAction' ]; /** * プロダクトリポジトリ */ class ProductRepo { constructor(connection) { this.productModel = connection.model(product_1.modelName, (0, product_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; // 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 typeOfEq = (_c = params.typeOf) === null || _c === void 0 ? void 0 : _c.$eq; if (typeof typeOfEq === 'string') { andConditions.push({ typeOf: { $eq: typeOfEq } }); } const typeOfIn = (_d = params.typeOf) === null || _d === void 0 ? void 0 : _d.$in; if (Array.isArray(typeOfIn)) { andConditions.push({ typeOf: { $in: typeOfIn } }); } const hasOfferCatalogIdEq = (_f = (_e = params.hasOfferCatalog) === null || _e === void 0 ? void 0 : _e.id) === null || _f === void 0 ? void 0 : _f.$eq; if (typeof hasOfferCatalogIdEq === 'string') { // migrate to itemListElement(2024-09-30~) // andConditions.push({ // 'hasOfferCatalog.id': { // $exists: true, // $eq: hasOfferCatalogIdEq // } // }); andConditions.push({ 'hasOfferCatalog.itemListElement.id': { $exists: true, $eq: hasOfferCatalogIdEq } }); } const idEq = (_g = params.id) === null || _g === void 0 ? void 0 : _g.$eq; if (typeof idEq === 'string') { andConditions.push({ _id: { $eq: idEq } }); } const idIn = (_h = params.id) === null || _h === void 0 ? void 0 : _h.$in; if (Array.isArray(idIn)) { andConditions.push({ _id: { $in: idIn } }); } const productIDEq = (_j = params.productID) === null || _j === void 0 ? void 0 : _j.$eq; if (typeof productIDEq === 'string') { andConditions.push({ productID: { $eq: productIDEq } }); } const productIDIn = (_k = params.productID) === null || _k === void 0 ? void 0 : _k.$in; if (Array.isArray(productIDIn)) { andConditions.push({ productID: { $in: productIDIn } }); } const productIDRegex = (_l = params.productID) === null || _l === void 0 ? void 0 : _l.$regex; if (typeof productIDRegex === 'string' && productIDRegex.length > 0) { andConditions.push({ productID: { $regex: new RegExp(productIDRegex) } }); } const offersElemMatch = (_m = params.offers) === null || _m === void 0 ? void 0 : _m.$elemMatch; if (offersElemMatch !== undefined && offersElemMatch !== null) { andConditions.push({ offers: { $elemMatch: offersElemMatch } }); } const serviceOutputTypeOfEq = (_p = (_o = params.serviceOutput) === null || _o === void 0 ? void 0 : _o.typeOf) === null || _p === void 0 ? void 0 : _p.$eq; if (typeof serviceOutputTypeOfEq === 'string') { andConditions.push({ 'serviceOutput.typeOf': { $exists: true, $eq: serviceOutputTypeOfEq } }); } const serviceOutputAmountCurrencyEq = (_s = (_r = (_q = params.serviceOutput) === null || _q === void 0 ? void 0 : _q.amount) === null || _r === void 0 ? void 0 : _r.currency) === null || _s === void 0 ? void 0 : _s.$eq; if (typeof serviceOutputAmountCurrencyEq === 'string') { andConditions.push({ 'serviceOutput.amount.currency': { $exists: true, $eq: serviceOutputAmountCurrencyEq } }); } const serviceTypeCodeValueEq = (_u = (_t = params.serviceType) === null || _t === void 0 ? void 0 : _t.codeValue) === null || _u === void 0 ? void 0 : _u.$eq; if (typeof serviceTypeCodeValueEq === 'string') { andConditions.push({ 'serviceType.codeValue': { $exists: true, $eq: serviceTypeCodeValueEq } }); } const nameRegex = (_v = params.name) === null || _v === void 0 ? void 0 : _v.$regex; if (typeof nameRegex === 'string' && nameRegex.length > 0) { const nameRegexExp = new RegExp(nameRegex); andConditions.push({ $or: [ { 'name.ja': { $exists: true, $regex: nameRegexExp } }, { 'name.en': { $exists: true, $regex: nameRegexExp } } ] }); } // const providerIdEq = params.provider?.id?.$eq; // if (typeof providerIdEq === 'string') { // andConditions.push({ 'provider.id': { $exists: true, $eq: providerIdEq } }); // } return andConditions; } /** * プロダクトを検索する */ projectFields(conditions, inclusion) { return __awaiter(this, void 0, void 0, function* () { var _a; const andConditions = ProductRepo.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 { 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.productModel.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)); } // tslint:disable-next-line:no-single-line-block-comment /* istanbul ignore else */ if (((_a = conditions.sort) === null || _a === void 0 ? void 0 : _a.productID) !== undefined) { query.sort({ productID: conditions.sort.productID }); } return query.setOptions({ maxTimeMS: settings_1.MONGO_MAX_TIME_MS }) .lean() // 2024-08-20~ .exec(); }); } /** * カタログを検索する */ aggregateHasOfferCatalog(params) { return __awaiter(this, void 0, void 0, function* () { const page = (typeof params.page === 'number' && params.page > 0) ? params.page : 1; const matchStages = [{ $match: { _id: { $eq: new mongoose_1.Types.ObjectId(params.id) } } }]; return this.productModel.aggregate([ { $unwind: { path: '$hasOfferCatalog.itemListElement' // includeArrayIndex: 'elementIndex' } }, ...matchStages, { $project: { _id: 0, id: '$hasOfferCatalog.itemListElement.id' // elementIndex: '$elementIndex' } } ]) .limit(params.limit * page) .skip(params.limit * (page - 1)) .exec(); }); } deleteProductById(params) { return __awaiter(this, void 0, void 0, function* () { yield this.productModel.findOneAndDelete({ _id: { $eq: params.id } }, { projection: { _id: 1 } }) .exec(); }); } /** * プロダクトを保管する */ saveProduct(params) { return __awaiter(this, void 0, void 0, function* () { var _a, _b; let doc; let savedId; if (typeof params.id === 'string') { // 上書き禁止属性を除外 const _c = params.$set, { id, productID, project, typeOf, offers } = _c, setFields = __rest(_c, ["id", "productID", "project", "typeOf", "offers"]); switch (typeOf) { case factory.product.ProductType.EventService: case factory.product.ProductType.MembershipService: case factory.product.ProductType.PaymentCard: case factory.product.ProductType.Product: case factory.product.ProductType.Transportation: doc = yield this.productModel.findOneAndUpdate({ _id: { $eq: params.id }, typeOf: { $eq: typeOf } }, { $set: setFields, $unset: params.$unset }, { upsert: false, new: true, projection: { _id: 1, id: { $toString: '$_id' } } }) .lean() .exec(); if (doc === null) { throw new factory.errors.NotFound(this.productModel.modelName); } break; default: throw new factory.errors.NotImplemented(`${typeOf} not implemented`); } savedId = params.id; } else { const _d = params.$set, { id } = _d, createParams = __rest(_d, ["id"]); if (params.createIfNotExist === true) { doc = yield this.productModel.findOneAndUpdate({ 'project.id': { $eq: createParams.project.id }, typeOf: { $eq: createParams.typeOf } }, { $setOnInsert: createParams }, { new: true, upsert: true, projection: { _id: 1, id: { $toString: '$_id' } } }) .lean() .exec(); if (doc === null) { throw new factory.errors.NotFound(this.productModel.modelName); } savedId = doc.id; } else { // doc = await this.productModel.create(createParams); const result = yield this.productModel.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(`product not saved unexpectedly. result:${JSON.stringify(result)}`); } savedId = insertedId; } } return { id: savedId }; }); } /** * プロダクトコードをキーにして冪等置換 */ upsertManyByProductId(params // options?: { // } ) { return __awaiter(this, void 0, void 0, function* () { const bulkWriteOps = []; const queryFilters = []; if (Array.isArray(params)) { params.forEach(({ $set, $unset }) => { const { id, productID, project, typeOf, offers } = $set, setFields = __rest($set, ["id", "productID", "project", "typeOf", "offers"]); if (typeof productID !== 'string' || productID.length === 0) { throw new factory.errors.ArgumentNull('productID'); } // リソースのユニークネスを保証するfilter const filter = { 'project.id': { $eq: project.id }, productID: { $eq: productID } }; queryFilters.push({ 'project.id': { $eq: project.id }, productID: { $eq: productID } }); const setOnInsert = { productID, 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.productModel.bulkWrite(bulkWriteOps, { ordered: false }); // modifiedの場合upsertedIdsに含まれないので、idを検索する const modifiedProducts = yield this.productModel.find({ $or: queryFilters }, { _id: 1 }) .exec(); return { bulkWriteResult, modifiedProducts }; } }); } /** * プロダクトIDからavailableChannelを取得する */ findAvailableChannel(params) { return __awaiter(this, void 0, void 0, function* () { const paymentService = (yield this.projectFields({ limit: 1, page: 1, project: { id: { $eq: params.project.id } }, typeOf: { $eq: factory.product.ProductType.PaymentCard }, id: { $eq: params.id } }, ['availableChannel'] // [] )).shift(); if (paymentService === undefined) { throw new factory.errors.NotFound('PaymentService'); } const availableChannel = paymentService.availableChannel; if (availableChannel === undefined) { throw new factory.errors.NotFound('paymentService.availableChannel'); } return availableChannel; }); } /** * 指定カタログの設定されたプロダクトを削除する */ deleteByHasOfferCatalog(params) { return __awaiter(this, void 0, void 0, function* () { return this.productModel.deleteMany({ 'project.id': { $eq: params.project.id }, // 'hasOfferCatalog.id': { $exists: true, $eq: params.hasOfferCatalog.id } // migrate to itemListElement(2024-09-30~) 'hasOfferCatalog.itemListElement.id': { $exists: true, $eq: params.hasOfferCatalog.id } }) .exec(); }); } /** * プロジェクト指定で削除する */ deleteByProject(params) { return __awaiter(this, void 0, void 0, function* () { yield this.productModel.deleteMany({ 'project.id': { $eq: params.project.id } }) .exec(); }); } getCursor(conditions, projection) { return this.productModel.find(conditions, projection) .sort({ productID: factory.sortType.Ascending }) .cursor(); } unsetUnnecessaryFields(params) { return __awaiter(this, void 0, void 0, function* () { return this.productModel.updateMany(params.filter, { $unset: params.$unset }, { timestamps: false }) .exec(); }); } migrateHasOfferCatalogItemListElement(params) { return __awaiter(this, void 0, void 0, function* () { const offerCatalogItems = [{ id: params.hasOfferCatalog.id }]; const doc = yield this.productModel.findOneAndUpdate({ _id: { $eq: params.id }, 'hasOfferCatalog.id': { $exists: true, $eq: params.hasOfferCatalog.id } }, { $set: { 'hasOfferCatalog.itemListElement': offerCatalogItems } }, { upsert: false, new: true, projection: { _id: 1, id: { $toString: '$_id' } } }) .lean() .exec(); if (doc === null) { throw new factory.errors.NotFound(this.productModel.modelName); } }); } } exports.ProductRepo = ProductRepo;