@chevre/domain 21.28.0-alpha.13 → 21.28.0-alpha.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,64 @@
1
+ // tslint:disable:no-console
2
+ import * as mongoose from 'mongoose';
3
+
4
+ import { chevre } from '../../../lib/index';
5
+
6
+ const project = { id: String(process.env.PROJECT_ID) };
7
+
8
+ async function main() {
9
+ await mongoose.connect(<string>process.env.MONGOLAB_URI, { autoIndex: false });
10
+
11
+ const productModelRepo = await chevre.repository.ProductModel.createInstance(mongoose.connection);
12
+ const result = await productModelRepo.search(
13
+ {
14
+ limit: 100,
15
+ page: 1,
16
+ category: {
17
+ codeValue: { $in: ['Premium'] },
18
+ inCodeSet: { identifier: { $eq: chevre.factory.categoryCode.CategorySetIdentifier.SeatingType } }
19
+ }
20
+ },
21
+ [],
22
+ []
23
+ );
24
+ console.log('result:', result);
25
+
26
+ const productModel = {
27
+ project: {
28
+ id: project.id,
29
+ typeOf: <chevre.factory.organizationType.Project>chevre.factory.organizationType.Project
30
+ },
31
+ typeOf: <'ProductModel'>'ProductModel',
32
+ category: {
33
+ codeValue: 'Premium',
34
+ inCodeSet: {
35
+ identifier: chevre.factory.categoryCode.CategorySetIdentifier.SeatingType,
36
+ typeOf: <'CategoryCodeSet'>'CategoryCodeSet'
37
+ }
38
+ },
39
+ name: { ja: 'プレミアムシート' },
40
+ offers: [{
41
+ typeOf: <chevre.factory.offerType.Offer>chevre.factory.offerType.Offer
42
+ }]
43
+ };
44
+
45
+ const createdModel = await productModelRepo.save({
46
+ $set: productModel
47
+ });
48
+ console.log('created. id:', createdModel);
49
+
50
+ await productModelRepo.save({
51
+ id: createdModel.id,
52
+ $set: productModel
53
+ });
54
+ console.log('updated. id:', createdModel.id);
55
+
56
+ await productModelRepo.deleteById({
57
+ id: createdModel.id
58
+ });
59
+ console.log('deleted. id:', createdModel.id);
60
+ }
61
+
62
+ main()
63
+ .then(console.log)
64
+ .catch(console.error);
@@ -0,0 +1,5 @@
1
+ import { IndexDefinition, IndexOptions, Schema } from 'mongoose';
2
+ declare const modelName = "ProductModel";
3
+ declare const indexes: [d: IndexDefinition, o: IndexOptions][];
4
+ declare function createSchema(): Schema;
5
+ export { modelName, indexes, createSchema };
@@ -0,0 +1,68 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createSchema = exports.indexes = exports.modelName = void 0;
4
+ const mongoose_1 = require("mongoose");
5
+ const writeConcern_1 = require("../writeConcern");
6
+ const settings_1 = require("../../../settings");
7
+ const modelName = 'ProductModel';
8
+ exports.modelName = modelName;
9
+ const schemaDefinition = {
10
+ project: mongoose_1.SchemaTypes.Mixed,
11
+ typeOf: { type: String, required: true },
12
+ category: mongoose_1.SchemaTypes.Mixed,
13
+ name: mongoose_1.SchemaTypes.Mixed,
14
+ offers: mongoose_1.SchemaTypes.Mixed
15
+ };
16
+ const schemaOptions = {
17
+ autoIndex: settings_1.MONGO_AUTO_INDEX,
18
+ autoCreate: false,
19
+ collection: 'productModels',
20
+ id: true,
21
+ read: settings_1.MONGO_READ_PREFERENCE,
22
+ writeConcern: writeConcern_1.writeConcern,
23
+ strict: true,
24
+ strictQuery: false,
25
+ timestamps: {
26
+ createdAt: 'createdAt',
27
+ updatedAt: 'updatedAt'
28
+ },
29
+ toJSON: {
30
+ getters: false,
31
+ virtuals: false,
32
+ minimize: false,
33
+ versionKey: false
34
+ },
35
+ toObject: {
36
+ getters: false,
37
+ virtuals: true,
38
+ minimize: false,
39
+ versionKey: false
40
+ }
41
+ };
42
+ const indexes = [
43
+ [
44
+ { createdAt: 1 },
45
+ { name: 'searchByCreatedAt' }
46
+ ],
47
+ [
48
+ { updatedAt: 1 },
49
+ { name: 'searchByUpdatedAt' }
50
+ ]
51
+ ];
52
+ exports.indexes = indexes;
53
+ /**
54
+ * プロダクトモデルスキーマ
55
+ */
56
+ let schema;
57
+ function createSchema() {
58
+ if (schema === undefined) {
59
+ schema = new mongoose_1.Schema(schemaDefinition, schemaOptions);
60
+ if (settings_1.MONGO_AUTO_INDEX) {
61
+ indexes.forEach((indexParams) => {
62
+ schema === null || schema === void 0 ? void 0 : schema.index(...indexParams);
63
+ });
64
+ }
65
+ }
66
+ return schema;
67
+ }
68
+ exports.createSchema = createSchema;
@@ -0,0 +1,61 @@
1
+ import type { Connection, FilterQuery } from 'mongoose';
2
+ import * as factory from '../factory';
3
+ interface IProductModel {
4
+ id?: string;
5
+ project: {
6
+ id: string;
7
+ typeOf: factory.organizationType.Project;
8
+ };
9
+ typeOf: 'ProductModel';
10
+ category: Pick<factory.categoryCode.ICategoryCode, 'codeValue' | 'inCodeSet'>;
11
+ name: factory.multilingualString;
12
+ offers: {
13
+ typeOf: factory.offerType.Offer;
14
+ eligibleCustomerType?: {
15
+ codeValue: string;
16
+ }[];
17
+ }[];
18
+ }
19
+ type IKeyOfProjection = keyof IProductModel | '_id';
20
+ type ISearchConditions = Pick<factory.product.ISearchConditions, 'id' | 'limit' | 'page' | 'project'> & {
21
+ category?: {
22
+ codeValue?: {
23
+ $in?: string[];
24
+ };
25
+ inCodeSet?: {
26
+ identifier?: {
27
+ $eq?: string;
28
+ };
29
+ };
30
+ };
31
+ };
32
+ /**
33
+ * プロダクトモデルリポジトリ
34
+ */
35
+ export declare class MongoRepository {
36
+ private readonly productModelModel;
37
+ constructor(connection: Connection);
38
+ static CREATE_MONGO_CONDITIONS(params: ISearchConditions): FilterQuery<factory.product.IProduct>[];
39
+ search(conditions: ISearchConditions, inclusion: IKeyOfProjection[], exclusion: IKeyOfProjection[]): Promise<IProductModel[]>;
40
+ deleteById(params: {
41
+ id: string;
42
+ }): Promise<void>;
43
+ /**
44
+ * プロダクトを保管する
45
+ */
46
+ save(params: {
47
+ /**
48
+ * idを指定すれば更新
49
+ */
50
+ id?: string;
51
+ $set: IProductModel;
52
+ }): Promise<{
53
+ id: string;
54
+ }>;
55
+ deleteByProject(params: {
56
+ project: {
57
+ id: string;
58
+ };
59
+ }): Promise<void>;
60
+ }
61
+ export {};
@@ -0,0 +1,138 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __rest = (this && this.__rest) || function (s, e) {
12
+ var t = {};
13
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
14
+ t[p] = s[p];
15
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
16
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
17
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
18
+ t[p[i]] = s[p[i]];
19
+ }
20
+ return t;
21
+ };
22
+ Object.defineProperty(exports, "__esModule", { value: true });
23
+ exports.MongoRepository = void 0;
24
+ const factory = require("../factory");
25
+ const settings_1 = require("../settings");
26
+ const productModel_1 = require("./mongoose/schemas/productModel");
27
+ /**
28
+ * プロダクトモデルリポジトリ
29
+ */
30
+ class MongoRepository {
31
+ constructor(connection) {
32
+ this.productModelModel = connection.model(productModel_1.modelName, (0, productModel_1.createSchema)());
33
+ }
34
+ // tslint:disable-next-line:max-func-body-length
35
+ static CREATE_MONGO_CONDITIONS(params) {
36
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j;
37
+ // MongoDB検索条件
38
+ const andConditions = [];
39
+ const projectIdEq = (_b = (_a = params.project) === null || _a === void 0 ? void 0 : _a.id) === null || _b === void 0 ? void 0 : _b.$eq;
40
+ if (typeof projectIdEq === 'string') {
41
+ andConditions.push({
42
+ 'project.id': { $eq: projectIdEq }
43
+ });
44
+ }
45
+ const idEq = (_c = params.id) === null || _c === void 0 ? void 0 : _c.$eq;
46
+ if (typeof idEq === 'string') {
47
+ andConditions.push({ _id: { $eq: idEq } });
48
+ }
49
+ const idIn = (_d = params.id) === null || _d === void 0 ? void 0 : _d.$in;
50
+ if (Array.isArray(idIn)) {
51
+ andConditions.push({ _id: { $in: idIn } });
52
+ }
53
+ const categoryCodeValueIn = (_f = (_e = params.category) === null || _e === void 0 ? void 0 : _e.codeValue) === null || _f === void 0 ? void 0 : _f.$in;
54
+ if (Array.isArray(categoryCodeValueIn)) {
55
+ andConditions.push({ 'category.codeValue': { $exists: true, $in: categoryCodeValueIn } });
56
+ }
57
+ const categoryInCodeSetIdentifierEq = (_j = (_h = (_g = params.category) === null || _g === void 0 ? void 0 : _g.inCodeSet) === null || _h === void 0 ? void 0 : _h.identifier) === null || _j === void 0 ? void 0 : _j.$eq;
58
+ if (typeof categoryInCodeSetIdentifierEq === 'string') {
59
+ andConditions.push({ 'category.inCodeSet.identifier': { $exists: true, $eq: categoryInCodeSetIdentifierEq } });
60
+ }
61
+ return andConditions;
62
+ }
63
+ search(conditions, inclusion, exclusion) {
64
+ return __awaiter(this, void 0, void 0, function* () {
65
+ const andConditions = MongoRepository.CREATE_MONGO_CONDITIONS(conditions);
66
+ let projection = {};
67
+ if (Array.isArray(inclusion) && inclusion.length > 0) {
68
+ inclusion.forEach((field) => {
69
+ projection[field] = 1;
70
+ });
71
+ }
72
+ else {
73
+ projection = {
74
+ __v: 0,
75
+ createdAt: 0,
76
+ updatedAt: 0
77
+ };
78
+ if (Array.isArray(exclusion) && exclusion.length > 0) {
79
+ exclusion.forEach((field) => {
80
+ projection[field] = 0;
81
+ });
82
+ }
83
+ }
84
+ const query = this.productModelModel.find((andConditions.length > 0) ? { $and: andConditions } : {}, projection);
85
+ if (typeof conditions.limit === 'number' && conditions.limit > 0) {
86
+ const page = (typeof conditions.page === 'number' && conditions.page > 0) ? conditions.page : 1;
87
+ query.limit(conditions.limit)
88
+ .skip(conditions.limit * (page - 1));
89
+ }
90
+ // if (conditions.sort?.productID !== undefined) {
91
+ // query.sort({ productID: conditions.sort.productID });
92
+ // }
93
+ return query.setOptions({ maxTimeMS: settings_1.MONGO_MAX_TIME_MS })
94
+ .exec()
95
+ .then((docs) => docs.map((doc) => doc.toObject()));
96
+ });
97
+ }
98
+ deleteById(params) {
99
+ return __awaiter(this, void 0, void 0, function* () {
100
+ yield this.productModelModel.findOneAndDelete({ _id: params.id })
101
+ .exec();
102
+ });
103
+ }
104
+ /**
105
+ * プロダクトを保管する
106
+ */
107
+ save(params) {
108
+ return __awaiter(this, void 0, void 0, function* () {
109
+ let doc;
110
+ if (typeof params.id === 'string') {
111
+ // 上書き禁止属性を除外
112
+ const _a = params.$set, { id, project, typeOf, offers } = _a, setFields = __rest(_a, ["id", "project", "typeOf", "offers"]);
113
+ doc = yield this.productModelModel.findOneAndUpdate({ _id: { $eq: params.id } }, {
114
+ $set: setFields
115
+ // $unset: params.$unset
116
+ }, { upsert: false, new: true, projection: { _id: 1 } })
117
+ .exec();
118
+ }
119
+ else {
120
+ const _b = params.$set, { id } = _b, createParams = __rest(_b, ["id"]);
121
+ doc = yield this.productModelModel.create(createParams);
122
+ }
123
+ if (doc === null) {
124
+ throw new factory.errors.NotFound(this.productModelModel.modelName);
125
+ }
126
+ return doc.toObject();
127
+ });
128
+ }
129
+ deleteByProject(params) {
130
+ return __awaiter(this, void 0, void 0, function* () {
131
+ yield this.productModelModel.deleteMany({
132
+ 'project.id': { $eq: params.project.id }
133
+ })
134
+ .exec();
135
+ });
136
+ }
137
+ }
138
+ exports.MongoRepository = MongoRepository;
@@ -41,6 +41,7 @@ import type { MongoRepository as SeatRepo } from './repo/place/seat';
41
41
  import type { MongoRepository as SectionRepo } from './repo/place/section';
