@eeplatform/basic-edu 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.
package/dist/index.js ADDED
@@ -0,0 +1,1405 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var src_exports = {};
32
+ __export(src_exports, {
33
+ modelDivision: () => modelDivision,
34
+ modelRegion: () => modelRegion,
35
+ modelSchool: () => modelSchool,
36
+ schemaDivision: () => schemaDivision,
37
+ schemaRegion: () => schemaRegion,
38
+ schemaSchool: () => schemaSchool,
39
+ useDivisionController: () => useDivisionController,
40
+ useDivisionRepo: () => useDivisionRepo,
41
+ useRegionController: () => useRegionController,
42
+ useRegionRepo: () => useRegionRepo,
43
+ useSchoolController: () => useSchoolController,
44
+ useSchoolRepo: () => useSchoolRepo
45
+ });
46
+ module.exports = __toCommonJS(src_exports);
47
+
48
+ // src/models/region.model.ts
49
+ var import_nodejs_utils = require("@eeplatform/nodejs-utils");
50
+ var import_joi = __toESM(require("joi"));
51
+ var import_mongodb = require("mongodb");
52
+ var schemaRegion = import_joi.default.object({
53
+ _id: import_joi.default.string().hex().optional().allow(null, ""),
54
+ name: import_joi.default.string().min(1).max(100).required(),
55
+ createdAt: import_joi.default.string().isoDate().optional(),
56
+ updatedAt: import_joi.default.string().isoDate().optional(),
57
+ deletedAt: import_joi.default.string().isoDate().optional().allow(null, "")
58
+ });
59
+ function modelRegion(value) {
60
+ const { error } = schemaRegion.validate(value);
61
+ if (error) {
62
+ throw new import_nodejs_utils.BadRequestError(`Invalid region data: ${error.message}`);
63
+ }
64
+ if (value._id && typeof value._id === "string") {
65
+ try {
66
+ value._id = import_mongodb.ObjectId.createFromTime(value._id);
67
+ } catch (error2) {
68
+ throw new Error("Invalid _id.");
69
+ }
70
+ }
71
+ return {
72
+ _id: value._id,
73
+ name: value.name,
74
+ createdAt: value.createdAt ?? (/* @__PURE__ */ new Date()).toISOString(),
75
+ updatedAt: value.updatedAt ?? "",
76
+ deletedAt: value.deletedAt ?? ""
77
+ };
78
+ }
79
+
80
+ // src/repositories/region.repository.ts
81
+ var import_nodejs_utils2 = require("@eeplatform/nodejs-utils");
82
+ var import_mongodb2 = require("mongodb");
83
+ function useRegionRepo() {
84
+ const db = import_nodejs_utils2.useAtlas.getDb();
85
+ if (!db) {
86
+ throw new Error("Unable to connect to server.");
87
+ }
88
+ const namespace_collection = "deped.regions";
89
+ const collection = db.collection(namespace_collection);
90
+ const { getCache, setCache, delNamespace } = (0, import_nodejs_utils2.useCache)(namespace_collection);
91
+ async function createIndexes() {
92
+ try {
93
+ await collection.createIndexes([
94
+ { key: { name: 1 } },
95
+ { key: { createdAt: 1 } },
96
+ { key: { name: "text" } },
97
+ { key: { name: 1 }, unique: true, name: "unique_name" }
98
+ ]);
99
+ } catch (error) {
100
+ throw new Error("Failed to create index on regions.");
101
+ }
102
+ }
103
+ function delCachedData() {
104
+ delNamespace().then(() => {
105
+ import_nodejs_utils2.logger.log({
106
+ level: "info",
107
+ message: `Cache namespace cleared for ${namespace_collection}`
108
+ });
109
+ }).catch((err) => {
110
+ import_nodejs_utils2.logger.log({
111
+ level: "error",
112
+ message: `Failed to clear cache namespace for ${namespace_collection}: ${err.message}`
113
+ });
114
+ });
115
+ }
116
+ async function add(value, session) {
117
+ try {
118
+ value = modelRegion(value);
119
+ const res = await collection.insertOne(value, { session });
120
+ delCachedData();
121
+ return res.insertedId;
122
+ } catch (error) {
123
+ import_nodejs_utils2.logger.log({
124
+ level: "error",
125
+ message: error.message
126
+ });
127
+ if (error instanceof import_nodejs_utils2.AppError) {
128
+ throw error;
129
+ } else {
130
+ const isDuplicated = error.message.includes("duplicate");
131
+ if (isDuplicated) {
132
+ throw new import_nodejs_utils2.BadRequestError("Region already exists.");
133
+ }
134
+ throw new Error("Failed to create region.");
135
+ }
136
+ }
137
+ }
138
+ async function getAll({
139
+ search = "",
140
+ page = 1,
141
+ limit = 10,
142
+ sort = {},
143
+ status = "active"
144
+ } = {}) {
145
+ page = page > 0 ? page - 1 : 0;
146
+ const query = {
147
+ deletedAt: { $in: ["", null] },
148
+ status
149
+ };
150
+ sort = Object.keys(sort).length > 0 ? sort : { _id: 1 };
151
+ const cacheKeyOptions = {
152
+ status,
153
+ page,
154
+ limit,
155
+ sort: JSON.stringify(sort)
156
+ };
157
+ if (search) {
158
+ query.$text = { $search: search };
159
+ cacheKeyOptions.search = search;
160
+ }
161
+ const cacheKey = (0, import_nodejs_utils2.makeCacheKey)(namespace_collection, cacheKeyOptions);
162
+ import_nodejs_utils2.logger.log({
163
+ level: "info",
164
+ message: `Cache key for getAll regions: ${cacheKey}`
165
+ });
166
+ try {
167
+ const cached = await getCache(cacheKey);
168
+ if (cached) {
169
+ import_nodejs_utils2.logger.log({
170
+ level: "info",
171
+ message: `Cache hit for getAll regions: ${cacheKey}`
172
+ });
173
+ return cached;
174
+ }
175
+ const items = await collection.aggregate([
176
+ { $match: query },
177
+ { $sort: sort },
178
+ { $skip: page * limit },
179
+ { $limit: limit }
180
+ ]).toArray();
181
+ const length = await collection.countDocuments(query);
182
+ const data = (0, import_nodejs_utils2.paginate)(items, page, limit, length);
183
+ setCache(cacheKey, data, 600).then(() => {
184
+ import_nodejs_utils2.logger.log({
185
+ level: "info",
186
+ message: `Cache set for getAll regions: ${cacheKey}`
187
+ });
188
+ }).catch((err) => {
189
+ import_nodejs_utils2.logger.log({
190
+ level: "error",
191
+ message: `Failed to set cache for getAll regions: ${err.message}`
192
+ });
193
+ });
194
+ return data;
195
+ } catch (error) {
196
+ import_nodejs_utils2.logger.log({ level: "error", message: `${error}` });
197
+ throw error;
198
+ }
199
+ }
200
+ async function getById(_id) {
201
+ try {
202
+ _id = new import_mongodb2.ObjectId(_id);
203
+ } catch (error) {
204
+ throw new import_nodejs_utils2.BadRequestError("Invalid ID.");
205
+ }
206
+ const cacheKey = (0, import_nodejs_utils2.makeCacheKey)(namespace_collection, { _id: String(_id) });
207
+ try {
208
+ const cached = await getCache(cacheKey);
209
+ if (cached) {
210
+ import_nodejs_utils2.logger.log({
211
+ level: "info",
212
+ message: `Cache hit for getById region: ${cacheKey}`
213
+ });
214
+ return cached;
215
+ }
216
+ const result = await collection.findOne({
217
+ _id,
218
+ deletedAt: { $in: ["", null] }
219
+ });
220
+ if (!result) {
221
+ throw new import_nodejs_utils2.BadRequestError("Region not found.");
222
+ }
223
+ setCache(cacheKey, result, 300).then(() => {
224
+ import_nodejs_utils2.logger.log({
225
+ level: "info",
226
+ message: `Cache set for region by id: ${cacheKey}`
227
+ });
228
+ }).catch((err) => {
229
+ import_nodejs_utils2.logger.log({
230
+ level: "error",
231
+ message: `Failed to set cache for region by id: ${err.message}`
232
+ });
233
+ });
234
+ return result;
235
+ } catch (error) {
236
+ if (error instanceof import_nodejs_utils2.AppError) {
237
+ throw error;
238
+ } else {
239
+ throw new import_nodejs_utils2.InternalServerError("Failed to get region.");
240
+ }
241
+ }
242
+ }
243
+ async function getByName(name) {
244
+ const cacheKey = (0, import_nodejs_utils2.makeCacheKey)(namespace_collection, { name });
245
+ try {
246
+ const cached = await getCache(cacheKey);
247
+ if (cached) {
248
+ import_nodejs_utils2.logger.log({
249
+ level: "info",
250
+ message: `Cache hit for getByName region: ${cacheKey}`
251
+ });
252
+ return cached;
253
+ }
254
+ const result = await collection.findOne({
255
+ name,
256
+ deletedAt: { $in: ["", null] }
257
+ });
258
+ if (!result) {
259
+ throw new import_nodejs_utils2.BadRequestError("Region not found.");
260
+ }
261
+ setCache(cacheKey, result, 300).then(() => {
262
+ import_nodejs_utils2.logger.log({
263
+ level: "info",
264
+ message: `Cache set for region by name: ${cacheKey}`
265
+ });
266
+ }).catch((err) => {
267
+ import_nodejs_utils2.logger.log({
268
+ level: "error",
269
+ message: `Failed to set cache for region by name: ${err.message}`
270
+ });
271
+ });
272
+ return result;
273
+ } catch (error) {
274
+ if (error instanceof import_nodejs_utils2.AppError) {
275
+ throw error;
276
+ } else {
277
+ throw new import_nodejs_utils2.InternalServerError("Failed to get region.");
278
+ }
279
+ }
280
+ }
281
+ async function updateFieldById({ _id, field, value } = {}, session) {
282
+ const allowedFields = ["name"];
283
+ if (!allowedFields.includes(field)) {
284
+ throw new import_nodejs_utils2.BadRequestError(
285
+ `Field "${field}" is not allowed to be updated.`
286
+ );
287
+ }
288
+ try {
289
+ _id = new import_mongodb2.ObjectId(_id);
290
+ } catch (error) {
291
+ throw new import_nodejs_utils2.BadRequestError("Invalid ID.");
292
+ }
293
+ try {
294
+ await collection.updateOne(
295
+ { _id, deletedAt: { $in: ["", null] } },
296
+ { $set: { [field]: value, updatedAt: (/* @__PURE__ */ new Date()).toISOString() } },
297
+ { session }
298
+ );
299
+ delCachedData();
300
+ return `Successfully updated region ${field}.`;
301
+ } catch (error) {
302
+ throw new import_nodejs_utils2.InternalServerError(`Failed to update region ${field}.`);
303
+ }
304
+ }
305
+ async function deleteById(_id) {
306
+ try {
307
+ _id = new import_mongodb2.ObjectId(_id);
308
+ } catch (error) {
309
+ throw new import_nodejs_utils2.BadRequestError("Invalid ID.");
310
+ }
311
+ try {
312
+ await collection.updateOne(
313
+ { _id },
314
+ { $set: { deletedAt: (/* @__PURE__ */ new Date()).toISOString() } }
315
+ );
316
+ delCachedData();
317
+ return "Successfully deleted region.";
318
+ } catch (error) {
319
+ throw new import_nodejs_utils2.InternalServerError("Failed to delete region.");
320
+ }
321
+ }
322
+ return {
323
+ createIndexes,
324
+ add,
325
+ getAll,
326
+ getById,
327
+ updateFieldById,
328
+ deleteById,
329
+ getByName
330
+ };
331
+ }
332
+
333
+ // src/controllers/region.controller.ts
334
+ var import_nodejs_utils3 = require("@eeplatform/nodejs-utils");
335
+ var import_joi2 = __toESM(require("joi"));
336
+ function useRegionController() {
337
+ const {
338
+ add: _add,
339
+ getAll: _getAll,
340
+ getById: _getById,
341
+ getByName: _getByName,
342
+ updateFieldById: _updateFieldById,
343
+ deleteById: _deleteById
344
+ } = useRegionRepo();
345
+ async function add(req, res, next) {
346
+ const value = req.body;
347
+ const { error } = schemaRegion.validate(value);
348
+ if (error) {
349
+ next(new import_nodejs_utils3.BadRequestError(error.message));
350
+ return;
351
+ }
352
+ try {
353
+ const data = await _add(value);
354
+ res.json({
355
+ message: "Successfully created region.",
356
+ data
357
+ });
358
+ return;
359
+ } catch (error2) {
360
+ next(error2);
361
+ }
362
+ }
363
+ async function getAll(req, res, next) {
364
+ const query = req.query;
365
+ const validation = import_joi2.default.object({
366
+ page: import_joi2.default.number().min(1).optional().allow("", null),
367
+ limit: import_joi2.default.number().min(1).optional().allow("", null),
368
+ search: import_joi2.default.string().optional().allow("", null),
369
+ status: import_joi2.default.string().optional().allow("", null)
370
+ });
371
+ const { error } = validation.validate(query);
372
+ const page = typeof req.query.page === "string" ? Number(req.query.page) : 1;
373
+ const limit = typeof req.query.limit === "string" ? Number(req.query.limit) : 10;
374
+ const search = req.query.search ?? "";
375
+ const status = req.query.status ?? "active";
376
+ const isPageNumber = isFinite(page);
377
+ if (!isPageNumber) {
378
+ next(new import_nodejs_utils3.BadRequestError("Invalid page number."));
379
+ return;
380
+ }
381
+ const isLimitNumber = isFinite(limit);
382
+ if (!isLimitNumber) {
383
+ next(new import_nodejs_utils3.BadRequestError("Invalid limit number."));
384
+ return;
385
+ }
386
+ if (error) {
387
+ next(new import_nodejs_utils3.BadRequestError(error.message));
388
+ return;
389
+ }
390
+ try {
391
+ const data = await _getAll({ page, limit, search, status });
392
+ res.json(data);
393
+ return;
394
+ } catch (error2) {
395
+ next(error2);
396
+ }
397
+ }
398
+ async function getById(req, res, next) {
399
+ const id = req.params.id;
400
+ const validation = import_joi2.default.object({
401
+ id: import_joi2.default.string().hex().required()
402
+ });
403
+ const { error } = validation.validate({ id });
404
+ if (error) {
405
+ next(new import_nodejs_utils3.BadRequestError(error.message));
406
+ return;
407
+ }
408
+ try {
409
+ const data = await _getById(id);
410
+ res.json({
411
+ message: "Successfully retrieved region.",
412
+ data
413
+ });
414
+ return;
415
+ } catch (error2) {
416
+ next(error2);
417
+ }
418
+ }
419
+ async function getByName(req, res, next) {
420
+ const name = req.params.name;
421
+ const validation = import_joi2.default.object({
422
+ name: import_joi2.default.string().required()
423
+ });
424
+ const { error } = validation.validate({ name });
425
+ if (error) {
426
+ next(new import_nodejs_utils3.BadRequestError(error.message));
427
+ return;
428
+ }
429
+ try {
430
+ const data = await _getByName(name);
431
+ res.json({
432
+ message: "Successfully retrieved region.",
433
+ data
434
+ });
435
+ return;
436
+ } catch (error2) {
437
+ next(error2);
438
+ }
439
+ }
440
+ async function updateField(req, res, next) {
441
+ const _id = req.params.id;
442
+ const { field, value } = req.body;
443
+ const validation = import_joi2.default.object({
444
+ _id: import_joi2.default.string().hex().required(),
445
+ field: import_joi2.default.string().valid("name", "director", "directorName").required(),
446
+ value: import_joi2.default.string().required()
447
+ });
448
+ const { error } = validation.validate({ _id, field, value });
449
+ if (error) {
450
+ next(new import_nodejs_utils3.BadRequestError(error.message));
451
+ return;
452
+ }
453
+ try {
454
+ const message = await _updateFieldById({ _id, field, value });
455
+ res.json({ message });
456
+ return;
457
+ } catch (error2) {
458
+ next(error2);
459
+ }
460
+ }
461
+ async function deleteById(req, res, next) {
462
+ const _id = req.params.id;
463
+ const validation = import_joi2.default.object({
464
+ _id: import_joi2.default.string().hex().required()
465
+ });
466
+ const { error } = validation.validate({ _id });
467
+ if (error) {
468
+ next(new import_nodejs_utils3.BadRequestError(error.message));
469
+ return;
470
+ }
471
+ try {
472
+ const message = await _deleteById(_id);
473
+ res.json({ message });
474
+ return;
475
+ } catch (error2) {
476
+ next(error2);
477
+ }
478
+ }
479
+ return {
480
+ add,
481
+ getAll,
482
+ getById,
483
+ getByName,
484
+ updateField,
485
+ deleteById
486
+ };
487
+ }
488
+
489
+ // src/models/division.model.ts
490
+ var import_nodejs_utils4 = require("@eeplatform/nodejs-utils");
491
+ var import_joi3 = __toESM(require("joi"));
492
+ var import_mongodb3 = require("mongodb");
493
+ var schemaDivision = import_joi3.default.object({
494
+ _id: import_joi3.default.string().hex().optional().allow(null, ""),
495
+ name: import_joi3.default.string().min(1).max(100).required(),
496
+ region: import_joi3.default.string().hex().optional().allow(null, ""),
497
+ regionName: import_joi3.default.string().min(1).max(100).optional().allow(null, ""),
498
+ superintendent: import_joi3.default.string().hex().optional().allow(null, ""),
499
+ superintendentName: import_joi3.default.string().min(1).max(100).optional().allow(null, ""),
500
+ createdAt: import_joi3.default.string().isoDate().optional(),
501
+ updatedAt: import_joi3.default.string().isoDate().optional(),
502
+ deletedAt: import_joi3.default.string().isoDate().optional().allow(null, "")
503
+ });
504
+ function modelDivision(value) {
505
+ const { error } = schemaDivision.validate(value);
506
+ if (error) {
507
+ throw new import_nodejs_utils4.BadRequestError(`Invalid sdo data: ${error.message}`);
508
+ }
509
+ if (value._id && typeof value._id === "string") {
510
+ try {
511
+ value._id = import_mongodb3.ObjectId.createFromTime(value._id);
512
+ } catch (error2) {
513
+ throw new Error("Invalid _id.");
514
+ }
515
+ }
516
+ return {
517
+ _id: value._id,
518
+ name: value.name,
519
+ region: value.region,
520
+ regionName: value.regionName ?? "",
521
+ superintendent: value.superintendent,
522
+ superintendentName: value.superintendentName ?? "",
523
+ createdAt: value.createdAt ?? (/* @__PURE__ */ new Date()).toISOString(),
524
+ updatedAt: value.updatedAt ?? "",
525
+ deletedAt: value.deletedAt ?? ""
526
+ };
527
+ }
528
+
529
+ // src/repositories/division.repository.ts
530
+ var import_nodejs_utils5 = require("@eeplatform/nodejs-utils");
531
+ var import_mongodb4 = require("mongodb");
532
+ function useDivisionRepo() {
533
+ const db = import_nodejs_utils5.useAtlas.getDb();
534
+ if (!db) {
535
+ throw new Error("Unable to connect to server.");
536
+ }
537
+ const namespace_collection = "deped.divisions";
538
+ const collection = db.collection(namespace_collection);
539
+ const { getCache, setCache, delNamespace } = (0, import_nodejs_utils5.useCache)(namespace_collection);
540
+ async function createIndexes() {
541
+ try {
542
+ await collection.createIndexes([
543
+ { key: { name: 1 } },
544
+ { key: { createdAt: 1 } },
545
+ { key: { name: "text" } },
546
+ { key: { name: 1 }, unique: true, name: "unique_name" }
547
+ ]);
548
+ } catch (error) {
549
+ throw new Error("Failed to create index on divisions.");
550
+ }
551
+ }
552
+ function delCachedData() {
553
+ delNamespace().then(() => {
554
+ import_nodejs_utils5.logger.log({
555
+ level: "info",
556
+ message: `Cache namespace cleared for ${namespace_collection}`
557
+ });
558
+ }).catch((err) => {
559
+ import_nodejs_utils5.logger.log({
560
+ level: "error",
561
+ message: `Failed to clear cache namespace for ${namespace_collection}: ${err.message}`
562
+ });
563
+ });
564
+ }
565
+ async function add(value, session) {
566
+ try {
567
+ value = modelDivision(value);
568
+ const res = await collection.insertOne(value, { session });
569
+ delCachedData();
570
+ return res.insertedId;
571
+ } catch (error) {
572
+ import_nodejs_utils5.logger.log({
573
+ level: "error",
574
+ message: error.message
575
+ });
576
+ if (error instanceof import_nodejs_utils5.AppError) {
577
+ throw error;
578
+ } else {
579
+ const isDuplicated = error.message.includes("duplicate");
580
+ if (isDuplicated) {
581
+ throw new import_nodejs_utils5.BadRequestError("Division already exists.");
582
+ }
583
+ throw new Error("Failed to create division.");
584
+ }
585
+ }
586
+ }
587
+ async function getAll({
588
+ search = "",
589
+ page = 1,
590
+ limit = 10,
591
+ sort = {},
592
+ status = "active"
593
+ } = {}) {
594
+ page = page > 0 ? page - 1 : 0;
595
+ const query = {
596
+ deletedAt: { $in: ["", null] },
597
+ status
598
+ };
599
+ sort = Object.keys(sort).length > 0 ? sort : { _id: 1 };
600
+ const cacheKeyOptions = {
601
+ status,
602
+ page,
603
+ limit,
604
+ sort: JSON.stringify(sort)
605
+ };
606
+ if (search) {
607
+ query.$text = { $search: search };
608
+ cacheKeyOptions.search = search;
609
+ }
610
+ const cacheKey = (0, import_nodejs_utils5.makeCacheKey)(namespace_collection, cacheKeyOptions);
611
+ import_nodejs_utils5.logger.log({
612
+ level: "info",
613
+ message: `Cache key for getAll divisions: ${cacheKey}`
614
+ });
615
+ try {
616
+ const cached = await getCache(cacheKey);
617
+ if (cached) {
618
+ import_nodejs_utils5.logger.log({
619
+ level: "info",
620
+ message: `Cache hit for getAll divisions: ${cacheKey}`
621
+ });
622
+ return cached;
623
+ }
624
+ const items = await collection.aggregate([
625
+ { $match: query },
626
+ { $sort: sort },
627
+ { $skip: page * limit },
628
+ { $limit: limit }
629
+ ]).toArray();
630
+ const length = await collection.countDocuments(query);
631
+ const data = (0, import_nodejs_utils5.paginate)(items, page, limit, length);
632
+ setCache(cacheKey, data, 600).then(() => {
633
+ import_nodejs_utils5.logger.log({
634
+ level: "info",
635
+ message: `Cache set for getAll divisions: ${cacheKey}`
636
+ });
637
+ }).catch((err) => {
638
+ import_nodejs_utils5.logger.log({
639
+ level: "error",
640
+ message: `Failed to set cache for getAll divisions: ${err.message}`
641
+ });
642
+ });
643
+ return data;
644
+ } catch (error) {
645
+ import_nodejs_utils5.logger.log({ level: "error", message: `${error}` });
646
+ throw error;
647
+ }
648
+ }
649
+ async function getById(_id) {
650
+ try {
651
+ _id = new import_mongodb4.ObjectId(_id);
652
+ } catch (error) {
653
+ throw new import_nodejs_utils5.BadRequestError("Invalid ID.");
654
+ }
655
+ const cacheKey = (0, import_nodejs_utils5.makeCacheKey)(namespace_collection, { _id: String(_id) });
656
+ try {
657
+ const cached = await getCache(cacheKey);
658
+ if (cached) {
659
+ import_nodejs_utils5.logger.log({
660
+ level: "info",
661
+ message: `Cache hit for getById division: ${cacheKey}`
662
+ });
663
+ return cached;
664
+ }
665
+ const result = await collection.findOne({
666
+ _id,
667
+ deletedAt: { $in: ["", null] }
668
+ });
669
+ if (!result) {
670
+ throw new import_nodejs_utils5.BadRequestError("Division not found.");
671
+ }
672
+ setCache(cacheKey, result, 300).then(() => {
673
+ import_nodejs_utils5.logger.log({
674
+ level: "info",
675
+ message: `Cache set for division by id: ${cacheKey}`
676
+ });
677
+ }).catch((err) => {
678
+ import_nodejs_utils5.logger.log({
679
+ level: "error",
680
+ message: `Failed to set cache for division by id: ${err.message}`
681
+ });
682
+ });
683
+ return result;
684
+ } catch (error) {
685
+ if (error instanceof import_nodejs_utils5.AppError) {
686
+ throw error;
687
+ } else {
688
+ throw new import_nodejs_utils5.InternalServerError("Failed to get division.");
689
+ }
690
+ }
691
+ }
692
+ async function getByName(name) {
693
+ const cacheKey = (0, import_nodejs_utils5.makeCacheKey)(namespace_collection, { name });
694
+ try {
695
+ const cached = await getCache(cacheKey);
696
+ if (cached) {
697
+ import_nodejs_utils5.logger.log({
698
+ level: "info",
699
+ message: `Cache hit for getByName division: ${cacheKey}`
700
+ });
701
+ return cached;
702
+ }
703
+ const result = await collection.findOne({
704
+ name,
705
+ deletedAt: { $in: ["", null] }
706
+ });
707
+ if (!result) {
708
+ throw new import_nodejs_utils5.BadRequestError("Division not found.");
709
+ }
710
+ setCache(cacheKey, result, 300).then(() => {
711
+ import_nodejs_utils5.logger.log({
712
+ level: "info",
713
+ message: `Cache set for division by name: ${cacheKey}`
714
+ });
715
+ }).catch((err) => {
716
+ import_nodejs_utils5.logger.log({
717
+ level: "error",
718
+ message: `Failed to set cache for division by name: ${err.message}`
719
+ });
720
+ });
721
+ return result;
722
+ } catch (error) {
723
+ if (error instanceof import_nodejs_utils5.AppError) {
724
+ throw error;
725
+ } else {
726
+ throw new import_nodejs_utils5.InternalServerError("Failed to get division.");
727
+ }
728
+ }
729
+ }
730
+ async function updateFieldById({ _id, field, value } = {}, session) {
731
+ const allowedFields = ["name"];
732
+ if (!allowedFields.includes(field)) {
733
+ throw new import_nodejs_utils5.BadRequestError(
734
+ `Field "${field}" is not allowed to be updated.`
735
+ );
736
+ }
737
+ try {
738
+ _id = new import_mongodb4.ObjectId(_id);
739
+ } catch (error) {
740
+ throw new import_nodejs_utils5.BadRequestError("Invalid ID.");
741
+ }
742
+ try {
743
+ await collection.updateOne(
744
+ { _id, deletedAt: { $in: ["", null] } },
745
+ { $set: { [field]: value, updatedAt: (/* @__PURE__ */ new Date()).toISOString() } },
746
+ { session }
747
+ );
748
+ delCachedData();
749
+ return `Successfully updated division ${field}.`;
750
+ } catch (error) {
751
+ throw new import_nodejs_utils5.InternalServerError(`Failed to update division ${field}.`);
752
+ }
753
+ }
754
+ async function deleteById(_id) {
755
+ try {
756
+ _id = new import_mongodb4.ObjectId(_id);
757
+ } catch (error) {
758
+ throw new import_nodejs_utils5.BadRequestError("Invalid ID.");
759
+ }
760
+ try {
761
+ await collection.updateOne(
762
+ { _id },
763
+ { $set: { deletedAt: (/* @__PURE__ */ new Date()).toISOString() } }
764
+ );
765
+ delCachedData();
766
+ return "Successfully deleted division.";
767
+ } catch (error) {
768
+ throw new import_nodejs_utils5.InternalServerError("Failed to delete division.");
769
+ }
770
+ }
771
+ return {
772
+ createIndexes,
773
+ add,
774
+ getAll,
775
+ getById,
776
+ updateFieldById,
777
+ deleteById,
778
+ getByName
779
+ };
780
+ }
781
+
782
+ // src/controllers/division.controller.ts
783
+ var import_nodejs_utils6 = require("@eeplatform/nodejs-utils");
784
+ var import_joi4 = __toESM(require("joi"));
785
+ function useDivisionController() {
786
+ const {
787
+ add: _add,
788
+ getAll: _getAll,
789
+ getById: _getById,
790
+ getByName: _getByName,
791
+ updateFieldById: _updateFieldById,
792
+ deleteById: _deleteById
793
+ } = useDivisionRepo();
794
+ async function add(req, res, next) {
795
+ const value = req.body;
796
+ const { error } = schemaDivision.validate(value);
797
+ if (error) {
798
+ next(new import_nodejs_utils6.BadRequestError(error.message));
799
+ return;
800
+ }
801
+ try {
802
+ const data = await _add(value);
803
+ res.json({
804
+ message: "Successfully created division.",
805
+ data
806
+ });
807
+ return;
808
+ } catch (error2) {
809
+ next(error2);
810
+ }
811
+ }
812
+ async function getAll(req, res, next) {
813
+ const query = req.query;
814
+ const validation = import_joi4.default.object({
815
+ page: import_joi4.default.number().min(1).optional().allow("", null),
816
+ limit: import_joi4.default.number().min(1).optional().allow("", null),
817
+ search: import_joi4.default.string().optional().allow("", null),
818
+ status: import_joi4.default.string().optional().allow("", null)
819
+ });
820
+ const { error } = validation.validate(query);
821
+ const page = typeof req.query.page === "string" ? Number(req.query.page) : 1;
822
+ const limit = typeof req.query.limit === "string" ? Number(req.query.limit) : 10;
823
+ const search = req.query.search ?? "";
824
+ const status = req.query.status ?? "active";
825
+ const isPageNumber = isFinite(page);
826
+ if (!isPageNumber) {
827
+ next(new import_nodejs_utils6.BadRequestError("Invalid page number."));
828
+ return;
829
+ }
830
+ const isLimitNumber = isFinite(limit);
831
+ if (!isLimitNumber) {
832
+ next(new import_nodejs_utils6.BadRequestError("Invalid limit number."));
833
+ return;
834
+ }
835
+ if (error) {
836
+ next(new import_nodejs_utils6.BadRequestError(error.message));
837
+ return;
838
+ }
839
+ try {
840
+ const data = await _getAll({ page, limit, search, status });
841
+ res.json(data);
842
+ return;
843
+ } catch (error2) {
844
+ next(error2);
845
+ }
846
+ }
847
+ async function getById(req, res, next) {
848
+ const id = req.params.id;
849
+ const validation = import_joi4.default.object({
850
+ id: import_joi4.default.string().hex().required()
851
+ });
852
+ const { error } = validation.validate({ id });
853
+ if (error) {
854
+ next(new import_nodejs_utils6.BadRequestError(error.message));
855
+ return;
856
+ }
857
+ try {
858
+ const data = await _getById(id);
859
+ res.json({
860
+ message: "Successfully retrieved division.",
861
+ data
862
+ });
863
+ return;
864
+ } catch (error2) {
865
+ next(error2);
866
+ }
867
+ }
868
+ async function getByName(req, res, next) {
869
+ const name = req.params.name;
870
+ const validation = import_joi4.default.object({
871
+ name: import_joi4.default.string().required()
872
+ });
873
+ const { error } = validation.validate({ name });
874
+ if (error) {
875
+ next(new import_nodejs_utils6.BadRequestError(error.message));
876
+ return;
877
+ }
878
+ try {
879
+ const data = await _getByName(name);
880
+ res.json({
881
+ message: "Successfully retrieved division.",
882
+ data
883
+ });
884
+ return;
885
+ } catch (error2) {
886
+ next(error2);
887
+ }
888
+ }
889
+ async function updateField(req, res, next) {
890
+ const _id = req.params.id;
891
+ const { field, value } = req.body;
892
+ const validation = import_joi4.default.object({
893
+ _id: import_joi4.default.string().hex().required(),
894
+ field: import_joi4.default.string().valid("name", "director", "directorName").required(),
895
+ value: import_joi4.default.string().required()
896
+ });
897
+ const { error } = validation.validate({ _id, field, value });
898
+ if (error) {
899
+ next(new import_nodejs_utils6.BadRequestError(error.message));
900
+ return;
901
+ }
902
+ try {
903
+ const message = await _updateFieldById({ _id, field, value });
904
+ res.json({ message });
905
+ return;
906
+ } catch (error2) {
907
+ next(error2);
908
+ }
909
+ }
910
+ async function deleteById(req, res, next) {
911
+ const _id = req.params.id;
912
+ const validation = import_joi4.default.object({
913
+ _id: import_joi4.default.string().hex().required()
914
+ });
915
+ const { error } = validation.validate({ _id });
916
+ if (error) {
917
+ next(new import_nodejs_utils6.BadRequestError(error.message));
918
+ return;
919
+ }
920
+ try {
921
+ const message = await _deleteById(_id);
922
+ res.json({ message });
923
+ return;
924
+ } catch (error2) {
925
+ next(error2);
926
+ }
927
+ }
928
+ return {
929
+ add,
930
+ getAll,
931
+ getById,
932
+ getByName,
933
+ updateField,
934
+ deleteById
935
+ };
936
+ }
937
+
938
+ // src/models/school.model.ts
939
+ var import_nodejs_utils7 = require("@eeplatform/nodejs-utils");
940
+ var import_joi5 = __toESM(require("joi"));
941
+ var import_mongodb5 = require("mongodb");
942
+ var schemaSchool = import_joi5.default.object({
943
+ _id: import_joi5.default.string().hex().optional().allow(null, ""),
944
+ name: import_joi5.default.string().min(1).max(100).required(),
945
+ region: import_joi5.default.string().hex().optional().allow(null, ""),
946
+ regionName: import_joi5.default.string().min(1).max(100).optional().allow(null, ""),
947
+ division: import_joi5.default.string().hex().optional().allow(null, ""),
948
+ divisionName: import_joi5.default.string().min(1).max(100).optional().allow(null, ""),
949
+ principal: import_joi5.default.string().hex().optional().allow(null, ""),
950
+ principalName: import_joi5.default.string().min(1).max(100).optional().allow(null, ""),
951
+ createdAt: import_joi5.default.string().isoDate().optional(),
952
+ updatedAt: import_joi5.default.string().isoDate().optional(),
953
+ deletedAt: import_joi5.default.string().isoDate().optional().allow(null, "")
954
+ });
955
+ function modelSchool(value) {
956
+ const { error } = schemaSchool.validate(value);
957
+ if (error) {
958
+ throw new import_nodejs_utils7.BadRequestError(`Invalid sdo data: ${error.message}`);
959
+ }
960
+ if (value._id && typeof value._id === "string") {
961
+ try {
962
+ value._id = import_mongodb5.ObjectId.createFromTime(value._id);
963
+ } catch (error2) {
964
+ throw new Error("Invalid _id.");
965
+ }
966
+ }
967
+ return {
968
+ _id: value._id,
969
+ name: value.name,
970
+ region: value.region,
971
+ regionName: value.regionName ?? "",
972
+ division: value.division,
973
+ divisionName: value.divisionName ?? "",
974
+ principal: value.principal,
975
+ principalName: value.principalName ?? "",
976
+ createdAt: value.createdAt ?? (/* @__PURE__ */ new Date()).toISOString(),
977
+ updatedAt: value.updatedAt ?? "",
978
+ deletedAt: value.deletedAt ?? ""
979
+ };
980
+ }
981
+
982
+ // src/repositories/school.repository.ts
983
+ var import_nodejs_utils8 = require("@eeplatform/nodejs-utils");
984
+ var import_mongodb6 = require("mongodb");
985
+ function useSchoolRepo() {
986
+ const db = import_nodejs_utils8.useAtlas.getDb();
987
+ if (!db) {
988
+ throw new Error("Unable to connect to server.");
989
+ }
990
+ const namespace_collection = "deped.schools";
991
+ const collection = db.collection(namespace_collection);
992
+ const { getCache, setCache, delNamespace } = (0, import_nodejs_utils8.useCache)(namespace_collection);
993
+ async function createIndexes() {
994
+ try {
995
+ await collection.createIndexes([
996
+ { key: { name: 1 } },
997
+ { key: { createdAt: 1 } },
998
+ { key: { name: "text" } },
999
+ { key: { name: 1 }, unique: true, name: "unique_name" }
1000
+ ]);
1001
+ } catch (error) {
1002
+ throw new Error("Failed to create index on schools.");
1003
+ }
1004
+ }
1005
+ function delCachedData() {
1006
+ delNamespace().then(() => {
1007
+ import_nodejs_utils8.logger.log({
1008
+ level: "info",
1009
+ message: `Cache namespace cleared for ${namespace_collection}`
1010
+ });
1011
+ }).catch((err) => {
1012
+ import_nodejs_utils8.logger.log({
1013
+ level: "error",
1014
+ message: `Failed to clear cache namespace for ${namespace_collection}: ${err.message}`
1015
+ });
1016
+ });
1017
+ }
1018
+ async function add(value, session) {
1019
+ try {
1020
+ value = modelSchool(value);
1021
+ const res = await collection.insertOne(value, { session });
1022
+ delCachedData();
1023
+ return res.insertedId;
1024
+ } catch (error) {
1025
+ import_nodejs_utils8.logger.log({
1026
+ level: "error",
1027
+ message: error.message
1028
+ });
1029
+ if (error instanceof import_nodejs_utils8.AppError) {
1030
+ throw error;
1031
+ } else {
1032
+ const isDuplicated = error.message.includes("duplicate");
1033
+ if (isDuplicated) {
1034
+ throw new import_nodejs_utils8.BadRequestError("School already exists.");
1035
+ }
1036
+ throw new Error("Failed to create school.");
1037
+ }
1038
+ }
1039
+ }
1040
+ async function getAll({
1041
+ search = "",
1042
+ page = 1,
1043
+ limit = 10,
1044
+ sort = {},
1045
+ status = "active"
1046
+ } = {}) {
1047
+ page = page > 0 ? page - 1 : 0;
1048
+ const query = {
1049
+ deletedAt: { $in: ["", null] },
1050
+ status
1051
+ };
1052
+ sort = Object.keys(sort).length > 0 ? sort : { _id: 1 };
1053
+ const cacheKeyOptions = {
1054
+ status,
1055
+ page,
1056
+ limit,
1057
+ sort: JSON.stringify(sort)
1058
+ };
1059
+ if (search) {
1060
+ query.$text = { $search: search };
1061
+ cacheKeyOptions.search = search;
1062
+ }
1063
+ const cacheKey = (0, import_nodejs_utils8.makeCacheKey)(namespace_collection, cacheKeyOptions);
1064
+ import_nodejs_utils8.logger.log({
1065
+ level: "info",
1066
+ message: `Cache key for getAll schools: ${cacheKey}`
1067
+ });
1068
+ try {
1069
+ const cached = await getCache(cacheKey);
1070
+ if (cached) {
1071
+ import_nodejs_utils8.logger.log({
1072
+ level: "info",
1073
+ message: `Cache hit for getAll schools: ${cacheKey}`
1074
+ });
1075
+ return cached;
1076
+ }
1077
+ const items = await collection.aggregate([
1078
+ { $match: query },
1079
+ { $sort: sort },
1080
+ { $skip: page * limit },
1081
+ { $limit: limit }
1082
+ ]).toArray();
1083
+ const length = await collection.countDocuments(query);
1084
+ const data = (0, import_nodejs_utils8.paginate)(items, page, limit, length);
1085
+ setCache(cacheKey, data, 600).then(() => {
1086
+ import_nodejs_utils8.logger.log({
1087
+ level: "info",
1088
+ message: `Cache set for getAll schools: ${cacheKey}`
1089
+ });
1090
+ }).catch((err) => {
1091
+ import_nodejs_utils8.logger.log({
1092
+ level: "error",
1093
+ message: `Failed to set cache for getAll schools: ${err.message}`
1094
+ });
1095
+ });
1096
+ return data;
1097
+ } catch (error) {
1098
+ import_nodejs_utils8.logger.log({ level: "error", message: `${error}` });
1099
+ throw error;
1100
+ }
1101
+ }
1102
+ async function getById(_id) {
1103
+ try {
1104
+ _id = new import_mongodb6.ObjectId(_id);
1105
+ } catch (error) {
1106
+ throw new import_nodejs_utils8.BadRequestError("Invalid ID.");
1107
+ }
1108
+ const cacheKey = (0, import_nodejs_utils8.makeCacheKey)(namespace_collection, { _id: String(_id) });
1109
+ try {
1110
+ const cached = await getCache(cacheKey);
1111
+ if (cached) {
1112
+ import_nodejs_utils8.logger.log({
1113
+ level: "info",
1114
+ message: `Cache hit for getById school: ${cacheKey}`
1115
+ });
1116
+ return cached;
1117
+ }
1118
+ const result = await collection.findOne({
1119
+ _id,
1120
+ deletedAt: { $in: ["", null] }
1121
+ });
1122
+ if (!result) {
1123
+ throw new import_nodejs_utils8.BadRequestError("School not found.");
1124
+ }
1125
+ setCache(cacheKey, result, 300).then(() => {
1126
+ import_nodejs_utils8.logger.log({
1127
+ level: "info",
1128
+ message: `Cache set for school by id: ${cacheKey}`
1129
+ });
1130
+ }).catch((err) => {
1131
+ import_nodejs_utils8.logger.log({
1132
+ level: "error",
1133
+ message: `Failed to set cache for school by id: ${err.message}`
1134
+ });
1135
+ });
1136
+ return result;
1137
+ } catch (error) {
1138
+ if (error instanceof import_nodejs_utils8.AppError) {
1139
+ throw error;
1140
+ } else {
1141
+ throw new import_nodejs_utils8.InternalServerError("Failed to get school.");
1142
+ }
1143
+ }
1144
+ }
1145
+ async function getByName(name) {
1146
+ const cacheKey = (0, import_nodejs_utils8.makeCacheKey)(namespace_collection, { name });
1147
+ try {
1148
+ const cached = await getCache(cacheKey);
1149
+ if (cached) {
1150
+ import_nodejs_utils8.logger.log({
1151
+ level: "info",
1152
+ message: `Cache hit for getByName school: ${cacheKey}`
1153
+ });
1154
+ return cached;
1155
+ }
1156
+ const result = await collection.findOne({
1157
+ name,
1158
+ deletedAt: { $in: ["", null] }
1159
+ });
1160
+ if (!result) {
1161
+ throw new import_nodejs_utils8.BadRequestError("School not found.");
1162
+ }
1163
+ setCache(cacheKey, result, 300).then(() => {
1164
+ import_nodejs_utils8.logger.log({
1165
+ level: "info",
1166
+ message: `Cache set for school by name: ${cacheKey}`
1167
+ });
1168
+ }).catch((err) => {
1169
+ import_nodejs_utils8.logger.log({
1170
+ level: "error",
1171
+ message: `Failed to set cache for school by name: ${err.message}`
1172
+ });
1173
+ });
1174
+ return result;
1175
+ } catch (error) {
1176
+ if (error instanceof import_nodejs_utils8.AppError) {
1177
+ throw error;
1178
+ } else {
1179
+ throw new import_nodejs_utils8.InternalServerError("Failed to get school.");
1180
+ }
1181
+ }
1182
+ }
1183
+ async function updateFieldById({ _id, field, value } = {}, session) {
1184
+ const allowedFields = ["name"];
1185
+ if (!allowedFields.includes(field)) {
1186
+ throw new import_nodejs_utils8.BadRequestError(
1187
+ `Field "${field}" is not allowed to be updated.`
1188
+ );
1189
+ }
1190
+ try {
1191
+ _id = new import_mongodb6.ObjectId(_id);
1192
+ } catch (error) {
1193
+ throw new import_nodejs_utils8.BadRequestError("Invalid ID.");
1194
+ }
1195
+ try {
1196
+ await collection.updateOne(
1197
+ { _id, deletedAt: { $in: ["", null] } },
1198
+ { $set: { [field]: value, updatedAt: (/* @__PURE__ */ new Date()).toISOString() } },
1199
+ { session }
1200
+ );
1201
+ delCachedData();
1202
+ return `Successfully updated school ${field}.`;
1203
+ } catch (error) {
1204
+ throw new import_nodejs_utils8.InternalServerError(`Failed to update school ${field}.`);
1205
+ }
1206
+ }
1207
+ async function deleteById(_id) {
1208
+ try {
1209
+ _id = new import_mongodb6.ObjectId(_id);
1210
+ } catch (error) {
1211
+ throw new import_nodejs_utils8.BadRequestError("Invalid ID.");
1212
+ }
1213
+ try {
1214
+ await collection.updateOne(
1215
+ { _id },
1216
+ { $set: { deletedAt: (/* @__PURE__ */ new Date()).toISOString() } }
1217
+ );
1218
+ delCachedData();
1219
+ return "Successfully deleted school.";
1220
+ } catch (error) {
1221
+ throw new import_nodejs_utils8.InternalServerError("Failed to delete school.");
1222
+ }
1223
+ }
1224
+ return {
1225
+ createIndexes,
1226
+ add,
1227
+ getAll,
1228
+ getById,
1229
+ updateFieldById,
1230
+ deleteById,
1231
+ getByName
1232
+ };
1233
+ }
1234
+
1235
+ // src/controllers/school.controller.ts
1236
+ var import_nodejs_utils9 = require("@eeplatform/nodejs-utils");
1237
+ var import_joi6 = __toESM(require("joi"));
1238
+ function useSchoolController() {
1239
+ const {
1240
+ add: _add,
1241
+ getAll: _getAll,
1242
+ getById: _getById,
1243
+ getByName: _getByName,
1244
+ updateFieldById: _updateFieldById,
1245
+ deleteById: _deleteById
1246
+ } = useSchoolRepo();
1247
+ async function add(req, res, next) {
1248
+ const value = req.body;
1249
+ const { error } = schemaSchool.validate(value);
1250
+ if (error) {
1251
+ next(new import_nodejs_utils9.BadRequestError(error.message));
1252
+ return;
1253
+ }
1254
+ try {
1255
+ const data = await _add(value);
1256
+ res.json({
1257
+ message: "Successfully created school.",
1258
+ data
1259
+ });
1260
+ return;
1261
+ } catch (error2) {
1262
+ next(error2);
1263
+ }
1264
+ }
1265
+ async function getAll(req, res, next) {
1266
+ const query = req.query;
1267
+ const validation = import_joi6.default.object({
1268
+ page: import_joi6.default.number().min(1).optional().allow("", null),
1269
+ limit: import_joi6.default.number().min(1).optional().allow("", null),
1270
+ search: import_joi6.default.string().optional().allow("", null),
1271
+ status: import_joi6.default.string().optional().allow("", null)
1272
+ });
1273
+ const { error } = validation.validate(query);
1274
+ const page = typeof req.query.page === "string" ? Number(req.query.page) : 1;
1275
+ const limit = typeof req.query.limit === "string" ? Number(req.query.limit) : 10;
1276
+ const search = req.query.search ?? "";
1277
+ const status = req.query.status ?? "active";
1278
+ const isPageNumber = isFinite(page);
1279
+ if (!isPageNumber) {
1280
+ next(new import_nodejs_utils9.BadRequestError("Invalid page number."));
1281
+ return;
1282
+ }
1283
+ const isLimitNumber = isFinite(limit);
1284
+ if (!isLimitNumber) {
1285
+ next(new import_nodejs_utils9.BadRequestError("Invalid limit number."));
1286
+ return;
1287
+ }
1288
+ if (error) {
1289
+ next(new import_nodejs_utils9.BadRequestError(error.message));
1290
+ return;
1291
+ }
1292
+ try {
1293
+ const data = await _getAll({ page, limit, search, status });
1294
+ res.json(data);
1295
+ return;
1296
+ } catch (error2) {
1297
+ next(error2);
1298
+ }
1299
+ }
1300
+ async function getById(req, res, next) {
1301
+ const id = req.params.id;
1302
+ const validation = import_joi6.default.object({
1303
+ id: import_joi6.default.string().hex().required()
1304
+ });
1305
+ const { error } = validation.validate({ id });
1306
+ if (error) {
1307
+ next(new import_nodejs_utils9.BadRequestError(error.message));
1308
+ return;
1309
+ }
1310
+ try {
1311
+ const data = await _getById(id);
1312
+ res.json({
1313
+ message: "Successfully retrieved school.",
1314
+ data
1315
+ });
1316
+ return;
1317
+ } catch (error2) {
1318
+ next(error2);
1319
+ }
1320
+ }
1321
+ async function getByName(req, res, next) {
1322
+ const name = req.params.name;
1323
+ const validation = import_joi6.default.object({
1324
+ name: import_joi6.default.string().required()
1325
+ });
1326
+ const { error } = validation.validate({ name });
1327
+ if (error) {
1328
+ next(new import_nodejs_utils9.BadRequestError(error.message));
1329
+ return;
1330
+ }
1331
+ try {
1332
+ const data = await _getByName(name);
1333
+ res.json({
1334
+ message: "Successfully retrieved school.",
1335
+ data
1336
+ });
1337
+ return;
1338
+ } catch (error2) {
1339
+ next(error2);
1340
+ }
1341
+ }
1342
+ async function updateField(req, res, next) {
1343
+ const _id = req.params.id;
1344
+ const { field, value } = req.body;
1345
+ const validation = import_joi6.default.object({
1346
+ _id: import_joi6.default.string().hex().required(),
1347
+ field: import_joi6.default.string().valid("name", "director", "directorName").required(),
1348
+ value: import_joi6.default.string().required()
1349
+ });
1350
+ const { error } = validation.validate({ _id, field, value });
1351
+ if (error) {
1352
+ next(new import_nodejs_utils9.BadRequestError(error.message));
1353
+ return;
1354
+ }
1355
+ try {
1356
+ const message = await _updateFieldById({ _id, field, value });
1357
+ res.json({ message });
1358
+ return;
1359
+ } catch (error2) {
1360
+ next(error2);
1361
+ }
1362
+ }
1363
+ async function deleteById(req, res, next) {
1364
+ const _id = req.params.id;
1365
+ const validation = import_joi6.default.object({
1366
+ _id: import_joi6.default.string().hex().required()
1367
+ });
1368
+ const { error } = validation.validate({ _id });
1369
+ if (error) {
1370
+ next(new import_nodejs_utils9.BadRequestError(error.message));
1371
+ return;
1372
+ }
1373
+ try {
1374
+ const message = await _deleteById(_id);
1375
+ res.json({ message });
1376
+ return;
1377
+ } catch (error2) {
1378
+ next(error2);
1379
+ }
1380
+ }
1381
+ return {
1382
+ add,
1383
+ getAll,
1384
+ getById,
1385
+ getByName,
1386
+ updateField,
1387
+ deleteById
1388
+ };
1389
+ }
1390
+ // Annotate the CommonJS export names for ESM import in node:
1391
+ 0 && (module.exports = {
1392
+ modelDivision,
1393
+ modelRegion,
1394
+ modelSchool,
1395
+ schemaDivision,
1396
+ schemaRegion,
1397
+ schemaSchool,
1398
+ useDivisionController,
1399
+ useDivisionRepo,
1400
+ useRegionController,
1401
+ useRegionRepo,
1402
+ useSchoolController,
1403
+ useSchoolRepo
1404
+ });
1405
+ //# sourceMappingURL=index.js.map