index.cjs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934
  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 index_exports = {};
  21. __export(index_exports, {
  22. MongodbAdapter: () => MongodbAdapter
  23. });
  24. module.exports = __toCommonJS(index_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. * @private
  250. */
  251. _getIdPropName(modelName) {
  252. return this.getService(import_js_repository8.ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  253. modelName
  254. );
  255. }
  256. /**
  257. * Get id col name.
  258. *
  259. * @param modelName
  260. * @private
  261. */
  262. _getIdColName(modelName) {
  263. return this.getService(import_js_repository8.ModelDefinitionUtils).getPrimaryKeyAsColumnName(
  264. modelName
  265. );
  266. }
  267. /**
  268. * Coerce id.
  269. *
  270. * @param value
  271. * @returns {ObjectId|*}
  272. * @private
  273. */
  274. _coerceId(value) {
  275. if (value == null) return value;
  276. if (isObjectId(value)) return new import_mongodb2.ObjectId(value);
  277. return value;
  278. }
  279. /**
  280. * Coerce date.
  281. *
  282. * @param value
  283. * @returns {Date|*}
  284. * @private
  285. */
  286. _coerceDate(value) {
  287. if (value == null) return value;
  288. if (value instanceof Date) return value;
  289. if (isIsoDate(value)) return new Date(value);
  290. return value;
  291. }
  292. /**
  293. * To database.
  294. *
  295. * @param {string} modelName
  296. * @param {object} modelData
  297. * @returns {object}
  298. * @private
  299. */
  300. _toDatabase(modelName, modelData) {
  301. const tableData = this.getService(
  302. import_js_repository8.ModelDefinitionUtils
  303. ).convertPropertyNamesToColumnNames(modelName, modelData);
  304. const idColName = this._getIdColName(modelName);
  305. if (idColName !== "id" && idColName !== "_id")
  306. throw new import_js_repository9.InvalidArgumentError(
  307. 'MongoDB is not supporting custom names of the primary key. Do use "id" as a primary key instead of %v.',
  308. idColName
  309. );
  310. if (idColName in tableData && idColName !== "_id") {
  311. tableData._id = tableData[idColName];
  312. delete tableData[idColName];
  313. }
  314. return transformValuesDeep(tableData, (value) => {
  315. if (value instanceof import_mongodb2.ObjectId) return value;
  316. if (value instanceof Date) return value;
  317. if (isObjectId(value)) return new import_mongodb2.ObjectId(value);
  318. if (isIsoDate(value)) return new Date(value);
  319. return value;
  320. });
  321. }
  322. /**
  323. * From database.
  324. *
  325. * @param {string} modelName
  326. * @param {object} tableData
  327. * @returns {object}
  328. * @private
  329. */
  330. _fromDatabase(modelName, tableData) {
  331. if ("_id" in tableData) {
  332. const idColName = this._getIdColName(modelName);
  333. if (idColName !== "id" && idColName !== "_id")
  334. throw new import_js_repository9.InvalidArgumentError(
  335. 'MongoDB is not supporting custom names of the primary key. Do use "id" as a primary key instead of %v.',
  336. idColName
  337. );
  338. if (idColName !== "_id") {
  339. tableData[idColName] = tableData._id;
  340. delete tableData._id;
  341. }
  342. }
  343. const modelData = this.getService(
  344. import_js_repository8.ModelDefinitionUtils
  345. ).convertColumnNamesToPropertyNames(modelName, tableData);
  346. return transformValuesDeep(modelData, (value) => {
  347. if (value instanceof import_mongodb2.ObjectId) return String(value);
  348. if (value instanceof Date) return value.toISOString();
  349. return value;
  350. });
  351. }
  352. /**
  353. * Get collection.
  354. *
  355. * @param {string} modelName
  356. * @returns {*}
  357. * @private
  358. */
  359. _getCollection(modelName) {
  360. let collection = this._collections.get(modelName);
  361. if (collection) return collection;
  362. const tableName = this.getService(import_js_repository8.ModelDefinitionUtils).getTableNameByModelName(modelName);
  363. collection = this.client.db(this.settings.database).collection(tableName);
  364. this._collections.set(modelName, collection);
  365. return collection;
  366. }
  367. /**
  368. * Get id type.
  369. *
  370. * @param modelName
  371. * @returns {string|*}
  372. * @private
  373. */
  374. _getIdType(modelName) {
  375. const utils = this.getService(import_js_repository8.ModelDefinitionUtils);
  376. const pkPropName = utils.getPrimaryKeyAsPropertyName(modelName);
  377. return utils.getDataTypeByPropertyName(modelName, pkPropName);
  378. }
  379. /**
  380. * Get col name.
  381. *
  382. * @param {string} modelName
  383. * @param {string} propName
  384. * @returns {string}
  385. * @private
  386. */
  387. _getColName(modelName, propName) {
  388. if (!propName || typeof propName !== "string")
  389. throw new import_js_repository9.InvalidArgumentError(
  390. "Property name must be a non-empty String, but %v given.",
  391. propName
  392. );
  393. const utils = this.getService(import_js_repository8.ModelDefinitionUtils);
  394. let colName = propName;
  395. try {
  396. colName = utils.getColumnNameByPropertyName(modelName, propName);
  397. } catch (error) {
  398. if (!(error instanceof import_js_repository9.InvalidArgumentError) || error.message.indexOf("does not have the property") === -1) {
  399. throw error;
  400. }
  401. }
  402. return colName;
  403. }
  404. /**
  405. * Convert prop names chain to col names chain.
  406. *
  407. * @param {string} modelName
  408. * @param {string} propsChain
  409. * @returns {string}
  410. * @private
  411. */
  412. _convertPropNamesChainToColNamesChain(modelName, propsChain) {
  413. if (!modelName || typeof modelName !== "string")
  414. throw new import_js_repository9.InvalidArgumentError(
  415. "Model name must be a non-empty String, but %v given.",
  416. modelName
  417. );
  418. if (!propsChain || typeof propsChain !== "string")
  419. throw new import_js_repository9.InvalidArgumentError(
  420. "Properties chain must be a non-empty String, but %v given.",
  421. propsChain
  422. );
  423. propsChain = propsChain.replace(/\.{2,}/g, ".");
  424. const propNames = propsChain.split(".");
  425. const utils = this.getService(import_js_repository8.ModelDefinitionUtils);
  426. let currModelName = modelName;
  427. return propNames.map((currPropName) => {
  428. if (!currModelName) return currPropName;
  429. const colName = this._getColName(currModelName, currPropName);
  430. currModelName = utils.getModelNameOfPropertyValueIfDefined(
  431. currModelName,
  432. currPropName
  433. );
  434. return colName;
  435. }).join(".");
  436. }
  437. /**
  438. * Build projection.
  439. *
  440. * @param {string} modelName
  441. * @param {string|string[]} fields
  442. * @returns {Record<string, number>|undefined}
  443. * @private
  444. */
  445. _buildProjection(modelName, fields) {
  446. if (fields == null) return;
  447. if (Array.isArray(fields) === false) fields = [fields];
  448. if (!fields.length) return;
  449. if (fields.indexOf("_id") === -1) fields.push("_id");
  450. return fields.reduce((acc, field) => {
  451. if (!field || typeof field !== "string")
  452. throw new import_js_repository9.InvalidArgumentError(
  453. 'The provided option "fields" should be a non-empty String or an Array of non-empty String, but %v given.',
  454. field
  455. );
  456. let colName = this._convertPropNamesChainToColNamesChain(
  457. modelName,
  458. field
  459. );
  460. acc[colName] = 1;
  461. return acc;
  462. }, {});
  463. }
  464. /**
  465. * Build sort.
  466. *
  467. * @param {string} modelName
  468. * @param {string|string[]} clause
  469. * @returns {object|undefined}
  470. * @private
  471. */
  472. _buildSort(modelName, clause) {
  473. if (clause == null) return;
  474. if (Array.isArray(clause) === false) clause = [clause];
  475. if (!clause.length) return;
  476. const idPropName = this._getIdPropName(modelName);
  477. return clause.reduce((acc, order) => {
  478. if (!order || typeof order !== "string")
  479. throw new import_js_repository9.InvalidArgumentError(
  480. 'The provided option "order" should be a non-empty String or an Array of non-empty String, but %v given.',
  481. order
  482. );
  483. const direction = order.match(/\s+(A|DE)SC$/);
  484. let field = order.replace(/\s+(A|DE)SC$/, "").trim();
  485. if (field === idPropName) {
  486. field = "_id";
  487. } else {
  488. try {
  489. field = this._convertPropNamesChainToColNamesChain(modelName, field);
  490. } catch (error) {
  491. if (!(error instanceof import_js_repository9.InvalidArgumentError) || error.message.indexOf("does not have the property") === -1) {
  492. throw error;
  493. }
  494. }
  495. }
  496. acc[field] = direction && direction[1] === "DE" ? -1 : 1;
  497. return acc;
  498. }, {});
  499. }
  500. /**
  501. * Build query.
  502. *
  503. * @param {string} modelName
  504. * @param {object} clause
  505. * @returns {object}
  506. * @private
  507. */
  508. _buildQuery(modelName, clause) {
  509. if (clause == null) return;
  510. if (typeof clause !== "object" || Array.isArray(clause))
  511. throw new import_js_repository9.InvalidArgumentError(
  512. 'The provided option "where" should be an Object, but %v given.',
  513. clause
  514. );
  515. const query = {};
  516. const idPropName = this._getIdPropName(modelName);
  517. Object.keys(clause).forEach((key) => {
  518. var _a, _b;
  519. if (String(key).indexOf("$") !== -1)
  520. throw new import_js_repository9.InvalidArgumentError(
  521. 'The symbol "$" is not supported, but %v given.',
  522. key
  523. );
  524. let cond = clause[key];
  525. if (key === "and" || key === "or" || key === "nor") {
  526. if (cond == null) return;
  527. if (!Array.isArray(cond))
  528. throw new import_js_repository10.InvalidOperatorValueError(key, "an Array", cond);
  529. if (cond.length === 0) return;
  530. cond = cond.map((c) => this._buildQuery(modelName, c));
  531. cond = cond.filter((c) => c != null);
  532. const opKey = "$" + key;
  533. query[opKey] = (_a = query[opKey]) != null ? _a : [];
  534. query[opKey] = [...query[opKey], ...cond];
  535. return;
  536. }
  537. if (key === idPropName) {
  538. key = "_id";
  539. } else {
  540. key = this._convertPropNamesChainToColNamesChain(modelName, key);
  541. }
  542. if (typeof cond === "string") {
  543. query[key] = this._coerceId(cond);
  544. query[key] = this._coerceDate(query[key]);
  545. return;
  546. }
  547. if (cond instanceof import_mongodb2.ObjectId) {
  548. query[key] = cond;
  549. return;
  550. }
  551. if (cond && cond.constructor && cond.constructor.name === "Object") {
  552. const opConds = [];
  553. if ("eq" in cond) {
  554. let eq = this._coerceId(cond.eq);
  555. eq = this._coerceDate(eq);
  556. opConds.push({ $eq: eq });
  557. }
  558. if ("neq" in cond) {
  559. let neq = this._coerceId(cond.neq);
  560. neq = this._coerceDate(neq);
  561. opConds.push({ $ne: neq });
  562. }
  563. if ("gt" in cond) {
  564. const gt = this._coerceDate(cond.gt);
  565. opConds.push({ $gt: gt });
  566. }
  567. if ("lt" in cond) {
  568. const lt = this._coerceDate(cond.lt);
  569. opConds.push({ $lt: lt });
  570. }
  571. if ("gte" in cond) {
  572. const gte = this._coerceDate(cond.gte);
  573. opConds.push({ $gte: gte });
  574. }
  575. if ("lte" in cond) {
  576. const lte = this._coerceDate(cond.lte);
  577. opConds.push({ $lte: lte });
  578. }
  579. if ("inq" in cond) {
  580. if (!cond.inq || !Array.isArray(cond.inq))
  581. throw new import_js_repository10.InvalidOperatorValueError(
  582. "inq",
  583. "an Array of possible values",
  584. cond.inq
  585. );
  586. const inq = cond.inq.map((v) => {
  587. v = this._coerceId(v);
  588. v = this._coerceDate(v);
  589. return v;
  590. });
  591. opConds.push({ $in: inq });
  592. }
  593. if ("nin" in cond) {
  594. if (!cond.nin || !Array.isArray(cond.nin))
  595. throw new import_js_repository10.InvalidOperatorValueError(
  596. "nin",
  597. "an Array of possible values",
  598. cond
  599. );
  600. const nin = cond.nin.map((v) => {
  601. v = this._coerceId(v);
  602. v = this._coerceDate(v);
  603. return v;
  604. });
  605. opConds.push({ $nin: nin });
  606. }
  607. if ("between" in cond) {
  608. if (!Array.isArray(cond.between) || cond.between.length !== 2)
  609. throw new import_js_repository10.InvalidOperatorValueError(
  610. "between",
  611. "an Array of 2 elements",
  612. cond.between
  613. );
  614. const gte = this._coerceDate(cond.between[0]);
  615. const lte = this._coerceDate(cond.between[1]);
  616. opConds.push({ $gte: gte, $lte: lte });
  617. }
  618. if ("exists" in cond) {
  619. if (typeof cond.exists !== "boolean")
  620. throw new import_js_repository10.InvalidOperatorValueError(
  621. "exists",
  622. "a Boolean",
  623. cond.exists
  624. );
  625. opConds.push({ $exists: cond.exists });
  626. }
  627. if ("like" in cond) {
  628. if (typeof cond.like !== "string" && !(cond.like instanceof RegExp))
  629. throw new import_js_repository10.InvalidOperatorValueError(
  630. "like",
  631. "a String or RegExp",
  632. cond.like
  633. );
  634. opConds.push({ $regex: (0, import_js_repository6.stringToRegexp)(cond.like) });
  635. }
  636. if ("nlike" in cond) {
  637. if (typeof cond.nlike !== "string" && !(cond.nlike instanceof RegExp))
  638. throw new import_js_repository10.InvalidOperatorValueError(
  639. "nlike",
  640. "a String or RegExp",
  641. cond.nlike
  642. );
  643. opConds.push({ $not: (0, import_js_repository6.stringToRegexp)(cond.nlike) });
  644. }
  645. if ("ilike" in cond) {
  646. if (typeof cond.ilike !== "string" && !(cond.ilike instanceof RegExp))
  647. throw new import_js_repository10.InvalidOperatorValueError(
  648. "ilike",
  649. "a String or RegExp",
  650. cond.ilike
  651. );
  652. opConds.push({ $regex: (0, import_js_repository6.stringToRegexp)(cond.ilike, "i") });
  653. }
  654. if ("nilike" in cond) {
  655. if (typeof cond.nilike !== "string" && !(cond.nilike instanceof RegExp)) {
  656. throw new import_js_repository10.InvalidOperatorValueError(
  657. "nilike",
  658. "a String or RegExp",
  659. cond.nilike
  660. );
  661. }
  662. opConds.push({ $not: (0, import_js_repository6.stringToRegexp)(cond.nilike, "i") });
  663. }
  664. if ("regexp" in cond) {
  665. if (typeof cond.regexp !== "string" && !(cond.regexp instanceof RegExp)) {
  666. throw new import_js_repository10.InvalidOperatorValueError(
  667. "regexp",
  668. "a String or RegExp",
  669. cond.regexp
  670. );
  671. }
  672. const flags = cond.flags || void 0;
  673. if (flags && typeof flags !== "string")
  674. throw new import_js_repository9.InvalidArgumentError(
  675. "RegExp flags must be a String, but %v given.",
  676. cond.flags
  677. );
  678. opConds.push({ $regex: (0, import_js_repository6.stringToRegexp)(cond.regexp, flags) });
  679. }
  680. if (opConds.length === 1) {
  681. query[key] = opConds[0];
  682. } else if (opConds.length > 1) {
  683. query["$and"] = (_b = query["$and"]) != null ? _b : [];
  684. opConds.forEach((c) => query["$and"].push({ [key]: c }));
  685. }
  686. return;
  687. }
  688. query[key] = cond;
  689. });
  690. return Object.keys(query).length ? query : void 0;
  691. }
  692. /**
  693. * Create.
  694. *
  695. * @param {string} modelName
  696. * @param {object} modelData
  697. * @param {object|undefined} filter
  698. * @returns {Promise<object>}
  699. */
  700. async create(modelName, modelData, filter = void 0) {
  701. const idPropName = this._getIdPropName(modelName);
  702. const idValue = modelData[idPropName];
  703. if (idValue == null || idValue === "" || idValue === 0) {
  704. const pkType = this._getIdType(modelName);
  705. if (pkType !== import_js_repository4.DataType.STRING && pkType !== import_js_repository4.DataType.ANY)
  706. throw new import_js_repository9.InvalidArgumentError(
  707. "MongoDB unable to generate primary keys of %s. Do provide your own value for the %v property or set property type to String.",
  708. (0, import_js_repository5.capitalize)(pkType),
  709. idPropName
  710. );
  711. delete modelData[idPropName];
  712. }
  713. const tableData = this._toDatabase(modelName, modelData);
  714. const table = this._getCollection(modelName);
  715. const { insertedId } = await table.insertOne(tableData);
  716. const projection = this._buildProjection(
  717. modelName,
  718. filter && filter.fields
  719. );
  720. const insertedData = await table.findOne({ _id: insertedId }, { projection });
  721. return this._fromDatabase(modelName, insertedData);
  722. }
  723. /**
  724. * Replace by id.
  725. *
  726. * @param {string} modelName
  727. * @param {string|number} id
  728. * @param {object} modelData
  729. * @param {object|undefined} filter
  730. * @returns {Promise<object>}
  731. */
  732. async replaceById(modelName, id, modelData, filter = void 0) {
  733. id = this._coerceId(id);
  734. const idPropName = this._getIdPropName(modelName);
  735. modelData[idPropName] = id;
  736. const tableData = this._toDatabase(modelName, modelData);
  737. const table = this._getCollection(modelName);
  738. const { matchedCount } = await table.replaceOne({ _id: id }, tableData);
  739. if (matchedCount < 1)
  740. throw new import_js_repository9.InvalidArgumentError("Identifier %v is not found.", String(id));
  741. const projection = this._buildProjection(
  742. modelName,
  743. filter && filter.fields
  744. );
  745. const replacedData = await table.findOne({ _id: id }, { projection });
  746. return this._fromDatabase(modelName, replacedData);
  747. }
  748. /**
  749. * Replace or create.
  750. *
  751. * @param {string} modelName
  752. * @param {object} modelData
  753. * @param {object|undefined} filter
  754. * @returns {Promise<object>}
  755. */
  756. async replaceOrCreate(modelName, modelData, filter = void 0) {
  757. const idPropName = this._getIdPropName(modelName);
  758. let idValue = modelData[idPropName];
  759. idValue = this._coerceId(idValue);
  760. if (idValue == null || idValue === "" || idValue === 0) {
  761. const pkType = this._getIdType(modelName);
  762. if (pkType !== import_js_repository4.DataType.STRING && pkType !== import_js_repository4.DataType.ANY)
  763. throw new import_js_repository9.InvalidArgumentError(
  764. "MongoDB unable to generate primary keys of %s. Do provide your own value for the %v property or set property type to String.",
  765. (0, import_js_repository5.capitalize)(pkType),
  766. idPropName
  767. );
  768. delete modelData[idPropName];
  769. idValue = void 0;
  770. }
  771. const tableData = this._toDatabase(modelName, modelData);
  772. const table = this._getCollection(modelName);
  773. if (idValue == null) {
  774. const { insertedId } = await table.insertOne(tableData);
  775. idValue = insertedId;
  776. } else {
  777. const { upsertedId } = await table.replaceOne({ _id: idValue }, tableData, {
  778. upsert: true
  779. });
  780. if (upsertedId) idValue = upsertedId;
  781. }
  782. const projection = this._buildProjection(
  783. modelName,
  784. filter && filter.fields
  785. );
  786. const upsertedData = await table.findOne({ _id: idValue }, { projection });
  787. return this._fromDatabase(modelName, upsertedData);
  788. }
  789. /**
  790. * Patch.
  791. *
  792. * @param {string} modelName
  793. * @param {object} modelData
  794. * @param {object|undefined} where
  795. * @returns {Promise<number>}
  796. */
  797. async patch(modelName, modelData, where = void 0) {
  798. const idPropName = this._getIdPropName(modelName);
  799. delete modelData[idPropName];
  800. const query = this._buildQuery(modelName, where) || {};
  801. const tableData = this._toDatabase(modelName, modelData);
  802. const table = this._getCollection(modelName);
  803. const { matchedCount } = await table.updateMany(query, { $set: tableData });
  804. return matchedCount;
  805. }
  806. /**
  807. * Patch by id.
  808. *
  809. * @param {string} modelName
  810. * @param {string|number} id
  811. * @param {object} modelData
  812. * @param {object|undefined} filter
  813. * @returns {Promise<object>}
  814. */
  815. async patchById(modelName, id, modelData, filter = void 0) {
  816. id = this._coerceId(id);
  817. const idPropName = this._getIdPropName(modelName);
  818. delete modelData[idPropName];
  819. const tableData = this._toDatabase(modelName, modelData);
  820. const table = this._getCollection(modelName);
  821. const { matchedCount } = await table.updateOne({ _id: id }, { $set: tableData });
  822. if (matchedCount < 1)
  823. throw new import_js_repository9.InvalidArgumentError("Identifier %v is not found.", String(id));
  824. const projection = this._buildProjection(
  825. modelName,
  826. filter && filter.fields
  827. );
  828. const patchedData = await table.findOne({ _id: id }, { projection });
  829. return this._fromDatabase(modelName, patchedData);
  830. }
  831. /**
  832. * Find.
  833. *
  834. * @param {string} modelName
  835. * @param {object|undefined} filter
  836. * @returns {Promise<object[]>}
  837. */
  838. async find(modelName, filter = void 0) {
  839. filter = filter || {};
  840. const query = this._buildQuery(modelName, filter.where);
  841. const sort = this._buildSort(modelName, filter.order);
  842. const limit = filter.limit || void 0;
  843. const skip = filter.skip || void 0;
  844. const projection = this._buildProjection(modelName, filter.fields);
  845. const collection = this._getCollection(modelName);
  846. const options = { sort, limit, skip, projection };
  847. const tableItems = await collection.find(query, options).toArray();
  848. return tableItems.map((v) => this._fromDatabase(modelName, v));
  849. }
  850. /**
  851. * Find by id.
  852. *
  853. * @param {string} modelName
  854. * @param {string|number} id
  855. * @param {object|undefined} filter
  856. * @returns {Promise<object>}
  857. */
  858. async findById(modelName, id, filter = void 0) {
  859. id = this._coerceId(id);
  860. const table = this._getCollection(modelName);
  861. const projection = this._buildProjection(
  862. modelName,
  863. filter && filter.fields
  864. );
  865. const patchedData = await table.findOne({ _id: id }, { projection });
  866. if (!patchedData)
  867. throw new import_js_repository9.InvalidArgumentError("Identifier %v is not found.", String(id));
  868. return this._fromDatabase(modelName, patchedData);
  869. }
  870. /**
  871. * Delete.
  872. *
  873. * @param {string} modelName
  874. * @param {object|undefined} where
  875. * @returns {Promise<number>}
  876. */
  877. async delete(modelName, where = void 0) {
  878. const table = this._getCollection(modelName);
  879. const query = this._buildQuery(modelName, where);
  880. const { deletedCount } = await table.deleteMany(query);
  881. return deletedCount;
  882. }
  883. /**
  884. * Delete by id.
  885. *
  886. * @param {string} modelName
  887. * @param {string|number} id
  888. * @returns {Promise<boolean>}
  889. */
  890. async deleteById(modelName, id) {
  891. id = this._coerceId(id);
  892. const table = this._getCollection(modelName);
  893. const { deletedCount } = await table.deleteOne({ _id: id });
  894. return deletedCount > 0;
  895. }
  896. /**
  897. * Exists.
  898. *
  899. * @param {string} modelName
  900. * @param {string|number} id
  901. * @returns {Promise<boolean>}
  902. */
  903. async exists(modelName, id) {
  904. id = this._coerceId(id);
  905. const table = this._getCollection(modelName);
  906. const result = await table.findOne({ _id: id }, {});
  907. return result != null;
  908. }
  909. /**
  910. * Count.
  911. *
  912. * @param {string} modelName
  913. * @param {object|undefined} where
  914. * @returns {Promise<number>}
  915. */
  916. async count(modelName, where = void 0) {
  917. const query = this._buildQuery(modelName, where);
  918. const table = this._getCollection(modelName);
  919. return await table.count(query);
  920. }
  921. };
  922. __name(_MongodbAdapter, "MongodbAdapter");
  923. var MongodbAdapter = _MongodbAdapter;
  924. // Annotate the CommonJS export names for ESM import in node:
  925. 0 && (module.exports = {
  926. MongodbAdapter
  927. });