42
42
  import type { MongoRepository as PriceSpecificationRepo } from './repo/priceSpecification';
43
43
  import type { MongoRepository as ProductRepo } from './repo/product';
44
+ import type { MongoRepository as ProductModelRepo } from './repo/productModel';
44
45
  import type { MongoRepository as ProductOfferRepo } from './repo/productOffer';
45
46
  import type { MongoRepository as ProjectRepo } from './repo/project';
46
47
  import type { MongoRepository as ProjectMakesOfferRepo } from './repo/projectMakesOffer';
@@ -262,6 +263,10 @@ export type Product = ProductRepo;
262
263
  export declare namespace Product {
263
264
  function createInstance(...params: ConstructorParameters<typeof ProductRepo>): Promise<ProductRepo>;
264
265
  }
266
+ export type ProductModel = ProductModelRepo;
267
+ export declare namespace ProductModel {
268
+ function createInstance(...params: ConstructorParameters<typeof ProductModelRepo>): Promise<ProductModelRepo>;
269
+ }
265
270
  export type ProductOffer = ProductOfferRepo;
266
271
  export declare namespace ProductOffer {
267
272
  function createInstance(...params: ConstructorParameters<typeof ProductOfferRepo>): Promise<ProductOfferRepo>;
@@ -9,8 +9,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
9
9
  });
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.Task = exports.StockHolder = exports.ServiceOutputIdentifier = exports.ServiceOutput = exports.SellerPaymentAccepted = exports.Seller = exports.Role = exports.Reservation = exports.ProjectMakesOffer = exports.Project = exports.ProductOffer = exports.Product = exports.PriceSpecification = exports.place = exports.Permit = exports.Person = exports.paymentMethod = exports.PaymentServiceProvider = exports.PaymentService = exports.OwnershipInfo = exports.OrderNumber = exports.OrderInTransaction = exports.Order = exports.Offer = exports.OfferItemCondition = exports.OfferCatalogItem = exports.OfferCatalog = exports.Note = exports.MerchantReturnPolicy = exports.Member = exports.Event = exports.EmailMessage = exports.CustomerType = exports.Customer = exports.CreativeWork = exports.ConfirmationNumber = exports.Comment = exports.Code = exports.CategoryCode = exports.AssetTransaction = exports.Aggregation = exports.AggregateReservation = exports.AggregateOffer = exports.AdditionalProperty = exports.Action = exports.AccountTransaction = exports.AccountTitle = exports.AccountingReport = exports.Account = exports.AcceptedOffer = void 0;
13
- exports.rateLimit = exports.Trip = exports.TransactionNumber = exports.Transaction = exports.Telemetry = void 0;
12
+ exports.StockHolder = exports.ServiceOutputIdentifier = exports.ServiceOutput = exports.SellerPaymentAccepted = exports.Seller = exports.Role = exports.Reservation = exports.ProjectMakesOffer = exports.Project = exports.ProductOffer = exports.ProductModel = exports.Product = exports.PriceSpecification = exports.place = exports.Permit = exports.Person = exports.paymentMethod = exports.PaymentServiceProvider = exports.PaymentService = exports.OwnershipInfo = exports.OrderNumber = exports.OrderInTransaction = exports.Order = exports.Offer = exports.OfferItemCondition = exports.OfferCatalogItem = exports.OfferCatalog = exports.Note = exports.MerchantReturnPolicy = exports.Member = exports.Event = exports.EmailMessage = exports.CustomerType = exports.Customer = exports.CreativeWork = exports.ConfirmationNumber = exports.Comment = exports.Code = exports.CategoryCode = exports.AssetTransaction = exports.Aggregation = exports.AggregateReservation = exports.AggregateOffer = exports.AdditionalProperty = exports.Action = exports.AccountTransaction = exports.AccountTitle = exports.AccountingReport = exports.Account = exports.AcceptedOffer = void 0;
13
+ exports.rateLimit = exports.Trip = exports.TransactionNumber = exports.Transaction = exports.Telemetry = exports.Task = void 0;
14
14
  var AcceptedOffer;
