index.cjs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897
  1. var __defProp = Object.defineProperty;
  2. var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
  3. var __getOwnPropNames = Object.getOwnPropertyNames;
  4. var __hasOwnProp = Object.prototype.hasOwnProperty;
  5. var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
  6. var __export = (target, all) => {
  7. for (var name in all)
  8. __defProp(target, name, { get: all[name], enumerable: true });
  9. };
  10. var __copyProps = (to, from, except, desc) => {
  11. if (from && typeof from === "object" || typeof from === "function") {
  12. for (let key of __getOwnPropNames(from))
  13. if (!__hasOwnProp.call(to, key) && key !== except)
  14. __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  15. }
  16. return to;
  17. };
  18. var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
  19. // src/index.js
  20. var src_exports = {};
  21. __export(src_exports, {
  22. MongodbAdapter: () => MongodbAdapter
  23. });
  24. module.exports = __toCommonJS(src_exports);
  25. // src/mongodb-adapter.js
  26. var import_mongodb2 = require("mongodb");
  27. var import_mongodb3 = require("mongodb");
  28. // src/utils/is-iso-date.js
  29. function isIsoDate(value) {
  30. if (!value) return false;
  31. if (value instanceof Date) return true;
  32. if (!/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3}Z/.test(value)) return false;
  33. const d = new Date(value);
  34. return d instanceof Date && !isNaN(d.getTime()) && d.toISOString() === value;
  35. }
  36. __name(isIsoDate, "isIsoDate");
  37. // src/utils/is-object-id.js
  38. var import_mongodb = require("mongodb");
  39. function isObjectId(value) {
  40. if (!value) return false;
  41. if (value instanceof import_mongodb.ObjectId) return true;
  42. if (typeof value !== "string") return false;
  43. return value.match(/^[a-fA-F0-9]{24}$/) != null;
  44. }
  45. __name(isObjectId, "isObjectId");
  46. // src/utils/create-mongodb-url.js
  47. var import_js_repository = require("@e22m4u/js-repository");
  48. function createMongodbUrl(options = {}) {
  49. if (!options || typeof options !== "object" || Array.isArray(options))
  50. throw new import_js_repository.InvalidArgumentError(
  51. 'The first argument of "createMongodbUrl" must be an Object, but %v given.',
  52. options
  53. );
  54. if (options.protocol && typeof options.protocol !== "string")
  55. throw new import_js_repository.InvalidArgumentError(
  56. 'MongoDB option "protocol" must be a String, but %v given.',
  57. options.protocol
  58. );
  59. if (options.hostname && typeof options.hostname !== "string")
  60. throw new import_js_repository.InvalidArgumentError(
  61. 'MongoDB option "hostname" must be a String, but %v given.',
  62. options.hostname
  63. );
  64. if (options.host && typeof options.host !== "string")
  65. throw new import_js_repository.InvalidArgumentError(
  66. 'MongoDB option "host" must be a String, but %v given.',
  67. options.host
  68. );
  69. if (options.port && typeof options.port !== "number" && typeof options.port !== "string") {
  70. throw new import_js_repository.InvalidArgumentError(
  71. 'MongoDB option "port" must be a Number or a String, but %v given.',
  72. options.port
  73. );
  74. }
  75. if (options.database && typeof options.database !== "string")
  76. throw new import_js_repository.InvalidArgumentError(
  77. 'MongoDB option "database" must be a String, but %v given.',
  78. options.database
  79. );
  80. if (options.db && typeof options.db !== "string")
  81. throw new import_js_repository.InvalidArgumentError(
  82. 'MongoDB option "db" must be a String, but %v given.',
  83. options.db
  84. );
  85. if (options.username && typeof options.username !== "string")
  86. throw new import_js_repository.InvalidArgumentError(
  87. 'MongoDB option "username" must be a String, but %v given.',
  88. options.username
  89. );
  90. if (options.password && typeof options.password !== "string" && typeof options.password !== "number") {
  91. throw new import_js_repository.InvalidArgumentError(
  92. 'MongoDB option "password" must be a String or a Number, but %v given.',
  93. options.password
  94. );
  95. }
  96. if (options.pass && typeof options.pass !== "string" && typeof options.pass !== "number") {
  97. throw new import_js_repository.InvalidArgumentError(
  98. 'MongoDB option "pass" must be a String or a Number, but %v given.',
  99. options.pass
  100. );
  101. }
  102. const protocol = options.protocol || "mongodb";
  103. const hostname = options.hostname || options.host || "127.0.0.1";
  104. const port = options.port || 27017;
  105. const database = options.database || options.db || "database";
  106. const username = options.username || options.user;
  107. const password = options.password || options.pass || void 0;
  108. let portUrl = "";
  109. if (protocol !== "mongodb+srv") {
  110. portUrl = ":" + port;
  111. }
  112. if (username && password) {
  113. return `${protocol}://${username}:${password}@${hostname}${portUrl}/${database}`;
  114. } else {
  115. return `${protocol}://${hostname}${portUrl}/${database}`;
  116. }
  117. }
  118. __name(createMongodbUrl, "createMongodbUrl");
  119. // src/utils/transform-values-deep.js
  120. var import_js_repository2 = require("@e22m4u/js-repository");
  121. function transformValuesDeep(value, transformer) {
  122. if (!transformer || typeof transformer !== "function")
  123. throw new import_js_repository2.InvalidArgumentError(
  124. 'The second argument of "transformValuesDeep" must be a Function, but %v given.',
  125. transformer
  126. );
  127. if (Array.isArray(value)) {
  128. value.forEach((v, i) => value[i] = transformValuesDeep(v, transformer));
  129. return value;
  130. } else if (value && typeof value === "object") {
  131. if (!value.constructor || value.constructor && value.constructor.name === "Object") {
  132. Object.keys(value).forEach((key) => {
  133. if (Object.prototype.hasOwnProperty.call(value, key))
  134. value[key] = transformValuesDeep(value[key], transformer);
  135. });
  136. return value;
  137. } else {
  138. return transformer(value);
  139. }
  140. } else {
  141. return transformer(value);
  142. }
  143. }
  144. __name(transformValuesDeep, "transformValuesDeep");
  145. // src/mongodb-adapter.js
  146. var import_js_repository3 = require("@e22m4u/js-repository");
  147. var import_js_repository4 = require("@e22m4u/js-repository");
  148. var import_js_repository5 = require("@e22m4u/js-repository");
  149. var import_js_service = require("@e22m4u/js-service");
  150. var import_js_repository6 = require("@e22m4u/js-repository");
  151. var import_js_repository7 = require("@e22m4u/js-repository");
  152. var import_js_repository8 = require("@e22m4u/js-repository");
  153. var import_js_repository9 = require("@e22m4u/js-repository");
  154. var import_js_repository10 = require("@e22m4u/js-repository");
  155. var MONGODB_OPTION_NAMES = [
  156. "appname",
  157. "authMechanism",
  158. "authMechanismProperties",
  159. "authSource",
  160. "compressors",
  161. "connectTimeoutMS",
  162. "directConnection",
  163. "heartbeatFrequencyMS",
  164. "journal",
  165. "loadBalanced",
  166. "localThresholdMS",
  167. "maxIdleTimeMS",
  168. "maxPoolSize",
  169. "maxConnecting",
  170. "maxStalenessSeconds",
  171. "minPoolSize",
  172. "proxyHost",
  173. "proxyPort",
  174. "proxyUsername",
  175. "proxyPassword",
  176. "readConcernLevel",
  177. "readPreference",
  178. "readPreferenceTags",
  179. "replicaSet",
  180. "retryReads",
  181. "retryWrites",
  182. "serverSelectionTimeoutMS",
  183. "serverSelectionTryOnce",
  184. "socketTimeoutMS",
  185. "srvMaxHosts",
  186. "srvServiceName",
  187. "ssl",
  188. "timeoutMS",
  189. "tls",
  190. "tlsAllowInvalidCertificates",
  191. "tlsAllowInvalidHostnames",
  192. "tlsCAFile",
  193. "tlsCertificateKeyFile",
  194. "tlsCertificateKeyFilePassword",
  195. "tlsInsecure",
  196. "w",
  197. "waitQueueTimeoutMS",
  198. "wTimeoutMS",
  199. "zlibCompressionLevel"
  200. ];
  201. var DEFAULT_SETTINGS = {
  202. // connectTimeoutMS: 2500,
  203. // serverSelectionTimeoutMS: 2500,
  204. };
  205. var _MongodbAdapter = class _MongodbAdapter extends import_js_repository3.Adapter {
  206. /**
  207. * Mongodb instance.
  208. *
  209. * @type {MongoClient}
  210. * @private
  211. */
  212. _client;
  213. /**
  214. * Client.
  215. *
  216. * @returns {MongoClient}
  217. */
  218. get client() {
  219. return this._client;
  220. }
  221. /**
  222. * Collections.
  223. *
  224. * @type {Map<any, any>}
  225. * @private
  226. */
  227. _collections = /* @__PURE__ */ new Map();
  228. /**
  229. * Constructor.
  230. *
  231. * @param {ServiceContainer} container
  232. * @param settings
  233. */
  234. constructor(container, settings) {
  235. settings = Object.assign({}, DEFAULT_SETTINGS, settings || {});
  236. settings.protocol = settings.protocol || "mongodb";
  237. settings.hostname = settings.hostname || settings.host || "127.0.0.1";
  238. settings.port = settings.port || 27017;
  239. settings.database = settings.database || settings.db || "database";
  240. super(container, settings);
  241. const options = (0, import_js_repository7.selectObjectKeys)(this.settings, MONGODB_OPTION_NAMES);
  242. const url = createMongodbUrl(this.settings);
  243. this._client = new import_mongodb3.MongoClient(url, options);
  244. }
  245. /**
  246. * Get id prop name.
  247. *
  248. * @param modelName
  249. */
  250. _getIdPropName(modelName) {
  251. return this.getService(import_js_repository8.ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  252. modelName
  253. );
  254. }
  255. /**
  256. * Get id col name.
  257. *
  258. * @param modelName
  259. */
  260. _getIdColName(modelName) {
  261. return this.getService(import_js_repository8.ModelDefinitionUtils).getPrimaryKeyAsColumnName(
  262. modelName
  263. );
  264. }
  265. /**
  266. * Coerce id.
  267. *
  268. * @param value
  269. * @return {ObjectId|*}
  270. * @private
  271. */
  272. _coerceId(value) {
  273. if (value == null) return value;
  274. if (isObjectId(value)) return new import_mongodb2.ObjectId(value);
  275. return value;
  276. }
  277. /**
  278. * Coerce date.
  279. *
  280. * @param value
  281. * @returns {Date|*}
  282. * @private
  283. */
  284. _coerceDate(value) {
  285. if (value == null) return value;
  286. if (value instanceof Date) return value;
  287. if (isIsoDate(value)) return new Date(value);
  288. return value;
  289. }
  290. /**
  291. * To database.
  292. *
  293. * @param {string} modelName
  294. * @param {object} modelData
  295. * @return {object}
  296. * @private
  297. */
  298. _toDatabase(modelName, modelData) {
  299. const tableData = this.getService(
  300. import_js_repository8.ModelDefinitionUtils
  301. ).convertPropertyNamesToColumnNames(modelName, modelData);
  302. const idColName = this._getIdColName(modelName);
  303. if (idColName !== "id" && idColName !== "_id")
  304. throw new import_js_repository9.InvalidArgumentError(
  305. 'MongoDB is not supporting custom names of the primary key. Do use "id" as a primary key instead of %v.',
  306. idColName
  307. );
  308. if (idColName in tableData && idColName !== "_id") {
  309. tableData._id = tableData[idColName];
  310. delete tableData[idColName];
  311. }
  312. return transformValuesDeep(tableData, (value) => {
  313. if (value instanceof import_mongodb2.ObjectId) return value;
  314. if (value instanceof Date) return value;
  315. if (isObjectId(value)) return new import_mongodb2.ObjectId(value);
  316. if (isIsoDate(value)) return new Date(value);
  317. return value;
  318. });
  319. }
  320. /**
  321. * From database.
  322. *
  323. * @param {string} modelName
  324. * @param {object} tableData
  325. * @return {object}
  326. * @private
  327. */
  328. _fromDatabase(modelName, tableData) {
  329. if ("_id" in tableData) {
  330. const idColName = this._getIdColName(modelName);
  331. if (idColName !== "id" && idColName !== "_id")
  332. throw new import_js_repository9.InvalidArgumentError(
  333. 'MongoDB is not supporting custom names of the primary key. Do use "id" as a primary key instead of %v.',
  334. idColName
  335. );
  336. if (idColName !== "_id") {
  337. tableData[idColName] = tableData._id;
  338. delete tableData._id;
  339. }
  340. }
  341. const modelData = this.getService(
  342. import_js_repository8.ModelDefinitionUtils
  343. ).convertColumnNamesToPropertyNames(modelName, tableData);
  344. return transformValuesDeep(modelData, (value) => {
  345. if (value instanceof import_mongodb2.ObjectId) return String(value);
  346. if (value instanceof Date) return value.toISOString();
  347. return value;
  348. });
  349. }
  350. /**
  351. * Get collection.
  352. *
  353. * @param {string} modelName
  354. * @return {*}
  355. * @private
  356. */
  357. _getCollection(modelName) {
  358. let collection = this._collections.get(modelName);
  359. if (collection) return collection;
  360. const tableName = this.getService(import_js_repository8.ModelDefinitionUtils).getTableNameByModelName(modelName);
  361. collection = this.client.db(this.settings.database).collection(tableName);
  362. this._collections.set(modelName, collection);
  363. return collection;
  364. }
  365. /**
  366. * Get id type.
  367. *
  368. * @param modelName
  369. * @return {string|*}
  370. * @private
  371. */
  372. _getIdType(modelName) {
  373. const utils = this.getService(import_js_repository8.ModelDefinitionUtils);
  374. const pkPropName = utils.getPrimaryKeyAsPropertyName(modelName);
  375. return utils.getDataTypeByPropertyName(modelName, pkPropName);
  376. }
  377. /**
  378. * Build projection.
  379. *
  380. * @param {string} modelName
  381. * @param {string|string[]} fields
  382. * @return {Record<string, number>|undefined}
  383. * @private
  384. */
  385. _buildProjection(modelName, fields) {
  386. if (fields == null) return;
  387. if (Array.isArray(fields) === false) fields = [fields];
  388. if (!fields.length) return;
  389. if (fields.indexOf("_id") === -1) fields.push("_id");
  390. return fields.reduce((acc, field) => {
  391. if (!field || typeof field !== "string")
  392. throw new import_js_repository9.InvalidArgumentError(
  393. 'The provided option "fields" should be a non-empty String or an Array of non-empty String, but %v given.',
  394. field
  395. );
  396. let colName = this._getColName(modelName, field);
  397. acc[colName] = 1;
  398. return acc;
  399. }, {});
  400. }
  401. /**
  402. * Get col name.
  403. *
  404. * @param {string} modelName
  405. * @param {string} propName
  406. * @return {string}
  407. * @private
  408. */
  409. _getColName(modelName, propName) {
  410. if (!propName || typeof propName !== "string")
  411. throw new import_js_repository9.InvalidArgumentError(
  412. "A property name must be a non-empty String, but %v given.",
  413. propName
  414. );
  415. const utils = this.getService(import_js_repository8.ModelDefinitionUtils);
  416. let colName = propName;
  417. try {
  418. colName = utils.getColumnNameByPropertyName(modelName, propName);
  419. } catch (error) {
  420. if (!(error instanceof import_js_repository9.InvalidArgumentError) || error.message.indexOf("does not have the property") === -1) {
  421. throw error;
  422. }
  423. }
  424. return colName;
  425. }
  426. /**
  427. * Build sort.
  428. *
  429. * @param {string} modelName
  430. * @param {string|string[]} clause
  431. * @return {object|undefined}
  432. * @private
  433. */
  434. _buildSort(modelName, clause) {
  435. if (clause == null) return;
  436. if (Array.isArray(clause) === false) clause = [clause];
  437. if (!clause.length) return;
  438. const utils = this.getService(import_js_repository8.ModelDefinitionUtils);
  439. const idPropName = this._getIdPropName(modelName);
  440. return clause.reduce((acc, order) => {
  441. if (!order || typeof order !== "string")
  442. throw new import_js_repository9.InvalidArgumentError(
  443. 'The provided option "order" should be a non-empty String or an Array of non-empty String, but %v given.',
  444. order
  445. );
  446. const direction = order.match(/\s+(A|DE)SC$/);
  447. let field = order.replace(/\s+(A|DE)SC$/, "").trim();
  448. if (field === idPropName) {
  449. field = "_id";
  450. } else {
  451. try {
  452. field = utils.getColumnNameByPropertyName(modelName, field);
  453. } catch (error) {
  454. if (!(error instanceof import_js_repository9.InvalidArgumentError) || error.message.indexOf("does not have the property") === -1) {
  455. throw error;
  456. }
  457. }
  458. }
  459. acc[field] = direction && direction[1] === "DE" ? -1 : 1;
  460. return acc;
  461. }, {});
  462. }
  463. /**
  464. * Build query.
  465. *
  466. * @param {string} modelName
  467. * @param {object} clause
  468. * @return {object}
  469. * @private
  470. */
  471. _buildQuery(modelName, clause) {
  472. if (clause == null) return;
  473. if (typeof clause !== "object" || Array.isArray(clause))
  474. throw new import_js_repository9.InvalidArgumentError(
  475. 'The provided option "where" should be an Object, but %v given.',
  476. clause
  477. );
  478. const query = {};
  479. const idPropName = this._getIdPropName(modelName);
  480. Object.keys(clause).forEach((key) => {
  481. var _a, _b;
  482. if (String(key).indexOf("$") !== -1)
  483. throw new import_js_repository9.InvalidArgumentError(
  484. 'The symbol "$" is not supported, but %v given.',
  485. key
  486. );
  487. let cond = clause[key];
  488. if (key === "and" || key === "or" || key === "nor") {
  489. if (cond == null) return;
  490. if (!Array.isArray(cond))
  491. throw new import_js_repository10.InvalidOperatorValueError(key, "an Array", cond);
  492. if (cond.length === 0) return;
  493. cond = cond.map((c) => this._buildQuery(modelName, c));
  494. cond = cond.filter((c) => c != null);
  495. const opKey = "$" + key;
  496. query[opKey] = (_a = query[opKey]) != null ? _a : [];
  497. query[opKey] = [...query[opKey], ...cond];
  498. return;
  499. }
  500. if (key === idPropName) {
  501. key = "_id";
  502. } else {
  503. key = this._getColName(modelName, key);
  504. }
  505. if (typeof cond === "string") {
  506. query[key] = this._coerceId(cond);
  507. query[key] = this._coerceDate(query[key]);
  508. return;
  509. }
  510. if (cond instanceof import_mongodb2.ObjectId) {
  511. query[key] = cond;
  512. return;
  513. }
  514. if (cond && cond.constructor && cond.constructor.name === "Object") {
  515. const opConds = [];
  516. if ("eq" in cond) {
  517. let eq = this._coerceId(cond.eq);
  518. eq = this._coerceDate(eq);
  519. opConds.push({ $eq: eq });
  520. }
  521. if ("neq" in cond) {
  522. let neq = this._coerceId(cond.neq);
  523. neq = this._coerceDate(neq);
  524. opConds.push({ $ne: neq });
  525. }
  526. if ("gt" in cond) {
  527. const gt = this._coerceDate(cond.gt);
  528. opConds.push({ $gt: gt });
  529. }
  530. if ("lt" in cond) {
  531. const lt = this._coerceDate(cond.lt);
  532. opConds.push({ $lt: lt });
  533. }
  534. if ("gte" in cond) {
  535. const gte = this._coerceDate(cond.gte);
  536. opConds.push({ $gte: gte });
  537. }
  538. if ("lte" in cond) {
  539. const lte = this._coerceDate(cond.lte);
  540. opConds.push({ $lte: lte });
  541. }
  542. if ("inq" in cond) {
  543. if (!cond.inq || !Array.isArray(cond.inq))
  544. throw new import_js_repository10.InvalidOperatorValueError(
  545. "inq",
  546. "an Array of possible values",
  547. cond.inq
  548. );
  549. const inq = cond.inq.map((v) => {
  550. v = this._coerceId(v);
  551. v = this._coerceDate(v);
  552. return v;
  553. });
  554. opConds.push({ $in: inq });
  555. }
  556. if ("nin" in cond) {
  557. if (!cond.nin || !Array.isArray(cond.nin))
  558. throw new import_js_repository10.InvalidOperatorValueError(
  559. "nin",
  560. "an Array of possible values",
  561. cond
  562. );
  563. const nin = cond.nin.map((v) => {
  564. v = this._coerceId(v);
  565. v = this._coerceDate(v);
  566. return v;
  567. });
  568. opConds.push({ $nin: nin });
  569. }
  570. if ("between" in cond) {
  571. if (!Array.isArray(cond.between) || cond.between.length !== 2)
  572. throw new import_js_repository10.InvalidOperatorValueError(
  573. "between",
  574. "an Array of 2 elements",
  575. cond.between
  576. );
  577. const gte = this._coerceDate(cond.between[0]);
  578. const lte = this._coerceDate(cond.between[1]);
  579. opConds.push({ $gte: gte, $lte: lte });
  580. }
  581. if ("exists" in cond) {
  582. if (typeof cond.exists !== "boolean")
  583. throw new import_js_repository10.InvalidOperatorValueError(
  584. "exists",
  585. "a Boolean",
  586. cond.exists
  587. );
  588. opConds.push({ $exists: cond.exists });
  589. }
  590. if ("like" in cond) {
  591. if (typeof cond.like !== "string" && !(cond.like instanceof RegExp))
  592. throw new import_js_repository10.InvalidOperatorValueError(
  593. "like",
  594. "a String or RegExp",
  595. cond.like
  596. );
  597. opConds.push({ $regex: (0, import_js_repository6.stringToRegexp)(cond.like) });
  598. }
  599. if ("nlike" in cond) {
  600. if (typeof cond.nlike !== "string" && !(cond.nlike instanceof RegExp))
  601. throw new import_js_repository10.InvalidOperatorValueError(
  602. "nlike",
  603. "a String or RegExp",
  604. cond.nlike
  605. );
  606. opConds.push({ $not: (0, import_js_repository6.stringToRegexp)(cond.nlike) });
  607. }
  608. if ("ilike" in cond) {
  609. if (typeof cond.ilike !== "string" && !(cond.ilike instanceof RegExp))
  610. throw new import_js_repository10.InvalidOperatorValueError(
  611. "ilike",
  612. "a String or RegExp",
  613. cond.ilike
  614. );
  615. opConds.push({ $regex: (0, import_js_repository6.stringToRegexp)(cond.ilike, "i") });
  616. }
  617. if ("nilike" in cond) {
  618. if (typeof cond.nilike !== "string" && !(cond.nilike instanceof RegExp)) {
  619. throw new import_js_repository10.InvalidOperatorValueError(
  620. "nilike",
  621. "a String or RegExp",
  622. cond.nilike
  623. );
  624. }
  625. opConds.push({ $not: (0, import_js_repository6.stringToRegexp)(cond.nilike, "i") });
  626. }
  627. if ("regexp" in cond) {
  628. if (typeof cond.regexp !== "string" && !(cond.regexp instanceof RegExp)) {
  629. throw new import_js_repository10.InvalidOperatorValueError(
  630. "regexp",
  631. "a String or RegExp",
  632. cond.regexp
  633. );
  634. }
  635. const flags = cond.flags || void 0;
  636. if (flags && typeof flags !== "string")
  637. throw new import_js_repository9.InvalidArgumentError(
  638. "RegExp flags must be a String, but %v given.",
  639. cond.flags
  640. );
  641. opConds.push({ $regex: (0, import_js_repository6.stringToRegexp)(cond.regexp, flags) });
  642. }
  643. if (opConds.length === 1) {
  644. query[key] = opConds[0];
  645. } else if (opConds.length > 1) {
  646. query["$and"] = (_b = query["$and"]) != null ? _b : [];
  647. opConds.forEach((c) => query["$and"].push({ [key]: c }));
  648. }
  649. return;
  650. }
  651. query[key] = cond;
  652. });
  653. return Object.keys(query).length ? query : void 0;
  654. }
  655. /**
  656. * Create.
  657. *
  658. * @param {string} modelName
  659. * @param {object} modelData
  660. * @param {object|undefined} filter
  661. * @return {Promise<object>}
  662. */
  663. async create(modelName, modelData, filter = void 0) {
  664. const idPropName = this._getIdPropName(modelName);
  665. const idValue = modelData[idPropName];
  666. if (idValue == null || idValue === "" || idValue === 0) {
  667. const pkType = this._getIdType(modelName);
  668. if (pkType !== import_js_repository4.DataType.STRING && pkType !== import_js_repository4.DataType.ANY)
  669. throw new import_js_repository9.InvalidArgumentError(
  670. "MongoDB unable to generate primary keys of %s. Do provide your own value for the %v property or set property type to String.",
  671. (0, import_js_repository5.capitalize)(pkType),
  672. idPropName
  673. );
  674. delete modelData[idPropName];
  675. }
  676. const tableData = this._toDatabase(modelName, modelData);
  677. const table = this._getCollection(modelName);
  678. const { insertedId } = await table.insertOne(tableData);
  679. const projection = this._buildProjection(
  680. modelName,
  681. filter && filter.fields
  682. );
  683. const insertedData = await table.findOne({ _id: insertedId }, { projection });
  684. return this._fromDatabase(modelName, insertedData);
  685. }
  686. /**
  687. * Replace by id.
  688. *
  689. * @param {string} modelName
  690. * @param {string|number} id
  691. * @param {object} modelData
  692. * @param {object|undefined} filter
  693. * @return {Promise<object>}
  694. */
  695. async replaceById(modelName, id, modelData, filter = void 0) {
  696. id = this._coerceId(id);
  697. const idPropName = this._getIdPropName(modelName);
  698. modelData[idPropName] = id;
  699. const tableData = this._toDatabase(modelName, modelData);
  700. const table = this._getCollection(modelName);
  701. const { matchedCount } = await table.replaceOne({ _id: id }, tableData);
  702. if (matchedCount < 1)
  703. throw new import_js_repository9.InvalidArgumentError("Identifier %v is not found.", String(id));
  704. const projection = this._buildProjection(
  705. modelName,
  706. filter && filter.fields
  707. );
  708. const replacedData = await table.findOne({ _id: id }, { projection });
  709. return this._fromDatabase(modelName, replacedData);
  710. }
  711. /**
  712. * Replace or create.
  713. *
  714. * @param {string} modelName
  715. * @param {object} modelData
  716. * @param {object|undefined} filter
  717. * @return {Promise<object>}
  718. */
  719. async replaceOrCreate(modelName, modelData, filter = void 0) {
  720. const idPropName = this._getIdPropName(modelName);
  721. let idValue = modelData[idPropName];
  722. idValue = this._coerceId(idValue);
  723. if (idValue == null || idValue === "" || idValue === 0) {
  724. const pkType = this._getIdType(modelName);
  725. if (pkType !== import_js_repository4.DataType.STRING && pkType !== import_js_repository4.DataType.ANY)
  726. throw new import_js_repository9.InvalidArgumentError(
  727. "MongoDB unable to generate primary keys of %s. Do provide your own value for the %v property or set property type to String.",
  728. (0, import_js_repository5.capitalize)(pkType),
  729. idPropName
  730. );
  731. delete modelData[idPropName];
  732. idValue = void 0;
  733. }
  734. const tableData = this._toDatabase(modelName, modelData);
  735. const table = this._getCollection(modelName);
  736. if (idValue == null) {
  737. const { insertedId } = await table.insertOne(tableData);
  738. idValue = insertedId;
  739. } else {
  740. const { upsertedId } = await table.replaceOne({ _id: idValue }, tableData, {
  741. upsert: true
  742. });
  743. if (upsertedId) idValue = upsertedId;
  744. }
  745. const projection = this._buildProjection(
  746. modelName,
  747. filter && filter.fields
  748. );
  749. const upsertedData = await table.findOne({ _id: idValue }, { projection });
  750. return this._fromDatabase(modelName, upsertedData);
  751. }
  752. /**
  753. * Patch.
  754. *
  755. * @param {string} modelName
  756. * @param {object} modelData
  757. * @param {object|undefined} where
  758. * @return {Promise<number>}
  759. */
  760. async patch(modelName, modelData, where = void 0) {
  761. const idPropName = this._getIdPropName(modelName);
  762. delete modelData[idPropName];
  763. const query = this._buildQuery(modelName, where) || {};
  764. const tableData = this._toDatabase(modelName, modelData);
  765. const table = this._getCollection(modelName);
  766. const { matchedCount } = await table.updateMany(query, { $set: tableData });
  767. return matchedCount;
  768. }
  769. /**
  770. * Patch by id.
  771. *
  772. * @param {string} modelName
  773. * @param {string|number} id
  774. * @param {object} modelData
  775. * @param {object|undefined} filter
  776. * @return {Promise<object>}
  777. */
  778. async patchById(modelName, id, modelData, filter = void 0) {
  779. id = this._coerceId(id);
  780. const idPropName = this._getIdPropName(modelName);
  781. delete modelData[idPropName];
  782. const tableData = this._toDatabase(modelName, modelData);
  783. const table = this._getCollection(modelName);
  784. const { matchedCount } = await table.updateOne({ _id: id }, { $set: tableData });
  785. if (matchedCount < 1)
  786. throw new import_js_repository9.InvalidArgumentError("Identifier %v is not found.", String(id));
  787. const projection = this._buildProjection(
  788. modelName,
  789. filter && filter.fields
  790. );
  791. const patchedData = await table.findOne({ _id: id }, { projection });
  792. return this._fromDatabase(modelName, patchedData);
  793. }
  794. /**
  795. * Find.
  796. *
  797. * @param {string} modelName
  798. * @param {object|undefined} filter
  799. * @return {Promise<object[]>}
  800. */
  801. async find(modelName, filter = void 0) {
  802. filter = filter || {};
  803. const query = this._buildQuery(modelName, filter.where);
  804. const sort = this._buildSort(modelName, filter.order);
  805. const limit = filter.limit || void 0;
  806. const skip = filter.skip || void 0;
  807. const projection = this._buildProjection(modelName, filter.fields);
  808. const collection = this._getCollection(modelName);
  809. const options = { sort, limit, skip, projection };
  810. const tableItems = await collection.find(query, options).toArray();
  811. return tableItems.map((v) => this._fromDatabase(modelName, v));
  812. }
  813. /**
  814. * Find by id.
  815. *
  816. * @param {string} modelName
  817. * @param {string|number} id
  818. * @param {object|undefined} filter
  819. * @return {Promise<object>}
  820. */
  821. async findById(modelName, id, filter = void 0) {
  822. id = this._coerceId(id);
  823. const table = this._getCollection(modelName);
  824. const projection = this._buildProjection(
  825. modelName,
  826. filter && filter.fields
  827. );
  828. const patchedData = await table.findOne({ _id: id }, { projection });
  829. if (!patchedData)
  830. throw new import_js_repository9.InvalidArgumentError("Identifier %v is not found.", String(id));
  831. return this._fromDatabase(modelName, patchedData);
  832. }
  833. /**
  834. * Delete.
  835. *
  836. * @param {string} modelName
  837. * @param {object|undefined} where
  838. * @return {Promise<number>}
  839. */
  840. async delete(modelName, where = void 0) {
  841. const table = this._getCollection(modelName);
  842. const query = this._buildQuery(modelName, where);
  843. const { deletedCount } = await table.deleteMany(query);
  844. return deletedCount;
  845. }
  846. /**
  847. * Delete by id.
  848. *
  849. * @param {string} modelName
  850. * @param {string|number} id
  851. * @return {Promise<boolean>}
  852. */
  853. async deleteById(modelName, id) {
  854. id = this._coerceId(id);
  855. const table = this._getCollection(modelName);
  856. const { deletedCount } = await table.deleteOne({ _id: id });
  857. return deletedCount > 0;
  858. }
  859. /**
  860. * Exists.
  861. *
  862. * @param {string} modelName
  863. * @param {string|number} id
  864. * @return {Promise<boolean>}
  865. */
  866. async exists(modelName, id) {
  867. id = this._coerceId(id);
  868. const table = this._getCollection(modelName);
  869. const result = await table.findOne({ _id: id }, {});
  870. return result != null;
  871. }
  872. /**
  873. * Count.
  874. *
  875. * @param {string} modelName
  876. * @param {object|undefined} where
  877. * @return {Promise<number>}
  878. */
  879. async count(modelName, where = void 0) {
  880. const query = this._buildQuery(modelName, where);
  881. const table = this._getCollection(modelName);
  882. return await table.count(query);
  883. }
  884. };
  885. __name(_MongodbAdapter, "MongodbAdapter");
  886. var MongodbAdapter = _MongodbAdapter;
  887. // Annotate the CommonJS export names for ESM import in node:
  888. 0 && (module.exports = {
  889. MongodbAdapter
  890. });