@chevre/domain 21.18.0-alpha.0 → 21.18.0-alpha.2

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,36 @@
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 notificationService = await chevre.service.notification.createService();
12
+
13
+ // await notificationService.report2developers(
14
+ // 'xxx',
15
+ // 'xxx'
16
+ // )({ accessToken: String(process.env.LINE_NOTIFY_ACCESS_TOKEN) });
17
+
18
+ await notificationService.triggerWebhook({
19
+ typeOf: chevre.factory.actionType.InformAction,
20
+ project: { id: project.id, typeOf: chevre.factory.organizationType.Project },
21
+ agent: { id: project.id, typeOf: chevre.factory.organizationType.Project },
22
+ recipient: {
23
+ id: 'xxx',
24
+ url: 'https://example.com',
25
+ typeOf: chevre.factory.creativeWorkType.WebApplication
26
+ },
27
+ object: { sample: 'sample' }
28
+ })({
29
+ action: await chevre.repository.Action.createInstance(mongoose.connection),
30
+ useFetchAPI: true
31
+ });
32
+ }
33
+
34
+ main()
35
+ .then(console.log)
36
+ .catch(console.error);
@@ -0,0 +1,45 @@
1
+ // tslint:disable:no-console
2
+ const url = String(process.env.LINE_NOTIFY_URL);
3
+ const LINE_NOTIFY_ACCESS_TOKEN = String(process.env.LINE_NOTIFY_ACCESS_TOKEN);
4
+ const TIMEOUT = 5000;
5
+ const MESSAGE = 'sample message';
6
+
7
+ async function main() {
8
+ try {
9
+ const form = new FormData();
10
+ form.set('message', `${MESSAGE} ${(new Date()).toString()}`);
11
+
12
+ const res = await fetch(
13
+ url,
14
+ {
15
+ signal: AbortSignal.timeout(TIMEOUT),
16
+ method: 'POST',
17
+ headers: {
18
+ Authorization: `Bearer ${LINE_NOTIFY_ACCESS_TOKEN}`
19
+ },
20
+ body: form
21
+ }
22
+ );
23
+ const result = await res.json();
24
+ console.log('result', result);
25
+ } catch (err) {
26
+ console.error(err);
27
+ if (err.name === 'TimeoutError') {
28
+ console.error('Timeout: It took more than 5 seconds to get the result!');
29
+ } else if (err.name === 'AbortError') {
30
+ console.error('Fetch aborted by user action (browser stop button, closing tab, etc.');
31
+ } else if (err.name === 'TypeError') {
32
+ console.error('AbortSignal.timeout() method is not supported');
33
+ } else {
34
+ // A network error, or some other problem.
35
+ console.error(`Error: type: ${err.name}, message: ${err.message}`);
36
+ }
37
+ }
38
+
39
+ }
40
+
41
+ main()
42
+ .then(() => {
43
+ console.log('success!');
44
+ })
45
+ .catch(console.error);
@@ -1,8 +1,9 @@
1
1
  import * as factory from '../factory';
2
2
  import type { MongoRepository as ActionRepo } from '../repo/action';
3
3
  import type { MongoRepository as ProjectRepo } from '../repo/project';