15
15
  (function (AcceptedOffer) {
16
16
  let repo;
@@ -607,6 +607,19 @@ var Product;
607
607
  }
608
608
  Product.createInstance = createInstance;
609
609
  })(Product = exports.Product || (exports.Product = {}));
610
+ var ProductModel;
611
+ (function (ProductModel) {
612
+ let repo;
613
+ function createInstance(...params) {
614
+ return __awaiter(this, void 0, void 0, function* () {
615
+ if (repo === undefined) {
616
+ repo = (yield Promise.resolve().then(() => require('./repo/productModel'))).MongoRepository;
617
+ }
618
+ return new repo(...params);
619
+ });
620
+ }
621
+ ProductModel.createInstance = createInstance;
622
+ })(ProductModel = exports.ProductModel || (exports.ProductModel = {}));
610
623
  var ProductOffer;
611
624
  (function (ProductOffer) {
612
625
  let repo;
package/package.json CHANGED
@@ -110,5 +110,5 @@
110
110
  "postversion": "git push origin --tags",
111
111
  "prepublishOnly": "npm run clean && npm run build && npm test && npm run doc"
112
112
  },
113
- "version": "21.28.0-alpha.13"
113
+ "version": "21.28.0-alpha.14"
114
114
  }
@@ -1,47 +0,0 @@
1
- // tslint:disable:no-console
2
- import * as mongoose from 'mongoose';
3
-
4
- import { chevre } from '../../../lib/index';
5
-
6
- const project = { id: String(process.env.PROJECT_ID) };
7
- const CLIENT_ID = 'xxxx';
8
-
9
- async function main() {
10
- await mongoose.connect(<string>process.env.MONGOLAB_URI, { autoIndex: false });
11
-
12
- const projectMakesOfferRepo = await chevre.repository.ProjectMakesOffer.createInstance(mongoose.connection);
13
- const result = await projectMakesOfferRepo.search({
14
- limit: 100,
15
- page: 1,
16
- offeredBy: { id: { $eq: project.id } },
17
- availableAtOrFrom: { id: { $eq: CLIENT_ID } }
18
- });
19
- console.log('result:', result);
20
-
21
- try {
22
- await projectMakesOfferRepo.create({
23
- availableAtOrFrom: { id: CLIENT_ID },
24
- offeredBy: { id: project.id }
25
- });
26
- console.log('offer created');
27
- } catch (error) {
28
- console.error(error);
29
- }
30
-
31
- await projectMakesOfferRepo.updateOne({
32
- availableAtOrFrom: { id: CLIENT_ID },
33
- eligibleCustomerType: [{ codeValue: 'Enduser' }],
34
- offeredBy: { id: project.id }
35
- });
36
- console.log('offer updated');
37
-
38
- await projectMakesOfferRepo.deleteOne({
39
- availableAtOrFrom: { id: CLIENT_ID },
40
- offeredBy: { id: project.id }
41
- });
42
- console.log('offer deleted');
43
- }
44
-
45
- main()
46
- .then(console.log)
47
- .catch(console.error);