collection.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. const document_1 = require("./document");
  4. const query_1 = require("./query");
  5. const aggregate_1 = require("./aggregate");
  6. const datatype_1 = require("./serializer/datatype");
  7. const utils_1 = require("./utils/utils");
  8. const validate_1 = require("./validate");
  9. const type_1 = require("./utils/type");
  10. class CollectionReference extends query_1.Query {
  11. constructor(db, coll, apiOptions, transactionId) {
  12. super(db, coll, '', apiOptions, transactionId);
  13. if (transactionId) {
  14. this._transactionId = transactionId;
  15. }
  16. }
  17. get name() {
  18. return this._coll;
  19. }
  20. doc(docID) {
  21. if (typeof docID !== 'string' && typeof docID !== 'number') {
  22. throw new Error('docId必须为字符串或数字');
  23. }
  24. return new document_1.DocumentReference(this._db, this._coll, this._apiOptions, docID, this._transactionId);
  25. }
  26. async add(data) {
  27. let transformData = data;
  28. if (!type_1.isArray(data)) {
  29. transformData = [data];
  30. }
  31. transformData = transformData.map(item => {
  32. return utils_1.stringifyByEJSON(datatype_1.serialize(item));
  33. });
  34. let params = {
  35. collectionName: this._coll,
  36. data: transformData
  37. };
  38. if (this._transactionId) {
  39. params.transactionId = this._transactionId;
  40. }
  41. const res = await this._request.send('database.insertDocument', params, utils_1.getReqOpts(this._apiOptions));
  42. if (res.code) {
  43. return res;
  44. }
  45. if (!type_1.isArray(data)) {
  46. if (this._transactionId) {
  47. return {
  48. inserted: 1,
  49. ok: 1,
  50. id: res.data.insertedIds[0],
  51. requestId: res.requestId
  52. };
  53. }
  54. return {
  55. id: res.data.insertedIds[0],
  56. requestId: res.requestId
  57. };
  58. }
  59. return {
  60. ids: res.data.insertedIds,
  61. requestId: res.requestId
  62. };
  63. }
  64. aggregate() {
  65. return new aggregate_1.default(this._db, this._coll);
  66. }
  67. options(apiOptions) {
  68. validate_1.Validate.isValidOptions(apiOptions);
  69. return new CollectionReference(this._db, this._coll, apiOptions, this._transactionId);
  70. }
  71. }
  72. exports.CollectionReference = CollectionReference;