Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 | import {RemoteFile} from "./files"; const {Entity} = require("electrodb"); const FilterOperations = ["eq","gt","lt","gte","lte","between","begins","exists","notExists","contains","notContains"] as const; export type IndexTypes = 'pk' | 'sk'; export type Attribute = { type: 'string' | 'number' | 'boolean' | 'any' | 'enum'; name: string; required: boolean; readOnly: boolean; enumArray: string[]; } export type Facet = { type: IndexTypes; name: string; } type IndexKey = {field: string, facets: string[]}; type Index = { index: string; pk: IndexKey; sk?: IndexKey; } type IndexFacet = { all: Facet[]; } export type InstanceAccessType = "entity" | "collection"; export type ElectroInstanceType = "service" | "entity" | "model"; export type ElectroInstances = Service | Entity; export type Entity = { _instance: {description: "entity"} // really a `symbol` but typescript doesnt understand identifiers: { model: string version: string }; query: QueryRecord; get(val: any): any delete: QueryMethod; create: QueryMethod; patch: QueryMethod; scan: QueryOperation; find: any model: { entity: string service: string facets: { byIndex: Record<string, IndexFacet> fields: string[] } schema: { attributes: Record<string, Attribute> }, indexes: Record<string, Index>, translations: { indexes: { fromIndexToAccessPattern: Record<string, string>; fromAccessPatternToIndex: Record<string, string>; } } } } export type Service = { _instance: {description: "service"} entities: Record<string, Entity> service: { name: string; table: string; } collectionSchema: Record<string, CollectionSchema> collections: QueryRecord find: Record<string, any> } type CollectionSchema = { attributes: Record<string, Attribute>, entities: Record<string, Entity> keys: Index & {name: string} } export type FilterOperation = (typeof FilterOperations)[number]; export abstract class Instance { public name: string; public service: string; public type: InstanceAccessType; private __hasSK: boolean|undefined; abstract getItem(): Object; abstract getAccessPatternName(index?: string): string; abstract getIndexName(accessPattern?: string): string; abstract getAccessPattern(accessPattern?: string): Index; abstract getAllKeyFieldNames(): string[]; abstract getAttributes(): Record<string, Attribute>; abstract getFacets(name?: string): Facet[]; abstract getIndexes(): Index[] abstract getStaticProperties(): {name: string, value: string}[]; abstract hasAccessPattern(accessPattern: string): boolean; static readonly FilterOperations = FilterOperations; static isOperation(operation: string = ""): operation is FilterOperation { return !!Instance.FilterOperations.find(op => op.toLowerCase() === operation.toLowerCase()); } constructor(name: string, service: string, type: InstanceAccessType) { this.name = name; this.type = type; this.service = service; } getIndexTypeName(accessPattern: string): string { return `${accessPattern}Index`; } getKeyFieldNames(indexName: string = ""): string[] { let accessPattern = this.getAccessPatternName(indexName) let index = this.getAccessPattern(accessPattern); let names = [index.pk.field]; if (index.sk !== undefined) { names.push(index.sk.field); } return names; } getAttribute(name: string): Attribute { let attributes = this.getAttributes(); let attribute = attributes[name]; if (attribute === undefined) { throw new Error(`Attribute invalid: ${name}`); } return attribute; } getAttributeTypeName(attribute: string): string { let attr = this.getAttribute(attribute); if (attr.type === "enum") { return `${attribute}Enum`; } return attr.type; } getEnums(): Record<string, string[]> { let attributes = this.getAttributes(); let enums: Record<string, string[]> = {}; for (let name of Object.keys(attributes)) { let attribute = attributes[name]; if (attribute.type === "enum") { enums[name] = [...attribute.enumArray] } } return enums; } hasSK(): boolean { if (typeof this.__hasSK === "boolean") { return this.__hasSK; } let facets = this.getFacets(); for (let i = 0; i < facets.length; i++) { if (facets[i].type === "sk") { return this.setHasSKCache(true); } } return this.setHasSKCache(false); } private setHasSKCache(value: boolean): boolean { this.__hasSK = value; return value; } } export class EntityInstance extends Instance { public instance: Entity; constructor(name: string, service: string, instance: Entity) { super(name, service, "entity"); if (!instance || instance._instance.description !== "entity") { throw new Error("Instance is not of type Service"); } this.instance = instance; } hasAccessPattern(accessPattern: string): boolean { return this.instance.model.translations.indexes.fromAccessPatternToIndex[accessPattern] !== undefined } getStaticProperties(): {name: string, value: string}[] { return [ {name: "model", value: JSON.stringify(this.instance.model)}, {name: "identifiers", value: JSON.stringify(this.instance.identifiers)} ] } getAccessPatternName(index: string = ""): string { return this.instance.model.translations.indexes.fromIndexToAccessPattern[index]; } getIndexName(accessPattern: string = "") { return this.instance.model.translations.indexes.fromAccessPatternToIndex[accessPattern]; } getAccessPattern(accessPattern: string = ""): Index { return this.instance.model.indexes[accessPattern]; } getAttributes(): Record<string, Attribute> { return this.instance.model.schema.attributes; } getFacets(name: string = ""): Facet[] { return this.instance.model.facets.byIndex[name].all; } getAllKeyFieldNames(): string[] { return this.instance.model.facets.fields; } getItem(): Object { return this.getAttributes(); } getIndexes(): Index[] { return Object.values(this.instance.model.indexes); } } export class CollectionInstance extends Instance { public instance: CollectionSchema; constructor(name: string, service: string, instance: CollectionSchema) { super(name, service, "collection"); this.instance = instance; } hasAccessPattern(accessPattern: string): boolean { return this.name === accessPattern; } getStaticProperties(): {name: string, value: string}[] { return [] } getAccessPatternName(): string { return this.name; } getIndexName(): string { return this.instance.keys.name; } getAccessPattern(): Index { return this.instance.keys; } getIndexes(): Index[] { return [this.instance.keys] } getAttributes(): Record<string, Attribute> { return this.instance.attributes; } getFacets(): Facet[] { let index = this.getAccessPattern(); let facets: Facet[] = []; for (let pkFacet of index.pk.facets) { facets.push({type: "pk", name: pkFacet}); } if (index.sk !== undefined) { for (let skFacet of index.sk.facets) { facets.push({type: "sk", name: skFacet}); } } return facets; } getAllKeyFieldNames(): string[] { let fields: string[] = []; for (let entity of Object.values(this.instance.entities)) { fields = [...fields, ...entity.model.facets.fields]; } return Array.from(new Set(fields)); } getItem(): {[key: string]: Object} { let item: {[key: string]: Object} = {}; for (let entity of Object.values(this.instance.entities)) { let entityInstance = new EntityInstance(entity.model.entity, entity.model.service, entity); let attributes = Object.values(entityInstance.getAttributes()); let name = entityInstance.name; item[name] = attributes.map((attribute) => { return Object.assign({}, attribute, {type: this.getAttributeTypeName(attribute.name)}); }); } return item; } } type QueryRecord = Record<string, QueryMethod>; export type InstanceActions = { remove?: QueryMethod, create?: QueryMethod, patch?: QueryMethod }; export class ElectroInstance { public name: string; public isService: boolean; public instances: Instance[]; public service: string; public electro: ElectroInstances; public queries: QueryRecord; public scans: QueryRecord; public actions: Record<string, InstanceActions> static isEntity(electro: ElectroInstances): electro is Entity { return electro._instance.description === "entity"; } static isService(electro: ElectroInstances): electro is Service { return electro._instance.description === "service"; } static parse(electro: ElectroInstances): {name: string, instances: Instance[], queries: QueryRecord, actions: Record<string, {remove?: QueryMethod}>, scans: QueryRecord} { let name: string; let instances: Instance[] = []; let queries: QueryRecord = {}; let actions: Record<string, InstanceActions> = {}; let scans: QueryRecord = {}; if (ElectroInstance.isEntity(electro)) { name = electro.model.entity; let instance = new EntityInstance(name, electro.model.service, electro) scans[name] = () => electro.scan; instances.push(instance); for (let accessPattern in electro.query) { /** Using `find` instead of `query` here to allow queries to turn into scans if not all values are provided **/ queries[accessPattern] = (facets: object) => electro.query[accessPattern](facets); // queries[accessPattern] = electro.query[accessPattern]; /** -------------------------------------------------------------------------------------------------------- **/ } actions[name] = { remove: (facets: object) => electro.delete(facets), create: (facets: object) => electro.create(facets), patch: (facets: object) => electro.patch(facets), }; } else if (ElectroInstance.isService(electro)) { name = electro.service.name; for (let entity of Object.values(electro.entities)) { instances.push(new EntityInstance(entity.model.entity, electro.service.name, entity)); scans[entity.model.entity] = () => entity.scan; for (let accessPattern in entity.query) { /** Using `find` instead of `query` here to allow queries to turn into scans if not all values are provided **/ // queries[accessPattern] = (facets: object) => entity.find(facets); queries[accessPattern] = (facets: object) => entity.query[accessPattern](facets); /** -------------------------------------------------------------------------------------------------------- **/ } actions[entity.model.entity] = { remove: (facets: object) => entity.delete(facets), create: (facets: object) => entity.create(facets), patch: (facets: object) => entity.patch(facets), }; // queries.delete = entity.delete; } for (let collection of Object.keys(electro.collectionSchema)) { instances.push(new CollectionInstance(collection, electro.service.name, electro.collectionSchema[collection])); } for (let collection in electro.collections) { queries[collection] = electro.collections[collection]; } } else { throw new Error("File does not export instance of either Entity or Service."); } return {name, instances, queries, actions, scans}; } constructor(electro: ElectroInstances) { let {name, queries, instances, actions, scans} = ElectroInstance.parse(electro); this.scans = scans; this.name = name; this.electro = electro; this.queries = queries; this.instances = instances; this.service = instances[0].service; this.actions = actions; this.isService = ElectroInstance.isService(electro); } setName(name: string) { this.name = name; } getInstance(accessPattern: string): undefined | Instance { return this.instances.find(instance => instance.hasAccessPattern(accessPattern)); } eachQuery(cb: EachQueryCallback) { for (let [accessPattern, query] of Object.entries(this.queries)) { let instance = this.getInstance(accessPattern); if (instance) { cb(this.name, accessPattern, instance, query, this.actions[instance.name]) } } return this; } eachRemove(cb: EachQueryCallback) { for (let instance of this.instances) { let actions = this.actions[instance.name]; if (actions && actions.remove) { cb(this.name, instance.getAccessPatternName(), instance, actions.remove, actions); } } return this; } eachCreate(cb: EachQueryCallback) { for (let instance of this.instances) { let actions = this.actions[instance.name]; if (actions && actions.create) { cb(this.name, instance.getAccessPatternName(), instance, actions.create, actions); } } return this; } eachPatch(cb: EachQueryCallback) { for (let instance of this.instances) { let actions = this.actions[instance.name]; if (actions && actions.patch) { cb(this.name, instance.getAccessPatternName(), instance, actions.patch, actions); } } return this; } } export type EachQueryCallback = (serviceName: string, accessPatternName: string, entity: Instance, query: QueryMethod, actions: InstanceActions) => void; type AttributeFilterOperation = Record<FilterOperation, (value1: string, value2?: string) => string> type AttributeFilter = Record<string, AttributeFilterOperation> const whereAttributeSymbol: unique symbol = Symbol("where"); type WhereAttribute = typeof whereAttributeSymbol export type AttributeWhere = Record<string, WhereAttribute> export type OperationWhere = Record<FilterOperation, (attr: WhereAttribute, value1?: string, value2?: string) => string> export type QueryConfiguration = {params?: {TableName?: string, Limit?: number}}; export type QueryOperation = { set?: (facets: object) => QueryOperation; go: (config: QueryConfiguration) => Promise<object>; params: (config: QueryConfiguration) => object; filter: (cb: (attr: AttributeFilter) => string) => QueryOperation where: (cb: (attr: AttributeWhere, op: OperationWhere) => string) => QueryOperation }; export type QueryMethod = (facets: object) => QueryOperation; export class InstanceReader { public filePath: string; constructor(filePath: string) { this.filePath = InstanceReader.resolve(filePath); } static AllowedFileTypes = [".js", ".json"]; static resolve(filePath: string): string { let file = new RemoteFile(filePath); if (!file.test()) { throw new Error(`File ${file.path()} does not exist.`); } else if (!InstanceReader.AllowedFileTypes.includes(file.extention())) { throw new Error(`Only files of type "${InstanceReader.AllowedFileTypes.join(", ")}", are allowed. File also must export instance of Entity, Service, or Model`); } else { return file.path(); } } isElectroInstance(instance: any): instance is ElectroInstances { return instance && instance._instance !== undefined; } get({table, endpoint, region}: {table?: string, endpoint?: string, region?: string} = {}): [ElectroInstanceType, ElectroInstances] { let instance = require(this.filePath); if (this.isElectroInstance(instance)) { return [instance._instance.description, instance]; } else if (instance.attributes) { try { const DynamoDB = require("aws-sdk/clients/dynamodb"); const config: {endpoint?: string, region?: string} = {}; if (endpoint) { config.endpoint = endpoint; } if (region) { config.region = region; } const client = new DynamoDB.DocumentClient(config); const default_table_name = "your_table_name"; return ["model", new Entity(instance, {table: table || default_table_name, client})]; } catch(err) { throw err } // placeholder for importing model; } else { throw new Error("File must instance of Entity, Service, or Model."); } } } |