4
- export type Operation<T> = (repos: {
4
+ export type IReport2developersOperation<T> = (repos: {
5
5
  accessToken: string;
6
+ useFetchAPI: boolean;
6
7
  }) => Promise<T>;
7
8
  /**
8
9
  * Eメールメッセージを送信する
@@ -16,7 +17,13 @@ export declare function sendEmailMessage(params: factory.action.transfer.send.me
16
17
  * 開発者に報告する
17
18
  * https://notify-bot.line.me/doc/ja/
18
19
  */
19
- export declare function report2developers(subject: string, content: string, imageThumbnail?: string, imageFullsize?: string): Operation<void>;
20
+ export declare function report2developers({ subject, content, imageThumbnail, imageFullsize }: {
21
+ subject: string;
22
+ content: string;
23
+ imageThumbnail?: string;
24
+ imageFullsize?: string;
25
+ }): IReport2developersOperation<void>;
20
26
  export declare function triggerWebhook(params: factory.task.IData<factory.taskName.TriggerWebhook>): (repos: {
21
27
  action: ActionRepo;
28
+ useFetchAPI: boolean;
22
29
  }) => Promise<void>;
@@ -121,8 +121,10 @@ exports.sendEmailMessage = sendEmailMessage;
121
121
  * 開発者に報告する
122
122
  * https://notify-bot.line.me/doc/ja/
123
123
  */
124
- function report2developers(subject, content, imageThumbnail, imageFullsize) {
124
+ function report2developers({ subject, content, imageThumbnail, imageFullsize }) {
125
+ // tslint:disable-next-line:max-func-body-length
125
126
  return (repos) => __awaiter(this, void 0, void 0, function* () {
127
+ var _a;
126
128
  const LINE_NOTIFY_URL = credentials_1.credentials.lineNotify.url;
127
129
  if (LINE_NOTIFY_URL === undefined) {
128
130
  throw new Error('Environment variable LINE_NOTIFY_URL not set');
@@ -131,31 +133,83 @@ function report2developers(subject, content, imageThumbnail, imageFullsize) {
131
133
  ${subject}
132
134
  --------
133
135
  ${content}`;
134
- // LINE通知APIにPOST
135
- const formData = Object.assign(Object.assign({ message: message }, (typeof imageThumbnail === 'string') ? { imageThumbnail } : undefined), (typeof imageFullsize === 'string') ? { imageFullsize } : undefined);
136
- return new Promise((resolve, reject) => {
137
- var _a;
138
- request.post({
139
- url: LINE_NOTIFY_URL,
140
- auth: { bearer: repos.accessToken },
141
- form: formData,
142
- json: true,
143
- timeout: (_a = settings_1.settings.webhook) === null || _a === void 0 ? void 0 : _a.timeout
144
- }, (error, response, body) => {
145
- if (error !== null) {
146
- reject(error);
136
+ if (repos.useFetchAPI) {
137
+ try {
138
+ const form = new FormData();
139
+ form.set('message', message);
140
+ if (typeof imageThumbnail === 'string') {
141
+ form.set('imageThumbnail', imageThumbnail);
142
+ }
143
+ if (typeof imageFullsize === 'string') {
144
+ form.set('imageFullsize', imageFullsize);
145
+ }
146
+ const res = yield fetch(LINE_NOTIFY_URL, Object.assign({ method: 'POST', headers: {
147
+ Authorization: `Bearer ${repos.accessToken}`
148
+ }, body: form }, (typeof ((_a = settings_1.settings.webhook) === null || _a === void 0 ? void 0 : _a.timeout) === 'number')
149
+ ? { signal: AbortSignal.timeout(settings_1.settings.webhook.timeout) }
150
+ : undefined));
151
+ let body;
152
+ try {
153
+ body = yield res.json();
154
+ }
155
+ catch (error) {
156
+ // no op
157
+ }
158
+ switch (res.status) {
159
+ case http_status_1.OK:
160
+ break;
161
+ default:
162
+ throw new Error(`${res.status} ${body === null || body === void 0 ? void 0 : body.message}`);
163
+ }
164
+ }
165
+ catch (err) {
166
+ if (err.name === 'TimeoutError') {
167
+ // tslint:disable-next-line:no-console
168
+ console.error('report2developers: Timeout: It took more than 5 seconds to get the result!', err);
169
+ }
170
+ else if (err.name === 'AbortError') {
171
+ // tslint:disable-next-line:no-console
172
+ console.error('report2developers: Fetch aborted by user action (browser stop button, closing tab, etc.', err);
173
+ }
174
+ else if (err.name === 'TypeError') {
175
+ // tslint:disable-next-line:no-console
176
+ console.error('report2developers: AbortSignal.timeout() method is not supported', err);
147
177
  }
148
178
  else {
149
- switch (response.statusCode) {
150
- case http_status_1.OK:
151
- resolve();
152
- break;
153
- default:
154
- reject(new Error(body.message));
155
- }
179
+ // A network error, or some other problem.
180
+ // tslint:disable-next-line:no-console
181
+ console.error(`report2developers: Error: type: ${err.name}, message: ${err.message}`, err);
156
182
  }
183
+ throw err;
184
+ }
185
+ }
186
+ else {
187
+ // LINE通知APIにPOST
188
+ const formData = Object.assign(Object.assign({ message: message }, (typeof imageThumbnail === 'string') ? { imageThumbnail } : undefined), (typeof imageFullsize === 'string') ? { imageFullsize } : undefined);
189
+ return new Promise((resolve, reject) => {
190
+ var _a;
191
+ request.post({
192
+ url: LINE_NOTIFY_URL,
193
+ auth: { bearer: repos.accessToken },
194
+ form: formData,
195
+ json: true,
196
+ timeout: (_a = settings_1.settings.webhook) === null || _a === void 0 ? void 0 : _a.timeout
197
+ }, (error, response, body) => {
198
+ if (error !== null) {
199
+ reject(error);
200
+ }
201
+ else {
202
+ switch (response.statusCode) {
203
+ case http_status_1.OK:
204
+ resolve();
205
+ break;
206
+ default:
207
+ reject(new Error(body.message));
208
+ }
209
+ }
210
+ });
157
211
  });
158
- });
212
+ }
159
213
  });
160
214
  }
161
215
  exports.report2developers = report2developers;
@@ -200,54 +254,107 @@ function sleep(waitTime) {
200
254
  });
201
255
  }
202
256
  function processInformAction(params) {
257
+ // tslint:disable-next-line:max-func-body-length
203
258
  return (repos) => __awaiter(this, void 0, void 0, function* () {
204
- var _a, _b;
259
+ var _a, _b, _c;
205
260
  // アクション開始
206
261
  const action = yield repos.action.start(params);
207
262
  let result = {};
208
263
  try {
209
264
  if (typeof ((_a = params.recipient) === null || _a === void 0 ? void 0 : _a.url) === 'string') {
210
265
  const url = params.recipient.url;
211
- yield new Promise((resolve, reject) => {
212
- var _a;
213
- request.post({
214
- url: url,
215
- body: {
216
- data: params.object
217
- },
218
- json: true,
219
- timeout: (_a = settings_1.settings.webhook) === null || _a === void 0 ? void 0 : _a.timeout
220
- }, (error, response, body) => {
221
- if (error instanceof Error) {
222
- reject(error);
266
+ if (repos.useFetchAPI) {
267
+ try {
268
+ const res = yield fetch(url, Object.assign({ method: 'POST', headers: {
269
+ 'Content-Type': 'application/json'
270
+ }, body: JSON.stringify({
271
+ data: params.object
272
+ }) }, (typeof ((_b = settings_1.settings.webhook) === null || _b === void 0 ? void 0 : _b.timeout) === 'number')
273
+ ? { signal: AbortSignal.timeout(settings_1.settings.webhook.timeout) }
274
+ : undefined));
275
+ let body;
276
+ try {
277
+ body = yield res.text();
278
+ }
279
+ catch (error) {
280
+ // no op
281
+ }
282
+ switch (res.status) {
283
+ case http_status_1.OK:
284
+ case http_status_1.CREATED:
285
+ case http_status_1.ACCEPTED:
286
+ case http_status_1.NO_CONTENT:
287
+ result = {
288
+ statusCode: res.status,
289
+ useFetchAPI: repos.useFetchAPI
290
+ };
291
+ break;
292
+ default:
293
+ throw new Error(`statusCode: ${res.status} body: ${body}`);
294
+ }
295
+ // return res.json();
296
+ }
297
+ catch (err) {
298
+ if (err.name === 'TimeoutError') {
299
+ // tslint:disable-next-line:no-console
300
+ console.error('report2developers: Timeout: It took more than 5 seconds to get the result!', err);
301
+ }
302
+ else if (err.name === 'AbortError') {
303
+ // tslint:disable-next-line:no-console
304
+ console.error('report2developers: Fetch aborted by user action (browser stop button, closing tab, etc.', err);
305
+ }
306
+ else if (err.name === 'TypeError') {
307
+ // tslint:disable-next-line:no-console
308
+ console.error('report2developers: AbortSignal.timeout() method is not supported', err);
223
309
  }
224
310
  else {
225
- switch (response.statusCode) {
226
- case http_status_1.OK:
227
- case http_status_1.CREATED:
228
- case http_status_1.ACCEPTED:
229
- case http_status_1.NO_CONTENT:
230
- result = {
231
- statusCode: response.statusCode
232
- // body: body
233
- };
234
- resolve();
235
- break;
236
- default:
237
- reject({
238
- statusCode: response.statusCode,
239
- body: body
240
- });
241
- }
311
+ // A network error, or some other problem.
312
+ // tslint:disable-next-line:no-console
313
+ console.error(`report2developers: Error: type: ${err.name}, message: ${err.message}`, err);
242
314
  }
315
+ throw err;
316
+ }
317
+ }
318
+ else {
319
+ yield new Promise((resolve, reject) => {
320
+ var _a;
321
+ request.post({
322
+ url: url,
323
+ body: {
324
+ data: params.object
325
+ },
326
+ json: true,
327
+ timeout: (_a = settings_1.settings.webhook) === null || _a === void 0 ? void 0 : _a.timeout
328
+ }, (error, response, body) => {
329
+ if (error instanceof Error) {
330
+ reject(error);
331
+ }
332
+ else {
333
+ switch (response.statusCode) {
334
+ case http_status_1.OK:
335
+ case http_status_1.CREATED:
336
+ case http_status_1.ACCEPTED:
337
+ case http_status_1.NO_CONTENT:
338
+ result = {
339
+ statusCode: response.statusCode,
340
+ useFetchAPI: repos.useFetchAPI
341
+ // body: body
342
+ };
343
+ resolve();
344
+ break;
345
+ default:
346
+ reject(new Error(`statusCode: ${response.statusCode} body: ${body}`));
347
+ }
348
+ }
349
+ });
243
350
  });
244
- });
351
+ }
245
352
  }
246
353
  }
247
354
  catch (error) {
248
355
  let throwsError = true;
249
356
  // プロジェクト固有の特別対応
250
- if (error.statusCode === http_status_1.INTERNAL_SERVER_ERROR && ((_b = error.body) === null || _b === void 0 ? void 0 : _b.message) === USERNAME_ARGUMENT_REQUIRED_MESSAGE) {
357
+ if (error.statusCode === http_status_1.INTERNAL_SERVER_ERROR && ((_c = error.body) === null || _c === void 0 ? void 0 : _c.message) === USERNAME_ARGUMENT_REQUIRED_MESSAGE) {
251
358
  throwsError = false;
252
359
  }
253
360
  if (throwsError) {
@@ -10,6 +10,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.call = void 0;
13
+ const settings_1 = require("../../settings");
13
14
  const action_1 = require("../../repo/action");
14
15
  const NotificationService = require("../notification");
15
16
  /**
@@ -17,8 +18,10 @@ const NotificationService = require("../notification");
17
18
  */
18
19
  function call(data) {
19
20
  return (settings) => __awaiter(this, void 0, void 0, function* () {
20
- const actionRepo = new action_1.MongoRepository(settings.connection);
21
- yield NotificationService.triggerWebhook(data)({ action: actionRepo });
21
+ yield NotificationService.triggerWebhook(data)({
22
+ action: new action_1.MongoRepository(settings.connection),
23
+ useFetchAPI: settings_1.USE_FETCH_API
24
+ });
22
25
  });
23
26
  }
24
27
  exports.call = call;
@@ -143,8 +143,9 @@ function abort(params) {
143
143
  }
144
144
  // 開発者へ報告
145
145
  const message = (0, factory_1.task2lineNotify)({ task: abortedTask });
146
- yield notification.report2developers(message.subject, message.content)({
147
- accessToken: credentials_1.credentials.lineNotify.accessTokenAlert
146
+ yield notification.report2developers({ subject: message.subject, content: message.content })({
147
+ accessToken: credentials_1.credentials.lineNotify.accessTokenAlert,
148
+ useFetchAPI: settings_1.USE_FETCH_API
148
149
  });
149
150
  }
150
151
  });
@@ -155,18 +156,15 @@ function notifyAbortedTasks(params) {
155
156
  const abortedTasks = yield repos.task.search(Object.assign({ statuses: [factory.taskStatus.Aborted], dateAborted: { $gte: params.dateAbortedGte } }, (settings_1.ABORTED_TASKS_WITHOUT_REPORT.length > 0)
156
157
  ? { name: { $nin: settings_1.ABORTED_TASKS_WITHOUT_REPORT } }
157
158
  : undefined));
158
- // 中止を報告しないタスク以外にフィルター
159
- // abortedTasks = abortedTasks.filter((task) => {
160
- // return !ABORTED_TASKS_WITHOUT_REPORT.includes(task.name);
161
- // });
162
159
  if (abortedTasks.length > 0) {
163
160
  if (notification === undefined) {
164
161
  notification = yield Promise.resolve().then(() => require('./notification'));
165
162
  }
166
163
  // 開発者へ報告
167
164
  const message = (0, factory_1.tasks2lineNotify)({ tasks: abortedTasks });
168
- yield notification.report2developers(message.subject, message.content)({
169
- accessToken: credentials_1.credentials.lineNotify.accessTokenAlert
165
+ yield notification.report2developers({ subject: message.subject, content: message.content })({
166
+ accessToken: credentials_1.credentials.lineNotify.accessTokenAlert,
167
+ useFetchAPI: settings_1.USE_FETCH_API
170
168
  });
171
169
  }
172
170
  });
@@ -40,6 +40,7 @@ export declare const USE_DELETE_EVENT_BY_ORDER: boolean;
40
40
  export declare const USE_ORDER_PAYMENT_DUE_ON_PLACED: boolean;
41
41
  export declare const USE_OPTIMIZE_TICKET_OFFER: boolean;
42
42
  export declare const USE_ORDER_PAYMENT_METHOD_TYPE_OF: boolean;
43
+ export declare const USE_FETCH_API: boolean;
43
44
  export declare const MONGO_MAX_TIME_MS: number;
44
45
  export declare const MONGO_READ_PREFERENCE: string;
45
46
  export declare const MONGO_AUTO_INDEX: boolean;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.settings = exports.MONGO_AUTO_INDEX = exports.MONGO_READ_PREFERENCE = exports.MONGO_MAX_TIME_MS = exports.USE_ORDER_PAYMENT_METHOD_TYPE_OF = exports.USE_OPTIMIZE_TICKET_OFFER = exports.USE_ORDER_PAYMENT_DUE_ON_PLACED = exports.USE_DELETE_EVENT_BY_ORDER = exports.USE_OBJECT_AS_PAY_TRANSACTION_AMOUNT = exports.USE_ASSET_TRANSACTION_SYNC_PROCESSING = exports.DEFAULT_TASKS_EXPORT_AGENT_NAME = exports.DEFAULT_SENDER_EMAIL = exports.TRANSACTION_CANCELED_STORAGE_PERIOD_IN_DAYS = exports.TRANSACTION_CONFIRMED_STORAGE_PERIOD_IN_DAYS = exports.ASSET_TRANSACTION_STORAGE_PERIOD_IN_DAYS = exports.MAX_NUM_CREDIT_CARD_PAYMENT_METHOD = exports.ABORTED_TASKS_WITHOUT_REPORT = exports.TRIGGER_WEBHOOK_RETRY_INTERVAL_IN_MS = exports.TRIGGER_WEBHOOK_MAX_RETRY_COUNT = void 0;
3
+ exports.settings = exports.MONGO_AUTO_INDEX = exports.MONGO_READ_PREFERENCE = exports.MONGO_MAX_TIME_MS = exports.USE_FETCH_API = exports.USE_ORDER_PAYMENT_METHOD_TYPE_OF = exports.USE_OPTIMIZE_TICKET_OFFER = exports.USE_ORDER_PAYMENT_DUE_ON_PLACED = exports.USE_DELETE_EVENT_BY_ORDER = exports.USE_OBJECT_AS_PAY_TRANSACTION_AMOUNT = exports.USE_ASSET_TRANSACTION_SYNC_PROCESSING = exports.DEFAULT_TASKS_EXPORT_AGENT_NAME = exports.DEFAULT_SENDER_EMAIL = exports.TRANSACTION_CANCELED_STORAGE_PERIOD_IN_DAYS = exports.TRANSACTION_CONFIRMED_STORAGE_PERIOD_IN_DAYS = exports.ASSET_TRANSACTION_STORAGE_PERIOD_IN_DAYS = exports.MAX_NUM_CREDIT_CARD_PAYMENT_METHOD = exports.ABORTED_TASKS_WITHOUT_REPORT = exports.TRIGGER_WEBHOOK_RETRY_INTERVAL_IN_MS = exports.TRIGGER_WEBHOOK_MAX_RETRY_COUNT = void 0;
4
4
  const factory = require("./factory");
5
5
  const transactionWebhookUrls = (typeof process.env.INFORM_TRANSACTION_URL === 'string')
6
6
  ? process.env.INFORM_TRANSACTION_URL.split(' ')
@@ -64,6 +64,7 @@ exports.USE_DELETE_EVENT_BY_ORDER = process.env.USE_DELETE_EVENT_BY_ORDER === '1
64
64
  exports.USE_ORDER_PAYMENT_DUE_ON_PLACED = process.env.USE_ORDER_PAYMENT_DUE_ON_PLACED === '1';
65
65
  exports.USE_OPTIMIZE_TICKET_OFFER = process.env.USE_OPTIMIZE_TICKET_OFFER === '1';
66
66
  exports.USE_ORDER_PAYMENT_METHOD_TYPE_OF = process.env.USE_ORDER_PAYMENT_METHOD_TYPE_OF === '1';
67
+ exports.USE_FETCH_API = process.env.USE_FETCH_API === '1';
67
68
  exports.MONGO_MAX_TIME_MS = (typeof process.env.MONGO_MAX_TIME_MS === 'string')
68
69
  ? Number(process.env.MONGO_MAX_TIME_MS)
69
70
  // tslint:disable-next-line:no-magic-numbers
package/package.json CHANGED
@@ -43,8 +43,7 @@
43
43
  "@types/lodash.difference": "^4.5.6",
44
44
  "@types/mocha": "^5.2.7",
45
45
  "@types/moment-timezone": "^0.5.30",
46
- "@types/nock": "^9.3.1",
47
- "@types/node": "14.18.42",
46
+ "@types/node": "18.19.2",
48
47
  "@types/power-assert": "^1.5.3",
49
48
  "@types/pug": "^2.0.4",
50
49
  "@types/request": "^2.48.5",
@@ -59,13 +58,12 @@
59
58
  "json2csv": "4.5.4",
60
59
  "mocha": "^5.2.0",
61
60
  "mongoose": "7.0.5",
62
- "nock": "^9.6.1",
61
+ "nock": "13.4.0",
63
62
  "nyc": "^15.1.0",
64
63
  "power-assert": "^1.6.1",
65
64
  "redis": "4.6.5",
66
- "request-promise-native": "^1.0.9",
67
65
  "rimraf": "^2.7.1",
68
- "sinon": "^4.5.0",
66
+ "sinon": "4.5.0",
69
67
  "sinon-mongoose": "^2.3.0",
70
68
  "ts-node": "^10.9.1",
71
69
  "tslint": "^6.1.3",
@@ -78,7 +76,7 @@
78
76
  "redis": "^4.6.5"
79
77
  },
80
78
  "engines": {
81
- "node": ">=14.0.0",
79
+ "node": ">=18.0.0",
82
80
  "npm": ">=6.0.0"
83
81
  },
84
82
  "keywords": [],
@@ -117,5 +115,5 @@
117
115
  "postversion": "git push origin --tags",
118
116
  "prepublishOnly": "npm run clean && npm run build && npm test && npm run doc"
119
117
  },
120
- "version": "21.18.0-alpha.0"
118
+ "version": "21.18.0-alpha.2"
121
119
  }