import {ISerializable} from '../database/serializeable.interface'; import {v4} from 'node-uuid/node'; import { IGeoTransformStrategy } from './geo/geo-transform-strategy.interface'; import { ResolveGeoTransformStrategy } from './geo/resolve-geo-transform-strategy'; import { IFeatureCollection, IGeoJSONFeature } from '../utility/feature-collection.interface'; import turf from 'turf'; import _ from 'lodash'; export class RecordCollection implements ISerializable { /* tslint:disable */ private _id: string; private _rev: string; /* tslint:disable */ name: string; label: string; type: string; records: IRecord[]; fields: IRecordField[]; geoTransformer: IGeoTransformStrategy; constructor(properties: ISerializedRecordCollection) { this._id = properties._id || v4(); this._rev = properties._rev ? properties._rev : undefined; this.name = properties.name; this.label = properties.label; this.type = properties.type; this.records = properties.records; this.fields = properties.fields; if (properties.geoTransformStrategy) { this.geoTransformer = ResolveGeoTransformStrategy.resolveStrategy( properties.geoTransformStrategy ); } } get id(): string { return this._id; } get rev(): string { return this._rev; } set rev(val: string) { this._rev = val; } get geoJson(): IFeatureCollection { const allFeatures = _(this.records) .map(this.getRecordGeoJson.bind(this)) .map((featureCol: IFeatureCollection) => featureCol.features) .flatten() .value(); return turf.featurecollection(allFeatures); } get visibleFields(): IRecordField[] { return _.filter(this.fields, (field) => field.visible); } serialize(): ISerializedRecordCollection { return { _id: this.id, _rev: this._rev, name: this.name, label: this.label, type: this.type, fields: this.fields, records: this.records, geoTransformStrategy: this.geoTransformer ? ResolveGeoTransformStrategy.exportStrategy(this.geoTransformer) : null }; } getRecordGeoJson(record: IRecord): IFeatureCollection { if (!this.geoTransformer) { throw ` Unable to get record geojson, no transformer specified for collection ${this.id}, ${this.name} `; } return this.geoTransformer.transform(record, this); } deserialize(from: ISerializedRecordCollection): RecordCollection { return new RecordCollection(from); } /** * Clones this record collection, optionally overwriting any properties. */ clone(properties: ISerializedRecordCollection = {}) { return new RecordCollection(_.assign(this.serialize(), properties)); } } export interface ISerializedRecordCollection { _id?: string; _rev?: string; name?: string; label?: string; type?: string; records?: IRecord[]; fields?: IRecordField[]; geoTransformStrategy?: string; } export interface IRecord { _id?: string; 'record-type'?: string, [property: string]: any; } export interface IRecordField { name: string; label: string; type: string; visible: boolean; }