UNPKG

@chevre/domain

Version:

Chevre Domain Library for Node.js

259 lines (258 loc) 11.4 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()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.MessageRepo = void 0; // import { isMongoError, MongoErrorCode } from '../errorHandler'; const factory = require("../factory"); const settings_1 = require("../settings"); const message_1 = require("./mongoose/schemas/message"); const AVAILABLE_PROJECT_FIELDS = [ 'project', 'provider', 'typeOf', 'datePublished', 'identifier', 'mainEntity', 'name', 'about', 'sender', 'text', 'toRecipient' ]; /** * メッセージリポジトリ */ class MessageRepo { constructor(connection) { this.messageModel = connection.model(message_1.modelName, (0, message_1.createSchema)()); } static CREATE_MONGO_CONDITIONS(params) { var _a, _b, _c, _d, _e, _f, _g, _h, _j; 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 providerIdEq = (_d = (_c = params.provider) === null || _c === void 0 ? void 0 : _c.id) === null || _d === void 0 ? void 0 : _d.$eq; if (typeof providerIdEq === 'string') { andConditions.push({ 'provider.id': { $eq: providerIdEq } }); } const mainEntityOrderNumberEq = (_f = (_e = params.mainEntity) === null || _e === void 0 ? void 0 : _e.orderNumber) === null || _f === void 0 ? void 0 : _f.$eq; if (typeof mainEntityOrderNumberEq === 'string') { andConditions.push({ 'mainEntity.orderNumber': { $exists: true, $eq: mainEntityOrderNumberEq } }); } const identifierEq = (_g = params.identifier) === null || _g === void 0 ? void 0 : _g.$eq; if (typeof identifierEq === 'string') { andConditions.push({ identifier: { $eq: identifierEq } }); } const aboutIdentifierEq = (_j = (_h = params.about) === null || _h === void 0 ? void 0 : _h.identifier) === null || _j === void 0 ? void 0 : _j.$eq; if (typeof aboutIdentifierEq === 'string') { andConditions.push({ 'about.identifier': { $eq: aboutIdentifierEq } }); } return andConditions; } /** * 検索 */ projectFields(params, inclusion) { return __awaiter(this, void 0, void 0, function* () { var _a; const conditions = MessageRepo.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.messageModel.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)); } if (typeof ((_a = params.sort) === null || _a === void 0 ? void 0 : _a.datePublished) === 'number') { query.sort({ datePublished: params.sort.datePublished }); } return query.setOptions({ maxTimeMS: settings_1.MONGO_MAX_TIME_MS }) .lean() // 2024-09-19~ .exec(); }); } // 重複エラーをハンドルするためにupsertOneByIdentifierへ移行(2025-05-11~) /** * コードをキーにしてなければ作成する(複数対応) */ // public async upsertByIdentifier( // params: Pick< // IEmailMessage, // 'about' | 'identifier' | 'mainEntity' | 'name' | 'project' | 'sender' | 'text' | 'toRecipient' | 'provider' // >[] // ): Promise<BulkWriteResult | void> { // const now = new Date(); // const bulkWriteOps: AnyBulkWriteOperation<IEmailMessage>[] = []; // if (Array.isArray(params)) { // params.forEach((creatingNoteParams) => { // const { about, identifier, project, text, mainEntity, name, sender, toRecipient, provider } = creatingNoteParams; // if (typeof identifier !== 'string' || identifier.length === 0) { // throw new factory.errors.ArgumentNull('identifier'); // } // if (typeof text !== 'string') { // throw new factory.errors.ArgumentNull('text'); // } // // リソースのユニークネスを保証するfilter // const filter: Filter<IEmailMessage> = { // // typeOf: { $eq: factory.creativeWorkType.EmailMessage }, // 'project.id': { $eq: project.id }, // identifier: { $eq: identifier } // }; // const setOnInsert: MatchKeysAndValues<IEmailMessage> = { // identifier, // project, // datePublished: now, // typeOf: factory.creativeWorkType.EmailMessage // }; // // 変更可能な属性のみ上書き // const setFields: MatchKeysAndValues<IEmailMessage> = { // provider, // mainEntity, // about, // sender, // text, // toRecipient, // ...(typeof name === 'string') ? { name } : undefined // }; // const updateFilter: UpdateFilter<IEmailMessage> = { // $setOnInsert: setOnInsert, // $set: setFields // }; // const updateOne: UpdateOneModel<IEmailMessage> = { // filter, // update: updateFilter, // upsert: true // }; // bulkWriteOps.push({ updateOne }); // }); // } // if (bulkWriteOps.length > 0) { // return this.messageModel.bulkWrite(bulkWriteOps, { ordered: false }); // } // } /** * コードをキーにしてひとつ更新(なければ作成する) */ upsertOneByIdentifier(params) { return __awaiter(this, void 0, void 0, function* () { const datePublished = new Date(); const { about, identifier, project, text, mainEntity, name, sender, toRecipient, provider } = params; if (typeof identifier !== 'string' || identifier.length === 0) { throw new factory.errors.ArgumentNull('identifier'); } if (typeof project.id !== 'string' || project.id.length === 0) { throw new factory.errors.ArgumentNull('project.id'); } if (typeof text !== 'string') { throw new factory.errors.ArgumentNull('text'); } // リソースのユニークネスを保証するfilter const filter = { 'project.id': { $eq: project.id }, identifier: { $eq: identifier } }; const setOnInsert = { identifier, project, datePublished, typeOf: factory.creativeWorkType.EmailMessage }; // 変更可能な属性のみ上書き const setFields = Object.assign({ provider, mainEntity, about, sender, text, toRecipient }, (typeof name === 'string') ? { name } : undefined); const updateFilter = { $setOnInsert: setOnInsert, $set: setFields }; const options = { upsert: true }; try { yield this.messageModel.updateOne(filter, updateFilter, options) .exec(); } catch (error) { const throwsError = true; // ひとまず保留 // if (await isMongoError(error)) { // // すでにidentifierが存在する場合ok // if (error.code === MongoErrorCode.DuplicateKey) { // throwsError = false; // } // } if (throwsError) { throw error; } } }); } /** * コードで参照 */ findByIdentifier(params) { return __awaiter(this, void 0, void 0, function* () { const doc = yield this.messageModel.findOne({ 'project.id': { $eq: params.project.id }, identifier: { $eq: params.identifier } }, { typeOf: 1, identifier: 1, name: 1, about: 1, sender: 1, text: 1, toRecipient: 1 }) .lean() .exec(); if (doc === null) { throw new factory.errors.NotFound(factory.creativeWorkType.EmailMessage); } return doc; }); } deleteByMainEntityOrderNumber(params) { return __awaiter(this, void 0, void 0, function* () { return this.messageModel.deleteMany({ 'project.id': { $eq: params.project.id }, 'mainEntity.orderNumber': { $exists: true, $eq: params.mainEntity.orderNumber } }) .exec() .then((result) => { return { // n: result?.n, // opTime: result.opTime, // ok: result?.ok, // operationTime, deletedCount: result === null || result === void 0 ? void 0 : result.deletedCount }; }); }); } unsetUnnecessaryFields(params) { return __awaiter(this, void 0, void 0, function* () { return this.messageModel.updateMany(params.filter, { $unset: params.$unset }, { timestamps: false }) .exec(); }); } } exports.MessageRepo = MessageRepo;