UNPKG

fireorm

Version:
448 lines 22.4 kB
"use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; Object.defineProperty(exports, "__esModule", { value: true }); exports.AbstractFirestoreRepository = void 0; var class_transformer_1 = require("class-transformer"); var Serialize_1 = require("./Decorators/Serialize"); var TypeGuards_1 = require("./TypeGuards"); var MetadataUtils_1 = require("./MetadataUtils"); var BaseRepository_1 = require("./BaseRepository"); var QueryBuilder_1 = require("./QueryBuilder"); var utils_1 = require("./utils"); var Errors_1 = require("./Errors"); var AbstractFirestoreRepository = /** @class */ (function (_super) { __extends(AbstractFirestoreRepository, _super); function AbstractFirestoreRepository(pathOrConstructor) { var _this = _super.call(this) || this; _this.toSerializableObject = function (obj) { return utils_1.serializeEntity(obj, _this.colMetadata.subCollections); }; _this.transformFirestoreTypes = function (obj) { Object.keys(obj).forEach(function (key) { var val = obj[key]; if (!obj[key]) return; if (TypeGuards_1.isTimestamp(val)) { obj[key] = val.toDate(); } else if (TypeGuards_1.isGeoPoint(val)) { var latitude = val.latitude, longitude = val.longitude; obj[key] = { latitude: latitude, longitude: longitude }; } else if (TypeGuards_1.isDocumentReference(val)) { var id = val.id, path = val.path; obj[key] = { id: id, path: path }; } else if (TypeGuards_1.isObject(val)) { _this.transformFirestoreTypes(val); } }); return obj; }; _this.initializeSubCollections = function (entity, tran, tranRefStorage) { // Requiring here to prevent circular dependency // eslint-disable-next-line @typescript-eslint/no-var-requires var getRepository = require('./helpers').getRepository; // eslint-disable-next-line @typescript-eslint/no-var-requires var FirestoreTransaction = require('./Transaction/FirestoreTransaction').FirestoreTransaction; _this.colMetadata.subCollections.forEach(function (subCol) { var _a, _b; var pathWithSubCol = _this.path + "/" + entity.id + "/" + subCol.name; var propertyKey = subCol.propertyKey; // If we are inside a transaction, our subcollections should also be TransactionRepositories if (tran && tranRefStorage) { var firestoreTransaction = new FirestoreTransaction(tran, tranRefStorage); var repository = firestoreTransaction.getRepository(pathWithSubCol); tranRefStorage.add({ propertyKey: propertyKey, path: pathWithSubCol, entity: entity }); Object.assign(entity, (_a = {}, _a[propertyKey] = repository, _a)); } else { Object.assign(entity, (_b = {}, _b[propertyKey] = getRepository(pathWithSubCol), _b)); } }); }; _this.extractTFromDocSnap = function (doc, tran, tranRefStorage) { var entity = class_transformer_1.plainToClass(_this.colMetadata.entityConstructor, __assign({ id: doc.id }, _this.transformFirestoreTypes(doc.data() || {}))); _this.initializeSubCollections(entity, tran, tranRefStorage); _this.initializeSerializedObjects(entity); return entity; }; _this.extractTFromColSnap = function (q, tran, tranRefStorage) { return q.docs.filter(function (d) { return d.exists; }).map(function (d) { return _this.extractTFromDocSnap(d, tran, tranRefStorage); }); }; var _a = MetadataUtils_1.getMetadataStorage(), getCollection = _a.getCollection, config = _a.config, firestoreRef = _a.firestoreRef; if (!firestoreRef) { throw new Error('Firestore must be initialized first'); } _this.config = config; var colMetadata = getCollection(pathOrConstructor); if (!colMetadata) { throw new Errors_1.NoMetadataError(pathOrConstructor); } _this.colMetadata = colMetadata; _this.path = typeof pathOrConstructor === 'string' ? pathOrConstructor : _this.colMetadata.name; _this.firestoreColRef = firestoreRef.collection(_this.path); return _this; } AbstractFirestoreRepository.prototype.initializeSerializedObjects = function (entity) { var _this = this; Object.keys(entity).forEach(function (propertyKey) { if (Reflect.getMetadata(Serialize_1.serializeKey, entity, propertyKey) !== undefined) { var constructor_1 = Reflect.getMetadata(Serialize_1.serializeKey, entity, propertyKey); var data = entity; var subData = data[propertyKey]; if (Array.isArray(subData)) { entity[propertyKey] = subData.map(function (value) { var subEntity = new constructor_1(); for (var i in value) { subEntity[i] = value[i]; } _this.initializeSerializedObjects(subEntity); return subEntity; }); } else { var subEntity = new constructor_1(); for (var i in subData) { subEntity[i] = subData[i]; } _this.initializeSerializedObjects(subEntity); entity[propertyKey] = subEntity; } } }); }; /** * Returns a new QueryBuilder with a filter specifying that the * value in @param prop must be equal to @param val. * * @param {IWherePropParam<T>} prop field to be filtered on, where * prop could be keyof T or a lambda where T is the first parameter * @param {IFirestoreVal} val value to compare in the filter * @returns {QueryBuilder<T>} A new QueryBuilder with the specified * query applied. * @memberof AbstractFirestoreRepository */ AbstractFirestoreRepository.prototype.whereEqualTo = function (prop, val) { return new QueryBuilder_1.QueryBuilder(this).whereEqualTo(prop, val); }; /** * Returns a new QueryBuilder with a filter specifying that the * value in @param prop must not be equal to @param val. * * @param {IWherePropParam<T>} prop field to be filtered on, where * prop could be keyof T or a lambda where T is the first parameter * @param {IFirestoreVal} val value to compare in the filter * @returns {QueryBuilder<T>} A new QueryBuilder with the specified * query applied. * @memberof AbstractFirestoreRepository */ AbstractFirestoreRepository.prototype.whereNotEqualTo = function (prop, val) { return new QueryBuilder_1.QueryBuilder(this).whereNotEqualTo(prop, val); }; /** * Returns a new QueryBuilder with a filter specifying that the * value in @param prop must be greater than @param val. * * @param {IWherePropParam<T>} prop field to be filtered on, where * prop could be keyof T or a lambda where T is the first parameter * @param {IFirestoreVal} val value to compare in the filter * @returns {QueryBuilder<T>} A new QueryBuilder with the specified * query applied. * @memberof AbstractFirestoreRepository */ AbstractFirestoreRepository.prototype.whereGreaterThan = function (prop, val) { return new QueryBuilder_1.QueryBuilder(this).whereGreaterThan(prop, val); }; /** * Returns a new QueryBuilder with a filter specifying that the * value in @param prop must be greater or equal than @param val. * * @param {IWherePropParam<T>} prop field to be filtered on, where * prop could be keyof T or a lambda where T is the first parameter * @param {IFirestoreVal} val value to compare in the filter * @returns {QueryBuilder<T>} A new QueryBuilder with the specified * query applied. * @memberof AbstractFirestoreRepository */ AbstractFirestoreRepository.prototype.whereGreaterOrEqualThan = function (prop, val) { return new QueryBuilder_1.QueryBuilder(this).whereGreaterOrEqualThan(prop, val); }; /** * Returns a new QueryBuilder with a filter specifying that the * value in @param prop must be less than @param val. * * @param {IWherePropParam<T>} prop field to be filtered on, where * prop could be keyof T or a lambda where T is the first parameter * @param {IFirestoreVal} val value to compare in the filter * @returns {QueryBuilder<T>} A new QueryBuilder with the specified * query applied. * @memberof AbstractFirestoreRepository */ AbstractFirestoreRepository.prototype.whereLessThan = function (prop, val) { return new QueryBuilder_1.QueryBuilder(this).whereLessThan(prop, val); }; /** * Returns a new QueryBuilder with a filter specifying that the * value in @param prop must be less or equal than @param val. * * @param {IWherePropParam<T>} prop field to be filtered on, where * prop could be keyof T or a lambda where T is the first parameter * @param {IFirestoreVal} val value to compare in the filter * @returns {QueryBuilder<T>} A new QueryBuilder with the specified * query applied. * @memberof AbstractFirestoreRepository */ AbstractFirestoreRepository.prototype.whereLessOrEqualThan = function (prop, val) { return new QueryBuilder_1.QueryBuilder(this).whereLessOrEqualThan(prop, val); }; /** * Returns a new QueryBuilder with a filter specifying that the * value in @param val must be contained in @param prop. * * @param {IWherePropParam<T>} prop field to be filtered on, where * prop could be keyof T or a lambda where T is the first parameter * @param {IFirestoreVal} val value to compare in the filter * @returns {QueryBuilder<T>} A new QueryBuilder with the specified * query applied. * @memberof AbstractFirestoreRepository */ AbstractFirestoreRepository.prototype.whereArrayContains = function (prop, val) { return new QueryBuilder_1.QueryBuilder(this).whereArrayContains(prop, val); }; /** * Returns a new QueryBuilder with a filter specifying that the * field @param prop is an array that contains one or more of the comparison values in @param val * * @param {IWherePropParam<T>} prop field to be filtered on, where * prop could be keyof T or a lambda where T is the first parameter * @param {IFirestoreVal[]} val array of values to compare in the filter (max 10 items in array) * @returns {QueryBuilder<T>} A new QueryBuilder with the specified * query applied. * @memberof AbstractFirestoreRepository */ AbstractFirestoreRepository.prototype.whereArrayContainsAny = function (prop, val) { return new QueryBuilder_1.QueryBuilder(this).whereArrayContainsAny(prop, val); }; /** * Returns a new QueryBuilder with a filter specifying that the * field @param prop matches any of the comparison values in @param val * * @param {IWherePropParam<T>} prop field to be filtered on, where * prop could be keyof T or a lambda where T is the first parameter * @param {IFirestoreVal[]} val[] array of values to compare in the filter (max 10 items in array) * @returns {QueryBuilder<T>} A new QueryBuilder with the specified * query applied. * @memberof AbstractFirestoreRepository */ AbstractFirestoreRepository.prototype.whereIn = function (prop, val) { return new QueryBuilder_1.QueryBuilder(this).whereIn(prop, val); }; /** * Returns a new QueryBuilder with a filter specifying that the * field @param prop matches none of the comparison values in @param val * * @param {IWherePropParam<T>} prop field to be filtered on, where * prop could be keyof T or a lambda where T is the first parameter * @param {IFirestoreVal[]} val[] array of values to compare in the filter (max 10 items in array) * @returns {QueryBuilder<T>} A new QueryBuilder with the specified * query applied. * @memberof AbstractFirestoreRepository */ AbstractFirestoreRepository.prototype.whereNotIn = function (prop, val) { return new QueryBuilder_1.QueryBuilder(this).whereNotIn(prop, val); }; /** * Returns a new QueryBuilder with a maximum number of results * to return. Can only be used once per query. * * @param {number} limitVal maximum number of results to return * Must be greater or equal than 0 * @returns {IQueryBuilder<T>} QueryBuilder A new QueryBuilder with * the specified limit applied * @memberof AbstractFirestoreRepository */ AbstractFirestoreRepository.prototype.limit = function (limitVal) { if (limitVal < 0) { throw new Error("limitVal must be greater than 0. It received: " + limitVal); } return new QueryBuilder_1.QueryBuilder(this).limit(limitVal); }; /** * Returns a new QueryBuilder with an additional ascending order * specified by @param prop. Can only be used once per query. * * @param {IWherePropParam<T>} prop field to be ordered on, where * prop could be keyof T or a lambda where T is the first parameter * @returns {QueryBuilder<T>} A new QueryBuilder with the specified * ordering applied. * @memberof AbstractFirestoreRepository */ AbstractFirestoreRepository.prototype.orderByAscending = function (prop) { return new QueryBuilder_1.QueryBuilder(this).orderByAscending(prop); }; /** * Returns a new QueryBuilder with an additional descending order * specified by @param prop. Can only be used once per query. * * @param {IWherePropParam<T>} prop field to be ordered on, where * prop could be keyof T or a lambda where T is the first parameter * @returns {QueryBuilder<T>} A new QueryBuilder with the specified * ordering applied. * @memberof AbstractFirestoreRepository */ AbstractFirestoreRepository.prototype.orderByDescending = function (prop) { return new QueryBuilder_1.QueryBuilder(this).orderByDescending(prop); }; /** * Execute the query and applies all the filters (if specified) * * @returns {Promise<T[]>} List of documents that matched the filters * (if specified) * @memberof AbstractFirestoreRepository */ AbstractFirestoreRepository.prototype.find = function () { return new QueryBuilder_1.QueryBuilder(this).find(); }; /** * Execute the query to find at least one document matching all * filters (if specified) * * @returns {Promise<T | null>} One document that matched the filters * (if specified), or null if none exists. * * @memberof AbstractFirestoreRepository */ AbstractFirestoreRepository.prototype.findOne = function () { return new QueryBuilder_1.QueryBuilder(this).findOne(); }; /** * Returns a new QueryBuilder with an custom query * specified by @param func. Can only be used once per query. * * @param {ICustomQuery<T>} func function to run in a new query * @returns {QueryBuilder<T>} A new QueryBuilder with the specified * custom query applied. * @memberof AbstractFirestoreRepository */ AbstractFirestoreRepository.prototype.customQuery = function (func) { return new QueryBuilder_1.QueryBuilder(this).customQuery(func); }; /** * Uses class-validator to validate an entity using decorators set in the collection class * * @param item class or object representing an entity * @returns {Promise<ValidationError[]>} An array of class-validator errors */ AbstractFirestoreRepository.prototype.validate = function (item) { return __awaiter(this, void 0, void 0, function () { var classValidator, Entity, entity, error_1; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, , 3]); return [4 /*yield*/, Promise.resolve().then(function () { return __importStar(require('class-validator')); })]; case 1: classValidator = _a.sent(); Entity = this.colMetadata.entityConstructor; entity = item instanceof Entity ? item : Object.assign(new Entity(), item); return [2 /*return*/, classValidator.validate(entity, this.config.validatorOptions)]; case 2: error_1 = _a.sent(); if (error_1.code === 'MODULE_NOT_FOUND') { throw new Error('It looks like class-validator is not installed. Please run `npm i -S class-validator` to fix this error, or initialize FireORM with `validateModels: false` to disable validation.'); } throw error_1; case 3: return [2 /*return*/]; } }); }); }; return AbstractFirestoreRepository; }(BaseRepository_1.BaseRepository)); exports.AbstractFirestoreRepository = AbstractFirestoreRepository; //# sourceMappingURL=AbstractFirestoreRepository.js.map