pg-mvc-service 1.0.0

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.
Files changed (56) hide show
  1. package/README.md +1 -0
  2. package/dist/PoolManager.js +57 -0
  3. package/dist/Service.js +257 -0
  4. package/dist/clients/AwsS3Client.js +249 -0
  5. package/dist/clients/Base64Client.js +153 -0
  6. package/dist/clients/EncryptClient.js +85 -0
  7. package/dist/clients/StringClient.js +13 -0
  8. package/dist/documents/Swagger.js +94 -0
  9. package/dist/exceptions/Exception.js +53 -0
  10. package/dist/index.js +16 -0
  11. package/dist/models/MigrateDatabase.js +138 -0
  12. package/dist/models/MigrateRollback.js +146 -0
  13. package/dist/models/MigrateTable.js +51 -0
  14. package/dist/models/SqlUtils/SelectExpression.js +92 -0
  15. package/dist/models/SqlUtils/ValidateValueUtil.js +250 -0
  16. package/dist/models/SqlUtils/WhereExpression.js +256 -0
  17. package/dist/models/TableDoc.js +353 -0
  18. package/dist/models/TableModel.js +636 -0
  19. package/dist/models/Type.js +2 -0
  20. package/dist/models/Utils/DateTimeUtil.js +134 -0
  21. package/dist/models/Utils/NumberUtil.js +28 -0
  22. package/dist/models/Utils/StringUtil.js +31 -0
  23. package/dist/models/ValidateClient.js +164 -0
  24. package/dist/models/index.js +14 -0
  25. package/dist/reqestResponse/ReqResType.js +196 -0
  26. package/dist/reqestResponse/RequestType.js +742 -0
  27. package/dist/reqestResponse/ResponseType.js +380 -0
  28. package/index.d.ts +306 -0
  29. package/package.json +36 -0
  30. package/src/PoolManager.ts +48 -0
  31. package/src/Service.ts +251 -0
  32. package/src/clients/AwsS3Client.ts +229 -0
  33. package/src/clients/Base64Client.ts +155 -0
  34. package/src/clients/EncryptClient.ts +100 -0
  35. package/src/clients/StringClient.ts +14 -0
  36. package/src/documents/Swagger.ts +111 -0
  37. package/src/exceptions/Exception.ts +54 -0
  38. package/src/index.ts +7 -0
  39. package/src/models/MigrateDatabase.ts +135 -0
  40. package/src/models/MigrateRollback.ts +151 -0
  41. package/src/models/MigrateTable.ts +56 -0
  42. package/src/models/SqlUtils/SelectExpression.ts +97 -0
  43. package/src/models/SqlUtils/ValidateValueUtil.ts +270 -0
  44. package/src/models/SqlUtils/WhereExpression.ts +286 -0
  45. package/src/models/TableDoc.ts +360 -0
  46. package/src/models/TableModel.ts +713 -0
  47. package/src/models/Type.ts +59 -0
  48. package/src/models/Utils/DateTimeUtil.ts +146 -0
  49. package/src/models/Utils/NumberUtil.ts +23 -0
  50. package/src/models/Utils/StringUtil.ts +33 -0
  51. package/src/models/ValidateClient.ts +182 -0
  52. package/src/models/index.ts +7 -0
  53. package/src/reqestResponse/ReqResType.ts +242 -0
  54. package/src/reqestResponse/RequestType.ts +851 -0
  55. package/src/reqestResponse/ResponseType.ts +418 -0
  56. package/tsconfig.json +14 -0
