@chevre/domain
Version:
Chevre Domain Library for Node.js
243 lines (242 loc) • 11.1 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.AuthorizationRepo = void 0;
const moment = require("moment");
const uuid = require("uuid");
const factory = require("../factory");
const authorization_1 = require("./mongoose/schemas/authorization");
const settings_1 = require("../settings");
const AVAILABLE_PROJECT_FIELDS = [
'project',
'typeOf',
'code',
'object',
'validFrom',
'validUntil',
'audience',
'author',
'issuedBy'
];
/**
* 承認リポジトリ
*/
class AuthorizationRepo {
constructor(connection) {
this.authorizationModel = connection.model(authorization_1.modelName, (0, authorization_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;
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 } });
}
const idIn = (_d = params.id) === null || _d === void 0 ? void 0 : _d.$in;
if (Array.isArray(idIn)) {
andConditions.push({ _id: { $in: idIn } });
}
const codeEq = (_e = params.code) === null || _e === void 0 ? void 0 : _e.$eq;
if (typeof codeEq === 'string') {
andConditions.push({ code: { $eq: codeEq } });
}
const codeIn = (_f = params.code) === null || _f === void 0 ? void 0 : _f.$in;
if (Array.isArray(codeIn)) {
andConditions.push({ code: { $in: codeIn } });
}
const objectOrderNumberEq = (_h = (_g = params.object) === null || _g === void 0 ? void 0 : _g.orderNumber) === null || _h === void 0 ? void 0 : _h.$eq;
if (typeof objectOrderNumberEq === 'string') {
andConditions.push({ 'object.orderNumber': { $exists: true, $eq: objectOrderNumberEq } });
}
// tslint:disable-next-line:no-single-line-block-comment
/* istanbul ignore else */
const object = params.object;
if (object !== undefined) {
// tslint:disable-next-line:no-single-line-block-comment
/* istanbul ignore else */
if (Array.isArray(object.ids)) {
andConditions.push({
'object.id': { $exists: true, $in: object.ids }
});
}
// tslint:disable-next-line:no-single-line-block-comment
/* istanbul ignore else */
if (Array.isArray(object.typeOfs)) {
andConditions.push({
'object.typeOf': { $exists: true, $in: object.typeOfs }
});
}
// tslint:disable-next-line:no-single-line-block-comment
/* istanbul ignore else */
if (object.typeOfGood !== undefined) {
// tslint:disable-next-line:no-single-line-block-comment
/* istanbul ignore else */
if (Array.isArray(object.typeOfGood.ids)) {
andConditions.push({
'object.typeOfGood.id': { $exists: true, $in: object.typeOfGood.ids }
});
}
// tslint:disable-next-line:no-single-line-block-comment
/* istanbul ignore else */
if (Array.isArray(object.typeOfGood.typeOfs)) {
andConditions.push({
'object.typeOfGood.typeOf': { $exists: true, $in: object.typeOfGood.typeOfs }
});
}
}
}
if (params.validFrom instanceof Date) {
andConditions.push({ validUntil: { $gte: params.validFrom } });
}
if (params.validThrough instanceof Date) {
andConditions.push({ validFrom: { $lte: params.validThrough } });
}
const audienceIdeEq = (_k = (_j = params.audience) === null || _j === void 0 ? void 0 : _j.id) === null || _k === void 0 ? void 0 : _k.$eq;
if (typeof audienceIdeEq === 'string') {
andConditions.push({ 'audience.id': { $exists: true, $eq: audienceIdeEq } });
}
return andConditions;
}
/**
* コードを発行する
*/
publish(params) {
return __awaiter(this, void 0, void 0, function* () {
const saveParams = params.map(({ project, object, validFrom, expiresInSeconds, audience, author, issuedBy }) => {
const code = uuid.v4();
return { project, code, object, validFrom, expiresInSeconds, audience, author, issuedBy };
});
return this.save(saveParams);
});
}
/**
* コードで有効な承認を参照する
*/
findValidOneByCode(params) {
return __awaiter(this, void 0, void 0, function* () {
const now = new Date();
const doc = yield this.authorizationModel.findOne({
'project.id': { $eq: params.project.id },
code: { $eq: String(params.code) },
validFrom: { $lte: now },
validUntil: { $gte: now }
}, {
_id: 0,
id: { $toString: '$_id' },
object: 1, typeOf: 1, audience: 1, issuedBy: 1
})
.lean()
.exec();
if (doc === null) {
throw new factory.errors.NotFound(this.authorizationModel.modelName);
}
const { id, object, typeOf, audience, issuedBy } = doc;
return Object.assign(Object.assign({ id, object, typeOf }, (typeof (issuedBy === null || issuedBy === void 0 ? void 0 : issuedBy.id) === 'string') ? { issuedBy } : undefined), (typeof (audience === null || audience === void 0 ? void 0 : audience.id) === 'string') ? { audience } : undefined);
});
}
/**
* 有効な承認を参照する
*/
findValidOneById(params) {
return __awaiter(this, void 0, void 0, function* () {
const now = new Date();
const doc = yield this.authorizationModel.findOne({
'project.id': { $eq: params.project.id },
_id: { $eq: String(params.id) },
validFrom: { $lte: now },
validUntil: { $gte: now }
}, { object: 1, _id: 0 })
.lean() // projection的にleanで十分
.exec();
if (doc === null) {
throw new factory.errors.NotFound(this.authorizationModel.modelName);
}
return doc;
});
}
projectFields(params, inclusion) {
return __awaiter(this, void 0, void 0, function* () {
var _a;
const conditions = AuthorizationRepo.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));
}
const projection = Object.assign({ _id: 0, id: { $toString: '$_id' } }, Object.fromEntries(positiveProjectionFields.map((key) => ([key, 1]))));
const query = this.authorizationModel.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.validFrom) === 'number') {
query.sort({ validFrom: params.sort.validFrom });
}
return query.setOptions({ maxTimeMS: settings_1.MONGO_MAX_TIME_MS })
.lean()
.exec();
});
}
/**
* 有効期限を一定期間過ぎた承認を削除する
*/
deleteValidUntilPassedCertainPeriod(params) {
return __awaiter(this, void 0, void 0, function* () {
yield this.authorizationModel.deleteMany({
validUntil: {
$exists: true,
$lt: params.$lt
}
})
.exec();
});
}
unsetUnnecessaryFields(params) {
return __awaiter(this, void 0, void 0, function* () {
return this.authorizationModel.updateMany(params.filter, { $unset: params.$unset }, { timestamps: false })
.exec();
});
}
/**
* コードを保管する
*/
save(params) {
return __awaiter(this, void 0, void 0, function* () {
if (params.length > 0) {
const docs = params.map(({ project, code, object, validFrom, expiresInSeconds, audience, author, issuedBy }) => {
const validUntil = moment(validFrom)
.add(expiresInSeconds, 'seconds')
.toDate();
return Object.assign(Object.assign({ project, typeOf: 'Authorization', author,
code,
object,
validFrom,
validUntil }, (typeof (audience === null || audience === void 0 ? void 0 : audience.id) === 'string') ? { audience } : undefined), (typeof (issuedBy === null || issuedBy === void 0 ? void 0 : issuedBy.id) === 'string') ? { issuedBy } : undefined);
});
const result = yield this.authorizationModel.insertMany(docs, { ordered: false, rawResult: true });
if (result.insertedCount !== docs.length) {
throw new factory.errors.Internal('all codes not saved');
}
// return result.ops;
return docs;
}
else {
return [];
}
});
}
}
exports.AuthorizationRepo = AuthorizationRepo;