@eeplatform/core 1.7.2 → 1.8.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.mjs CHANGED
@@ -2175,11 +2175,13 @@ function useRoleRepo() {
2175
2175
  throw new InternalServerError8("Failed to create unique index on role.");
2176
2176
  }
2177
2177
  }
2178
- async function addRole(value, session) {
2178
+ async function addRole(value, session, clearCache = true) {
2179
2179
  value = new MRole(value);
2180
2180
  try {
2181
2181
  const res = await collection.insertOne(value, { session });
2182
- delCachedData();
2182
+ if (clearCache) {
2183
+ delCachedData();
2184
+ }
2183
2185
  return res.insertedId;
2184
2186
  } catch (error) {
2185
2187
  logger7.log({ level: "error", message: `${error}` });
@@ -2452,7 +2454,8 @@ function useRoleRepo() {
2452
2454
  getRoleByName,
2453
2455
  updateRole,
2454
2456
  deleteRole,
2455
- updatePermissionsById
2457
+ updatePermissionsById,
2458
+ delCachedData
2456
2459
  };
2457
2460
  }
2458
2461
 
@@ -3842,6 +3845,7 @@ function useRoleController() {
3842
3845
  // src/resources/file/file.service.ts
3843
3846
  import { logger as logger11, useS3 as useS32, useAtlas as useAtlas11 } from "@eeplatform/nodejs-utils";
3844
3847
  import cron from "node-cron";
3848
+ import * as fs from "fs";
3845
3849
  function useFileService() {
3846
3850
  const {
3847
3851
  createFile: _createFile,
@@ -3865,12 +3869,23 @@ function useFileService() {
3865
3869
  };
3866
3870
  try {
3867
3871
  const id = await _createFile(file, session);
3872
+ const fileBuffer = value.buffer || await fs.promises.readFile(value.path);
3868
3873
  await s3.uploadObject({
3869
3874
  key: id,
3870
- body: value.buffer,
3875
+ body: fileBuffer,
3871
3876
  contentType: value.mimetype
3872
3877
  });
3873
3878
  await session?.commitTransaction();
3879
+ if (value.path) {
3880
+ try {
3881
+ await fs.promises.unlink(value.path);
3882
+ } catch (cleanupError) {
3883
+ console.error(
3884
+ `Failed to cleanup temporary file ${value.path}:`,
3885
+ cleanupError
3886
+ );
3887
+ }
3888
+ }
3874
3889
  return id;
3875
3890
  } catch (error) {
3876
3891
  await session?.abortTransaction();
@@ -5907,7 +5922,7 @@ function useCounterRepo() {
5907
5922
 
5908
5923
  // src/resources/utils/gemini.service.ts
5909
5924
  import { GoogleGenerativeAI } from "@google/generative-ai";
5910
- import fs from "fs";
5925
+ import fs2 from "fs";
5911
5926
  import path from "path";
5912
5927
  var genAI = new GoogleGenerativeAI(GEMINI_API_KEY);
5913
5928
  var SUPPORTED_AUDIO_FORMATS = [
@@ -5927,7 +5942,7 @@ function useGeminiAiService() {
5927
5942
  };
5928
5943
  const readAudioFile = async (filePath) => {
5929
5944
  try {
5930
- const audioBuffer = await fs.promises.readFile(filePath);
5945
+ const audioBuffer = await fs2.promises.readFile(filePath);
5931
5946
  const extension = path.extname(filePath).toLowerCase();
5932
5947
  const mimeTypeMap = {
5933
5948
  ".wav": "audio/wav",
@@ -6265,7 +6280,7 @@ function useGitHubService() {
6265
6280
  const octokit = new Octokit({ auth: githubToken });
6266
6281
  const { owner, repo } = parseRepoUrl(repoUrl);
6267
6282
  await checkAdminPermission(owner, repo, octokit);
6268
- const lines = keyValues.split(/[\n\r\s\t]+/).map((l) => l.trim()).filter(Boolean);
6283
+ const lines = keyValues.split(";").map((l) => l.trim()).filter(Boolean);
6269
6284
  for (const line of lines) {
6270
6285
  const equalIndex = line.indexOf("=");
6271
6286
  if (equalIndex === -1)
@@ -6890,7 +6905,7 @@ function useUtilController() {
6890
6905
  availableEndpoints: [
6891
6906
  "POST /github/variables - Set GitHub environment variables or secrets"
6892
6907
  ],
6893
- keyValueFormat: "KEY=value pairs separated by newlines, spaces, or tabs"
6908
+ keyValueFormat: "KEY=value pairs separated by semicolons"
6894
6909
  }
6895
6910
  });
6896
6911
  } catch (error) {
@@ -6944,14 +6959,14 @@ function useUtilController() {
6944
6959
  );
6945
6960
  return;
6946
6961
  }
6947
- const lines = keyValues.split(/[\n\r\s\t]+/).map((l) => l.trim()).filter(Boolean);
6962
+ const lines = keyValues.split(";").map((l) => l.trim()).filter(Boolean);
6948
6963
  const invalidLines = lines.filter(
6949
6964
  (line) => !line.includes("=") || line.indexOf("=") === -1
6950
6965
  );
6951
6966
  if (invalidLines.length > 0) {
6952
6967
  next(
6953
6968
  new BadRequestError33(
6954
- "Invalid key-value format. Each pair should be in format: KEY=value. Pairs can be separated by newlines, spaces, or tabs."
6969
+ "Invalid key-value format. Each pair should be in format: KEY=value. Pairs should be separated by semicolons."
6955
6970
  )
6956
6971
  );
6957
6972
  return;
@@ -7024,6 +7039,297 @@ var transactionSchema = Joi17.object({
7024
7039
  updatedAt: Joi17.string().optional().allow("", null),
7025
7040
  deletedAt: Joi17.string().optional().allow("", null)
7026
7041
  });
7042
+
7043
+ // src/resources/phillipine-std-geo-code/psgc.model.ts
7044
+ import Joi18 from "joi";
7045
+ var schemaPSGC = Joi18.object({
7046
+ code: Joi18.number().required(),
7047
+ name: Joi18.string().required(),
7048
+ type: Joi18.string().valid("Reg", "Prov", "City", "Mun", "Bgy").required()
7049
+ });
7050
+ function modelPSGC(data) {
7051
+ const { error } = schemaPSGC.validate(data);
7052
+ if (error) {
7053
+ throw new Error(`Invalid PSGC data: ${error.message}`);
7054
+ }
7055
+ return {
7056
+ code: data.code,
7057
+ name: data.name,
7058
+ type: data.type
7059
+ };
7060
+ }
7061
+
7062
+ // src/resources/phillipine-std-geo-code/psgc.repository.ts
7063
+ import {
7064
+ AppError as AppError14,
7065
+ BadRequestError as BadRequestError34,
7066
+ InternalServerError as InternalServerError20,
7067
+ logger as logger19,
7068
+ makeCacheKey as makeCacheKey13,
7069
+ paginate as paginate8,
7070
+ useAtlas as useAtlas18,
7071
+ useCache as useCache14
7072
+ } from "@eeplatform/nodejs-utils";
7073
+ import { ObjectId as ObjectId21 } from "mongodb";
7074
+ function usePSGCRepo() {
7075
+ const db = useAtlas18.getDb();
7076
+ if (!db) {
7077
+ throw new Error("Unable to connect to server.");
7078
+ }
7079
+ const namespace_collection = "philippine.standard.geographic.codes";
7080
+ const collection = db.collection(namespace_collection);
7081
+ const { getCache, setCache, delNamespace } = useCache14(namespace_collection);
7082
+ async function createIndexes() {
7083
+ try {
7084
+ await collection.createIndexes([
7085
+ { key: { name: 1 } },
7086
+ { key: { name: "text" } },
7087
+ { key: { code: 1 }, unique: true, name: "unique_code" }
7088
+ ]);
7089
+ } catch (error) {
7090
+ throw new Error("Failed to create index on PSGC.");
7091
+ }
7092
+ }
7093
+ function delCachedData() {
7094
+ delNamespace().then(() => {
7095
+ logger19.log({
7096
+ level: "info",
7097
+ message: `Cache namespace cleared for ${namespace_collection}`
7098
+ });
7099
+ }).catch((err) => {
7100
+ logger19.log({
7101
+ level: "error",
7102
+ message: `Failed to clear cache namespace for ${namespace_collection}: ${err.message}`
7103
+ });
7104
+ });
7105
+ }
7106
+ async function add(value, session) {
7107
+ try {
7108
+ value = modelPSGC(value);
7109
+ const res = await collection.insertOne(value, { session });
7110
+ delCachedData();
7111
+ return res.insertedId;
7112
+ } catch (error) {
7113
+ logger19.log({
7114
+ level: "error",
7115
+ message: error.message
7116
+ });
7117
+ if (error instanceof AppError14) {
7118
+ throw error;
7119
+ } else {
7120
+ const isDuplicated = error.message.includes("duplicate");
7121
+ if (isDuplicated) {
7122
+ throw new BadRequestError34("Region already exists.");
7123
+ }
7124
+ throw new Error("Failed to create PSGC.");
7125
+ }
7126
+ }
7127
+ }
7128
+ async function getAll({
7129
+ search = "",
7130
+ page = 1,
7131
+ limit = 10,
7132
+ sort = {},
7133
+ status = "active"
7134
+ } = {}) {
7135
+ page = page > 0 ? page - 1 : 0;
7136
+ const query = {
7137
+ deletedAt: { $in: ["", null] },
7138
+ status
7139
+ };
7140
+ sort = Object.keys(sort).length > 0 ? sort : { _id: 1 };
7141
+ const cacheKeyOptions = {
7142
+ status,
7143
+ page,
7144
+ limit,
7145
+ sort: JSON.stringify(sort)
7146
+ };
7147
+ if (search) {
7148
+ query.$text = { $search: search };
7149
+ cacheKeyOptions.search = search;
7150
+ }
7151
+ const cacheKey = makeCacheKey13(namespace_collection, cacheKeyOptions);
7152
+ logger19.log({
7153
+ level: "info",
7154
+ message: `Cache key for getAll PSGC: ${cacheKey}`
7155
+ });
7156
+ try {
7157
+ const cached = await getCache(cacheKey);
7158
+ if (cached) {
7159
+ logger19.log({
7160
+ level: "info",
7161
+ message: `Cache hit for getAll PSGC: ${cacheKey}`
7162
+ });
7163
+ return cached;
7164
+ }
7165
+ const items = await collection.aggregate([
7166
+ { $match: query },
7167
+ { $sort: sort },
7168
+ { $skip: page * limit },
7169
+ { $limit: limit }
7170
+ ]).toArray();
7171
+ const length = await collection.countDocuments(query);
7172
+ const data = paginate8(items, page, limit, length);
7173
+ setCache(cacheKey, data, 600).then(() => {
7174
+ logger19.log({
7175
+ level: "info",
7176
+ message: `Cache set for getAll PSGC: ${cacheKey}`
7177
+ });
7178
+ }).catch((err) => {
7179
+ logger19.log({
7180
+ level: "error",
7181
+ message: `Failed to set cache for getAll PSGC: ${err.message}`
7182
+ });
7183
+ });
7184
+ return data;
7185
+ } catch (error) {
7186
+ logger19.log({ level: "error", message: `${error}` });
7187
+ throw error;
7188
+ }
7189
+ }
7190
+ async function getById(_id) {
7191
+ try {
7192
+ _id = new ObjectId21(_id);
7193
+ } catch (error) {
7194
+ throw new BadRequestError34("Invalid ID.");
7195
+ }
7196
+ const cacheKey = makeCacheKey13(namespace_collection, { _id: String(_id) });
7197
+ try {
7198
+ const cached = await getCache(cacheKey);
7199
+ if (cached) {
7200
+ logger19.log({
7201
+ level: "info",
7202
+ message: `Cache hit for getById PSGC: ${cacheKey}`
7203
+ });
7204
+ return cached;
7205
+ }
7206
+ const result = await collection.findOne({
7207
+ _id,
7208
+ deletedAt: { $in: ["", null] }
7209
+ });
7210
+ if (!result) {
7211
+ throw new BadRequestError34("Region not found.");
7212
+ }
7213
+ setCache(cacheKey, result, 300).then(() => {
7214
+ logger19.log({
7215
+ level: "info",
7216
+ message: `Cache set for PSGC by id: ${cacheKey}`
7217
+ });
7218
+ }).catch((err) => {
7219
+ logger19.log({
7220
+ level: "error",
7221
+ message: `Failed to set cache for PSGC by id: ${err.message}`
7222
+ });
7223
+ });
7224
+ return result;
7225
+ } catch (error) {
7226
+ if (error instanceof AppError14) {
7227
+ throw error;
7228
+ } else {
7229
+ throw new InternalServerError20("Failed to get PSGC.");
7230
+ }
7231
+ }
7232
+ }
7233
+ async function getByName({ name, cityMunicipality = false, code = 0, type = "" } = {}) {
7234
+ const query = { $text: { $search: name } };
7235
+ const cacheKeyOptions = { name };
7236
+ if (cityMunicipality) {
7237
+ query.type = { $in: ["City", "Mun"] };
7238
+ cacheKeyOptions.type = cityMunicipality;
7239
+ }
7240
+ if (type && !cityMunicipality) {
7241
+ query.type = type;
7242
+ cacheKeyOptions.type = type;
7243
+ }
7244
+ if (code) {
7245
+ query.code = { $gt: code };
7246
+ if (cityMunicipality) {
7247
+ query.code.$lt = code + 1e6;
7248
+ }
7249
+ cacheKeyOptions.code = code;
7250
+ }
7251
+ const cacheKey = makeCacheKey13(namespace_collection, { name });
7252
+ try {
7253
+ const cached = await getCache(cacheKey);
7254
+ if (cached) {
7255
+ logger19.log({
7256
+ level: "info",
7257
+ message: `Cache hit for getByName PSGC: ${cacheKey}`
7258
+ });
7259
+ return cached;
7260
+ }
7261
+ const result = await collection.findOne(query);
7262
+ setCache(cacheKey, result, 300).then(() => {
7263
+ logger19.log({
7264
+ level: "info",
7265
+ message: `Cache set for PSGC by name: ${cacheKey}`
7266
+ });
7267
+ }).catch((err) => {
7268
+ logger19.log({
7269
+ level: "error",
7270
+ message: `Failed to set cache for PSGC by name: ${err.message}`
7271
+ });
7272
+ });
7273
+ return result;
7274
+ } catch (error) {
7275
+ if (error instanceof AppError14) {
7276
+ throw error;
7277
+ } else {
7278
+ throw new InternalServerError20("Failed to get PSGC.");
7279
+ }
7280
+ }
7281
+ }
7282
+ async function updateFieldById({ _id, field, value } = {}, session) {
7283
+ const allowedFields = ["name"];
7284
+ if (!allowedFields.includes(field)) {
7285
+ throw new BadRequestError34(
7286
+ `Field "${field}" is not allowed to be updated.`
7287
+ );
7288
+ }
7289
+ try {
7290
+ _id = new ObjectId21(_id);
7291
+ } catch (error) {
7292
+ throw new BadRequestError34("Invalid ID.");
7293
+ }
7294
+ try {
7295
+ await collection.updateOne(
7296
+ { _id, deletedAt: { $in: ["", null] } },
7297
+ { $set: { [field]: value, updatedAt: (/* @__PURE__ */ new Date()).toISOString() } },
7298
+ { session }
7299
+ );
7300
+ delCachedData();
7301
+ return `Successfully updated PSGC ${field}.`;
7302
+ } catch (error) {
7303
+ throw new InternalServerError20(`Failed to update PSGC ${field}.`);
7304
+ }
7305
+ }
7306
+ async function deleteById(_id) {
7307
+ try {
7308
+ _id = new ObjectId21(_id);
7309
+ } catch (error) {
7310
+ throw new BadRequestError34("Invalid ID.");
7311
+ }
7312
+ try {
7313
+ await collection.updateOne(
7314
+ { _id },
7315
+ { $set: { status: "deleted", deletedAt: (/* @__PURE__ */ new Date()).toISOString() } }
7316
+ );
7317
+ delCachedData();
7318
+ return "Successfully deleted PSGC.";
7319
+ } catch (error) {
7320
+ throw new InternalServerError20("Failed to delete PSGC.");
7321
+ }
7322
+ }
7323
+ return {
7324
+ createIndexes,
7325
+ add,
7326
+ getAll,
7327
+ getById,
7328
+ updateFieldById,
7329
+ deleteById,
7330
+ getByName
7331
+ };
7332
+ }
7027
7333
  export {
7028
7334
  ACCESS_TOKEN_EXPIRY,
7029
7335
  ACCESS_TOKEN_SECRET,
@@ -7075,9 +7381,11 @@ export {
7075
7381
  XENDIT_SECRET_KEY,
7076
7382
  addressSchema,
7077
7383
  isDev,
7384
+ modelPSGC,
7078
7385
  schemaBuilding,
7079
7386
  schemaBuildingUnit,
7080
7387
  schemaOrg,
7388
+ schemaPSGC,
7081
7389
  schemaUpdateOptions,
7082
7390
  transactionSchema,
7083
7391
  useAddressController,
@@ -7103,6 +7411,7 @@ export {
7103
7411
  useOrgController,
7104
7412
  useOrgRepo,
7105
7413
  useOrgService,
7414
+ usePSGCRepo,
7106
7415
  useRoleController,
7107
7416
  useRoleRepo,
7108
7417
  useTokenRepo,