package/README.md ADDED
@@ -0,0 +1 @@
1
+ # npm-pack_pg-model-controller-service
@@ -0,0 +1,57 @@
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
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ // PoolManager.ts
13
+ const pg_1 = require("pg");
14
+ class PoolManager {
15
+ static getPool(user, host, database, password, port, isSslConnect) {
16
+ const key = `${user}@${host}/${database}`;
17
+ if (!this.poolMap[key]) {
18
+ this.poolMap[key] = new pg_1.Pool({
19
+ user: user,
20
+ host: host,
21
+ database: database,
22
+ password: password,
23
+ port: Number(port),
24
+ ssl: isSslConnect ? {
25
+ rejectUnauthorized: false
26
+ } : false
27
+ });
28
+ }
29
+ return this.poolMap[key];
30
+ }
31
+ static shutdownAll() {
32
+ return __awaiter(this, void 0, void 0, function* () {
33
+ for (const [key, pool] of Object.entries(this.poolMap)) {
34
+ try {
35
+ yield pool.end();
36
+ console.log(`Closed pool: ${key}`);
37
+ }
38
+ catch (e) {
39
+ console.error(`Error closing pool ${key}`, e);
40
+ }
41
+ }
42
+ });
43
+ }
44
+ }
45
+ PoolManager.poolMap = {};
46
+ exports.default = PoolManager;
47
+ // ✅ 自動実行されるシャットダウン登録
48
+ process.on('SIGINT', () => __awaiter(void 0, void 0, void 0, function* () {
49
+ console.log('🔌 SIGINT received. Closing all pools...');
50
+ yield PoolManager.shutdownAll();
51
+ process.exit(0);
52
+ }));
53
+ process.on('SIGTERM', () => __awaiter(void 0, void 0, void 0, function* () {
54
+ console.log('🔌 SIGTERM received. Closing all pools...');
55
+ yield PoolManager.shutdownAll();
56
+ process.exit(0);
57
+ }));
@@ -0,0 +1,257 @@
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 __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.Service = void 0;
16
+ const axios_1 = __importDefault(require("axios"));
17
+ const Exception_1 = require("./exceptions/Exception");
18
+ const RequestType_1 = require("./reqestResponse/RequestType");
19
+ const ResponseType_1 = require("./reqestResponse/ResponseType");
20
+ const AwsS3Client_1 = __importDefault(require("./clients/AwsS3Client"));
21
+ const Base64Client_1 = __importDefault(require("./clients/Base64Client"));
22
+ const StringClient_1 = __importDefault(require("./clients/StringClient"));
23
+ const EncryptClient_1 = __importDefault(require("./clients/EncryptClient"));
24
+ const PoolManager_1 = __importDefault(require("./PoolManager"));
25
+ class Service {
26
+ get Method() { return this.method; }
27
+ get Endpoint() { return this.endpoint; }
28
+ get ApiCode() { return this.apiCode; }
29
+ get Summary() { return `${this.ApiCode !== '' ? this.apiCode + ': ' : ''}${this.summary}`; }
30
+ get ApiUserAvailable() { return this.apiUserAvailable; }
31
+ get Request() { return this.request; }
32
+ ; // swaggerで必要なので、ここだけ宣言
33
+ get AuthToken() { var _a; return (_a = this.request.Authorization) !== null && _a !== void 0 ? _a : ''; }
34
+ get Response() { return this.response; }
35
+ ; // swaggerで必要なので、ここだけ宣言
36
+ get Tags() { return this.tags; }
37
+ constructor(request, response) {
38
+ this.method = 'GET';
39
+ this.endpoint = '';
40
+ this.apiCode = '';
41
+ this.summary = '';
42
+ this.apiUserAvailable = '';
43
+ this.request = new RequestType_1.RequestType();
44
+ this.response = new ResponseType_1.ResponseType();
45
+ this.isTest = process.env.NODE_ENV === 'test';
46
+ this.tags = [];
47
+ this.dbUser = this.isTest ? process.env.TEST_DB_USER : process.env.DB_USER;
48
+ this.dbHost = this.isTest ? process.env.TEST_DB_HOST : process.env.DB_HOST;
49
+ this.dbName = this.isTest ? process.env.TEST_DB_DATABASE : process.env.DB_DATABASE;
50
+ this.dbPassword = this.isTest ? process.env.TEST_DB_PASSWORD : process.env.DB_PASSWORD;
51
+ this.dbPort = this.isTest ? process.env.TEST_DB_PORT : process.env.DB_PORT;
52
+ this.dbIsSslConnect = (this.isTest ? process.env.TEST_DB_IS_SSL : process.env.DB_IS_SSL) === 'true';
53
+ this.isExecuteRollback = false;
54
+ this.req = request;
55
+ this.res = response;
56
+ }
57
+ inintialize() {
58
+ return __awaiter(this, void 0, void 0, function* () {
59
+ this.request.setRequest(this.req);
60
+ yield this.checkMaintenance();
61
+ yield this.middleware();
62
+ });
63
+ }
64
+ setPool() {
65
+ if (this.dbUser === undefined) {
66
+ throw new Error("Database user is not configured");
67
+ }
68
+ if (this.dbHost === undefined) {
69
+ throw new Error("Database host is not configured");
70
+ }
71
+ if (this.dbName === undefined) {
72
+ throw new Error("Database name is not configured");
73
+ }
74
+ if (this.dbPassword === undefined) {
75
+ throw new Error("Database password is not configured");
76
+ }
77
+ if (this.dbPort === undefined) {
78
+ throw new Error("Database port is not configured");
79
+ }
80
+ try {
81
+ return PoolManager_1.default.getPool(this.dbUser, this.dbHost, this.dbName, this.dbPassword, this.dbPort, this.dbIsSslConnect);
82
+ }
83
+ catch (ex) {
84
+ throw new Error("Failed to connect to the database. Please check the connection settings.");
85
+ }
86
+ }
87
+ checkMaintenance() {
88
+ return __awaiter(this, void 0, void 0, function* () { });
89
+ }
90
+ middleware() {
91
+ return __awaiter(this, void 0, void 0, function* () { });
92
+ }
93
+ resSuccess() {
94
+ this.res.status(200).json(this.response.ResponseData);
95
+ }
96
+ outputErrorLog(ex) {
97
+ return __awaiter(this, void 0, void 0, function* () { });
98
+ }
99
+ handleException(ex) {
100
+ // To avoid slowing down the response, make this asynchronous
101
+ this.outputErrorLog(ex).catch((ex) => {
102
+ console.error(ex);
103
+ });
104
+ if (ex instanceof Exception_1.AuthException) {
105
+ this.res.status(401).json({
106
+ message: "Authentication expired. Please login again."
107
+ });
108
+ return;
109
+ }
110
+ else if (ex instanceof Exception_1.ForbiddenException) {
111
+ this.res.status(403).json({
112
+ message: 'Forbidden error'
113
+ });
114
+ return;
115
+ }
116
+ else if (ex instanceof Exception_1.InputErrorException) {
117
+ this.res.status(400).json({
118
+ errorCode: `${this.apiCode}-${ex.ErrorId}`,
119
+ errorMessage: ex.message
120
+ });
121
+ return;
122
+ }
123
+ else if (ex instanceof Exception_1.MaintenanceException) {
124
+ this.res.status(503).json({
125
+ errorMessage: ex.message
126
+ });
127
+ return;
128
+ }
129
+ this.res.status(500).json({
130
+ message: 'Internal server error'
131
+ });
132
+ return;
133
+ }
134
+ get Pool() {
135
+ var _a;
136
+ if (this.pool === undefined) {
137
+ this.pool = this.setPool();
138
+ this.pool.query(`SET TIME ZONE '${(_a = process.env.TZ) !== null && _a !== void 0 ? _a : 'Asia/Tokyo'}';`);
139
+ }
140
+ return this.pool;
141
+ }
142
+ get Client() {
143
+ if (this.client === undefined) {
144
+ throw new Error("Please call this.PoolClient after using the startConnect method.");
145
+ }
146
+ return this.client;
147
+ }
148
+ startConnect() {
149
+ return __awaiter(this, void 0, void 0, function* () {
150
+ this.client = yield this.Pool.connect();
151
+ yield this.Client.query('BEGIN');
152
+ this.isExecuteRollback = true;
153
+ });
154
+ }
155
+ commit() {
156
+ return __awaiter(this, void 0, void 0, function* () {
157
+ yield this.Client.query('COMMIT');
158
+ this.isExecuteRollback = false;
159
+ });
160
+ }
161
+ rollback() {
162
+ return __awaiter(this, void 0, void 0, function* () {
163
+ if (this.isExecuteRollback) {
164
+ yield this.Client.query('ROLLBACK');
165
+ }
166
+ this.isExecuteRollback = false;
167
+ });
168
+ }
169
+ release() {
170
+ return __awaiter(this, void 0, void 0, function* () {
171
+ yield this.rollback();
172
+ if (this.client !== undefined) {
173
+ yield this.client.release();
174
+ }
175
+ if (this.isTest) {
176
+ // In tests, the connection is terminated because it is shut down every time
177
+ yield this.Pool.end();
178
+ }
179
+ });
180
+ }
181
+ get S3Client() {
182
+ if (this.s3Client === undefined) {
183
+ this.s3Client = new AwsS3Client_1.default({
184
+ bucketName: process.env.S3_BUCKET_NAME,
185
+ region: process.env.S3_REGION,
186
+ accessKeyId: process.env.S3_ACCESS_KEY_ID,
187
+ secretAccessKey: process.env.S3_SECRET_ACCESS_KEY
188
+ });
189
+ }
190
+ return this.s3Client;
191
+ }
192
+ get Base64Client() {
193
+ if (this.base64Client === undefined) {
194
+ this.base64Client = new Base64Client_1.default();
195
+ }
196
+ return this.base64Client;
197
+ }
198
+ get StringClient() {
199
+ if (this.stringClient === undefined) {
200
+ this.stringClient = new StringClient_1.default();
201
+ }
202
+ return this.stringClient;
203
+ }
204
+ get EncryptClient() {
205
+ if (this.encryptClient === undefined) {
206
+ this.encryptClient = new EncryptClient_1.default({
207
+ secretKeyHex: process.env.SECRET_KEY_HEX,
208
+ hmacKeyBase64: process.env.HMAC_KEY_BASE64
209
+ });
210
+ }
211
+ return this.encryptClient;
212
+ }
213
+ requestApi(method, url, params, header) {
214
+ return __awaiter(this, void 0, void 0, function* () {
215
+ // GET,DELETEのparamをURLクエリに
216
+ if (method === 'GET' || method === 'DELETE') {
217
+ for (const [key, value] of Object.entries(params)) {
218
+ if (value === undefined || value === null) {
219
+ continue;
220
+ }
221
+ if (Array.isArray(value)) {
222
+ for (const arrayValue of value) {
223
+ url += url.includes('?') ? '&' : '?';
224
+ url += `${key}=${arrayValue.toString()}`;
225
+ }
226
+ }
227
+ else {
228
+ url += url.includes('?') ? '&' : '?';
229
+ url += `${key}=${value.toString()}`;
230
+ }
231
+ }
232
+ }
233
+ try {
234
+ switch (method) {
235
+ case 'GET':
236
+ return yield axios_1.default.get(url, header === undefined ? {} : { headers: header });
237
+ case 'POST':
238
+ return yield axios_1.default.post(url, params, header === undefined ? {} : { headers: header });
239
+ case 'PUT':
240
+ return yield axios_1.default.put(url, params, header === undefined ? {} : { headers: header });
241
+ case 'DELETE':
242
+ return yield axios_1.default.delete(url, header === undefined ? {} : { headers: header });
243
+ case 'PATCH':
244
+ return yield axios_1.default.patch(url, params, header === undefined ? {} : { headers: header });
245
+ }
246
+ }
247
+ catch (ex) {
248
+ let response = ex.response;
249
+ if (response && [400, 401, 403, 409, 422].includes(response.status)) {
250
+ return response;
251
+ }
252
+ throw ex;
253
+ }
254
+ });
255
+ }
256
+ }
257
+ exports.Service = Service;
@@ -0,0 +1,249 @@
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 __asyncValues = (this && this.__asyncValues) || function (o) {
12
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
13
+ var m = o[Symbol.asyncIterator], i;
14
+ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
15
+ function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
16
+ function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
17
+ };
18
+ var __importDefault = (this && this.__importDefault) || function (mod) {
19
+ return (mod && mod.__esModule) ? mod : { "default": mod };
20
+ };
21
+ Object.defineProperty(exports, "__esModule", { value: true });
22
+ const client_s3_1 = require("@aws-sdk/client-s3");
23
+ const Base64Client_1 = __importDefault(require("./Base64Client"));
24
+ class AwsS3Client {
25
+ get urlPrefix() {
26
+ return `https://${this.bucketName}.s3.${this.region}.amazonaws.com`;
27
+ }
28
+ constructor(params) {
29
+ if (params.bucketName === undefined) {
30
+ throw new Error("Please specify the bucketName.");
31
+ }
32
+ if (params.region === undefined) {
33
+ throw new Error("Please specify the region.");
34
+ }
35
+ if (params.accessKeyId === undefined) {
36
+ throw new Error("Please specify the accessKeyId.");
37
+ }
38
+ if (params.secretAccessKey === undefined) {
39
+ throw new Error("Please specify the secretAccessKey.");
40
+ }
41
+ this.client = new client_s3_1.S3Client({
42
+ region: params.region,
43
+ credentials: {
44
+ accessKeyId: params.accessKeyId,
45
+ secretAccessKey: params.secretAccessKey
46
+ }
47
+ });
48
+ this.region = params.region;
49
+ this.bucketName = params.bucketName;
50
+ }
51
+ makeKey(path, fileName) {
52
+ path = path.replace(/^\/|\/$/g, '');
53
+ if ((fileName !== null && fileName !== void 0 ? fileName : '').trim().length > 0) {
54
+ path += '/' + fileName;
55
+ }
56
+ return path;
57
+ }
58
+ url(path, fileName = '') {
59
+ path = path.replace(/^\/|\/$/g, '');
60
+ let url = `${this.urlPrefix}`;
61
+ if (path !== '') {
62
+ url += '/' + path;
63
+ }
64
+ if (fileName.trim().length > 0) {
65
+ url += '/' + fileName;
66
+ }
67
+ return url;
68
+ }
69
+ uploadJson(path, fileName, data) {
70
+ return __awaiter(this, void 0, void 0, function* () {
71
+ const command = new client_s3_1.PutObjectCommand({
72
+ Bucket: this.bucketName,
73
+ Key: this.makeKey(path, fileName),
74
+ Body: JSON.stringify(data),
75
+ ContentType: 'text/plain; charset=utf-8'
76
+ });
77
+ yield this.client.send(command);
78
+ });
79
+ }
80
+ uploadToPdf(path, fileName, base64Datas) {
81
+ return __awaiter(this, void 0, void 0, function* () {
82
+ const base64Client = new Base64Client_1.default();
83
+ const mergedPdfBase64 = yield base64Client.mergeToPdfBase64(base64Datas);
84
+ const command = new client_s3_1.PutObjectCommand({
85
+ Bucket: this.bucketName,
86
+ Key: this.makeKey(path, fileName),
87
+ Body: Buffer.from(mergedPdfBase64, 'base64'),
88
+ ContentEncoding: 'base64',
89
+ ContentType: 'application/pdf'
90
+ });
91
+ yield this.client.send(command);
92
+ });
93
+ }
94
+ uploadText(path, fileName, text) {
95
+ return __awaiter(this, void 0, void 0, function* () {
96
+ const command = new client_s3_1.PutObjectCommand({
97
+ Bucket: this.bucketName,
98
+ Key: this.makeKey(path, fileName),
99
+ Body: text,
100
+ ContentType: 'text/plain; charset=utf-8'
101
+ });
102
+ yield this.client.send(command);
103
+ });
104
+ }
105
+ uploadBase64Data(path, fileName, base64Data) {
106
+ return __awaiter(this, void 0, void 0, function* () {
107
+ const base64Client = new Base64Client_1.default();
108
+ const type = base64Client.getMimeType(base64Data);
109
+ const extension = {
110
+ 'image/png': '.png',
111
+ 'image/jpeg': '.jpeg',
112
+ 'image/gif': '.gif',
113
+ 'application/pdf': '.pdf'
114
+ }[type];
115
+ if (fileName.endsWith(extension) === false) {
116
+ fileName += extension;
117
+ }
118
+ const key = this.makeKey(path, fileName);
119
+ const command = new client_s3_1.PutObjectCommand({
120
+ Bucket: this.bucketName,
121
+ Key: key,
122
+ Body: Buffer.from(base64Data, 'base64'),
123
+ ContentEncoding: 'base64',
124
+ ContentType: type
125
+ });
126
+ yield this.client.send(command);
127
+ return `${this.urlPrefix}/${key}`;
128
+ });
129
+ }
130
+ uploadStackText(path, fileName, text) {
131
+ return __awaiter(this, void 0, void 0, function* () {
132
+ let preText = yield this.getText(path, fileName);
133
+ if (typeof preText === 'string') {
134
+ text = preText + '\n' + text;
135
+ }
136
+ yield this.uploadText(path, fileName, text);
137
+ });
138
+ }
139
+ getText(path, fileName) {
140
+ return __awaiter(this, void 0, void 0, function* () {
141
+ var _a;
142
+ try {
143
+ const command = new client_s3_1.GetObjectCommand({
144
+ Bucket: this.bucketName,
145
+ Key: this.makeKey(path, fileName),
146
+ });
147
+ const res = yield this.client.send(command);
148
+ if (res.Body === undefined) {
149
+ throw new Error(`Failed to get text data. Response body is undefined.`);
150
+ }
151
+ if (((_a = res.ContentType) === null || _a === void 0 ? void 0 : _a.startsWith('text/')) === false) {
152
+ throw new Error(`Cannot get text data from non-text file. ContentType: ${res.ContentType}`);
153
+ }
154
+ // v3ではBodyがReadableStreamなので、変換が必要
155
+ const stream = res.Body;
156
+ const reader = stream.getReader();
157
+ const chunks = [];
158
+ while (true) {
159
+ const { done, value } = yield reader.read();
160
+ if (done)
161
+ break;
162
+ chunks.push(value);
163
+ }
164
+ const buffer = Buffer.concat(chunks);
165
+ return buffer.toString('utf-8');
166
+ }
167
+ catch (ex) {
168
+ if (ex instanceof Error && ex.name === 'NoSuchKey') {
169
+ return null;
170
+ }
171
+ throw ex;
172
+ }
173
+ });
174
+ }
175
+ getFilesInDir(path) {
176
+ return __awaiter(this, void 0, void 0, function* () {
177
+ var _a;
178
+ const listCommand = new client_s3_1.ListObjectsV2Command({
179
+ Bucket: this.bucketName,
180
+ Prefix: this.makeKey(path),
181
+ });
182
+ const data = yield this.client.send(listCommand);
183
+ return (_a = data.Contents) !== null && _a !== void 0 ? _a : [];
184
+ });
185
+ }
186
+ getDataFronJson(path, fileName) {
187
+ return __awaiter(this, void 0, void 0, function* () {
188
+ var _a, e_1, _b, _c;
189
+ const command = new client_s3_1.GetObjectCommand({
190
+ Bucket: this.bucketName,
191
+ Key: this.makeKey(path, fileName),
192
+ });
193
+ const res = yield this.client.send(command);
194
+ if (res.Body === undefined) {
195
+ throw new Error(`Failed to get JSON data. Response body is undefined.`);
196
+ }
197
+ if (res.ContentType !== 'application/json') {
198
+ throw new Error(`Cannot get JSON data from non-JSON file. ContentType: ${res.ContentType}`);
199
+ }
200
+ // v3ではBodyがReadableなので、変換が必要
201
+ const chunks = [];
202
+ try {
203
+ for (var _d = true, _e = __asyncValues(res.Body), _f; _f = yield _e.next(), _a = _f.done, !_a; _d = true) {
204
+ _c = _f.value;
205
+ _d = false;
206
+ const chunk = _c;
207
+ chunks.push(chunk);
208
+ }
209
+ }
210
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
211
+ finally {
212
+ try {
213
+ if (!_d && !_a && (_b = _e.return)) yield _b.call(_e);
214
+ }
215
+ finally { if (e_1) throw e_1.error; }
216
+ }
217
+ const buffer = Buffer.concat(chunks);
218
+ const jsonString = buffer.toString('utf-8');
219
+ return JSON.parse(jsonString);
220
+ });
221
+ }
222
+ deleteFile(path, fileName) {
223
+ return __awaiter(this, void 0, void 0, function* () {
224
+ const key = this.makeKey(path, fileName);
225
+ const command = new client_s3_1.DeleteObjectsCommand({
226
+ Bucket: this.bucketName,
227
+ Delete: {
228
+ Objects: [{ Key: key }]
229
+ }
230
+ });
231
+ yield this.client.send(command);
232
+ });
233
+ }
234
+ deleteDir(path) {
235
+ return __awaiter(this, void 0, void 0, function* () {
236
+ const files = yield this.getFilesInDir(path);
237
+ if (files.length > 0) {
238
+ const deleteCommand = new client_s3_1.DeleteObjectsCommand({
239
+ Bucket: this.bucketName,
240
+ Delete: {
241
+ Objects: files.map((file) => ({ Key: file.Key })),
242
+ },
243
+ });
244
+ yield this.client.send(deleteCommand);
245
+ }
246
+ });
247
+ }
248
+ }
249
+ exports.default = AwsS3Client;