@solidstarters/solid-core 1.2.63 → 1.2.64

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@solidstarters/solid-core",
3
- "version": "1.2.63",
3
+ "version": "1.2.64",
4
4
  "description": "This module is a NestJS module containing all the required core providers required by a Solid application",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
package/src/interfaces.ts CHANGED
@@ -162,4 +162,8 @@ export interface QueuesModuleOptions {
162
162
  name: string;
163
163
  type: BrokerType;
164
164
  queueName: string;
165
- }
165
+ }
166
+
167
+ export type MediaWithFullUrl = Media & {
168
+ _full_url: string;
169
+ };
@@ -158,11 +158,18 @@ export class CrudHelperService {
158
158
 
159
159
  buildFilterQuery(qb: SelectQueryBuilder<any>, basicFilterDto: BasicFilterDto, entityAlias: string): SelectQueryBuilder<any> { //TODO : Check how to pass a type to SelectQueryBuilder instead of any
160
160
  let { limit, offset, showSoftDeleted, filters } = basicFilterDto;
161
- const { fields, sort, groupBy, populate = [] } = basicFilterDto;
161
+ const { fields, sort, groupBy, populate = [], populateMedia=[] } = basicFilterDto;
162
162
 
163
163
  // Normalize the fields, sort, groupBy and populate options i.e (since they can be either a string or an array of strings, when coming from the request)
164
164
  const normalizedFields = this.normalize(fields);
165
165
  const normalizedPopulate = this.normalize(populate);
166
+ const normalizedPopulateMedia = this.normalize(populateMedia);
167
+
168
+ // if normalizedPopulateMedia, has any nested media paths, then add then to populate excluding the last part
169
+ const additionalPopulate = this.additionalRelationsRequiredForMediaPopulation(normalizedPopulateMedia);
170
+ // Add the additional populate relations to the normalizedPopulate, if they are not already present
171
+ normalizedPopulate.push(...additionalPopulate.filter((relation) => !normalizedPopulate.includes(relation)));
172
+
166
173
  const normalizedSort = this.normalize(sort);
167
174
  const normalizedGroupBy = this.normalize(groupBy);
168
175
  if (normalizedGroupBy.length > 1) {
@@ -223,6 +230,17 @@ export class CrudHelperService {
223
230
  return qb;
224
231
  }
225
232
 
233
+ additionalRelationsRequiredForMediaPopulation(normalizedPopulateMedia: string[]) {
234
+ // Populate relations containing the media field
235
+ return normalizedPopulateMedia
236
+ .filter(pm => pm.includes("."))
237
+ .map((pm) => {
238
+ const mediaPathParts = pm.split('.');
239
+ if (mediaPathParts.length <= 1) return pm;
240
+ return mediaPathParts.slice(0, -1).join('.');
241
+ });
242
+ }
243
+
226
244
  private buildPopulateQuery(normalizedPopulate: string[], entityAlias: string, qb: SelectQueryBuilder<any>) {
227
245
  normalizedPopulate.forEach((relation) => {
228
246
  this.buildJoinQueryForRelation(qb, entityAlias, relation);
@@ -1,4 +1,4 @@
1
- import { BadRequestException } from "@nestjs/common";
1
+ import { BadRequestException, Optional } from "@nestjs/common";
2
2
  import { ConfigService } from "@nestjs/config";
3
3
  import { DiscoveryService, ModuleRef } from "@nestjs/core";
4
4
  import { EntityManager, In, IsNull, Not, QueryFailedError, SelectQueryBuilder } from "typeorm";
@@ -28,14 +28,13 @@ import { SelectionDynamicFieldCrudManager } from "../helpers/field-crud-managers
28
28
  import { SelectionStaticFieldCrudManager } from "../helpers/field-crud-managers/SelectionStaticFieldCrudManager";
29
29
  import { ShortTextFieldCrudManager } from "../helpers/field-crud-managers/ShortTextFieldCrudManager";
30
30
  import { UUIDFieldCrudManager } from "../helpers/field-crud-managers/UUIDFieldCrudManager";
31
- import { FieldCrudManager } from "../interfaces";
31
+ import { FieldCrudManager, MediaWithFullUrl } from "../interfaces";
32
32
  import { CrudHelperService } from "./crud-helper.service";
33
33
  import { FileService } from "./file.service";
34
34
  import { getMediaStorageProvider } from "./mediaStorageProviders";
35
35
  import { ModelMetadataService } from "./model-metadata.service";
36
36
  import { ModuleMetadataService } from "./module-metadata.service";
37
37
  import { UserContextService } from "./user-context.service";
38
- import { Optional } from "@nestjs/common";
39
38
  const DEFAULT_LIMIT = 10;
40
39
  const DEFAULT_OFFSET = 0;
41
40
  export class CRUDService<T> { // Add two generic value i.e Person,CreatePersonDto, so we get the proper types in our service
@@ -496,42 +495,85 @@ export class CRUDService<T> { // Add two generic value i.e Person,CreatePersonDt
496
495
  return r;
497
496
  }
498
497
 
499
- private async handlePopulateMedia(populateMedia: string[], entities: T[]) {
500
- const model = await this.modelMetadataService.findOneBySingularName(this.modelName, {
501
- fields: {
502
- model: true,
503
- mediaStorageProvider: true,
498
+ private async handlePopulateMedia(populateMedia: string[], entities: T[]) {
499
+ const model = await this.entityManager.getRepository(ModelMetadata).findOne({
500
+ where: {
501
+ singularName: this.modelName,
504
502
  },
505
- module: true,
503
+ relations: ['fields', 'fields.mediaStorageProvider', 'fields.model','module'],
506
504
  });
507
505
 
508
- const mediaFields = model.fields.filter(field => (field.type === 'mediaSingle' || field.type === 'mediaMultiple') && populateMedia.includes(field.name)
509
- );
510
-
511
- if (mediaFields.length > 0) {
512
- // Map over all entities and retrieve media in parallel for each entity
513
- await Promise.all(entities.map(async (entity) => {
514
- const mediaObj: Record<string, any> = {};
515
- // Retrieve media for each media field in parallel
516
- const media = await Promise.all(mediaFields.map(async (mediaField) => {
517
- const storageProviderMetadata = mediaField.mediaStorageProvider;
518
- const storageProviderType = storageProviderMetadata.type as MediaStorageProviderType;
519
- const storageProvider = await getMediaStorageProvider(this.moduleRef, storageProviderType);
520
- const mediaResult = await storageProvider.retrieve(entity, mediaField);
521
- mediaObj[mediaField.name] = mediaResult;
522
- }));
523
-
524
- // If media is found, assign to _media field
525
- if (media.length > 0) {
526
- entity['_media'] = mediaObj;
527
- }
528
- }));
506
+ // Will iterate through every entity & all populateMedia & call getMediaDetails for each field
507
+ for (const entity of entities) {
508
+ const mediaObj: Record<string, any> = {};
509
+ for (const mediaFieldPath of populateMedia) {
510
+ mediaObj[mediaFieldPath] = await this.getMediaObject(mediaFieldPath, model, entity);
511
+ }
512
+ entity['_media'] = mediaObj;
513
+ }
514
+ return entities;
515
+ }
516
+
517
+ private async getMediaObject(mediaFieldPath: string, model: ModelMetadata, entity: T) {
518
+ if (mediaFieldPath.includes('.')) { // mediaFieldPath is a nested field
519
+ const pathParts = mediaFieldPath.split('.');
520
+ const mediaFieldMetadata = await this.getFieldMetadataRecursively(pathParts, model.fields);
521
+ if (!mediaFieldMetadata) {
522
+ throw new BadRequestException(`Media field ${mediaFieldPath} not found in model ${this.modelName}`);
523
+ }
524
+
525
+ // We can assume that the media field entity model is already populated as part of the entity data
526
+ const mediaFieldEntity = this.getMediaFieldEntity(entity, pathParts);
527
+ if (!mediaFieldEntity) {
528
+ throw new BadRequestException(`Media field path ${mediaFieldPath} is not populated in model ${this.modelName}`);
529
+ }
530
+ const mediaWithFullUrl = await this.getMediaWithFullUrl(mediaFieldEntity, mediaFieldMetadata);
531
+ return mediaWithFullUrl;
532
+ }
533
+ else {
534
+ // mediaFieldPath is a single field
535
+ const mediaFieldMetadata = model.fields.find(field => field.name === mediaFieldPath);
536
+ if (!mediaFieldMetadata) {
537
+ throw new BadRequestException(`Media field ${mediaFieldPath} not found in model ${this.modelName}`);
538
+ }
539
+ const mediaWithFullUrl = await this.getMediaWithFullUrl(entity, mediaFieldMetadata);
540
+ return mediaWithFullUrl;
529
541
  }
530
542
  }
531
543
 
544
+ private getMediaFieldEntity(entity: T, mediaPathParts: string[]) {
545
+ let mediaFieldEntity = entity;
546
+ for (let i = 0; i < mediaPathParts.length - 1; i++) {
547
+ const pathPart = mediaPathParts[i];
548
+ if (mediaFieldEntity[pathPart]) {
549
+ mediaFieldEntity = mediaFieldEntity[pathPart];
550
+ } else {
551
+ throw new BadRequestException(`Media field ${pathPart} not found in entity ${JSON.stringify(entity)}`);
552
+ }
553
+ }
554
+ return mediaFieldEntity;
555
+ }
556
+
557
+ async getMediaWithFullUrl(mediaEntity: any, mediaFieldMetadata: FieldMetadata): Promise<MediaWithFullUrl>{
558
+ const storageProviderMetadata = mediaFieldMetadata.mediaStorageProvider;
559
+ const storageProviderType = storageProviderMetadata.type as MediaStorageProviderType;
560
+ const storageProvider = await getMediaStorageProvider(this.moduleRef, storageProviderType);
561
+ const mediaDetails = await storageProvider.retrieve(mediaEntity, mediaFieldMetadata);
562
+ return mediaDetails as MediaWithFullUrl;
563
+ }
564
+
532
565
  async findOne(id: number, query: any, solidRequestContext: any = {}) {
533
566
  const { populate = [], fields = [], populateMedia = [] } = query;
534
567
 
568
+ // const normalizedFields = this.crudHelperService.normalize(fields);
569
+ const normalizedPopulate = this.crudHelperService.normalize(populate);
570
+ const normalizedPopulateMedia = this.crudHelperService.normalize(populateMedia);
571
+
572
+ // if normalizedPopulateMedia, has any nested media paths, then add then to populate excluding the last part
573
+ const additionalPopulate = this.crudHelperService.additionalRelationsRequiredForMediaPopulation(normalizedPopulateMedia);
574
+ // Add the additional populate relations to the normalizedPopulate, if they are not already present
575
+ normalizedPopulate.push(...additionalPopulate.filter((relation) => !normalizedPopulate.includes(relation)));
576
+
535
577
  const model = await this.loadModel();
536
578
  // Check wheather user has update permission for model
537
579
  if (solidRequestContext.activeUser) {
@@ -541,42 +583,21 @@ export class CRUDService<T> { // Add two generic value i.e Person,CreatePersonDt
541
583
  }
542
584
  }
543
585
 
544
- const entity = await this.repo.findOne({
586
+ let entity = await this.repo.findOne({
545
587
  where: {
546
588
  //@ts-ignore
547
589
  id: id,
548
590
  },
549
- relations: populate,
591
+ relations: normalizedPopulate,
550
592
  select: fields,
551
593
  });
552
594
  if (!entity) {
553
595
  throw new Error(`Entity [${this.moduleName}.${this.modelName}] with id ${id} not found`);
554
596
  }
555
597
  // Populate the entity with the media
556
- if (populateMedia.length > 0) {
557
- const model = await this.modelMetadataService.findOneBySingularName(this.modelName, {
558
- fields: {
559
- model: true,
560
- mediaStorageProvider: true,
561
- },
562
- module: true,
563
- });
564
- const mediaObj: Record<string, any> = {};
565
- for (const mediaField of model.fields.filter(field => field.type === 'mediaSingle' || field.type === 'mediaMultiple')) {
566
- if (!populateMedia.includes(mediaField.name)) {
567
- continue;
568
- }
569
- const storageProviderMetadata = mediaField.mediaStorageProvider;
570
- const storageProviderType = storageProviderMetadata.type as MediaStorageProviderType;
571
- const storageProvider = await getMediaStorageProvider(this.moduleRef, storageProviderType);
572
- const mediaResult = await storageProvider.retrieve(entity, mediaField);
573
- let obj = { [mediaField.name]: mediaResult }
574
- mediaObj[mediaField.name] = mediaResult;
575
- // entity['media'][mediaField.name] = await storageProvider.retrieve(entity, mediaField);
576
- }
577
- if (Object.keys(mediaObj).length > 0) {
578
- entity['_media'] = mediaObj;
579
- }
598
+ if (normalizedPopulateMedia.length > 0) {
599
+ const populatedEntities = await this.handlePopulateMedia(normalizedPopulateMedia, [entity]);
600
+ entity = populatedEntities[0] as Awaited<T>;
580
601
  }
581
602
  return entity;
582
603
  }
@@ -775,4 +796,37 @@ export class CRUDService<T> { // Add two generic value i.e Person,CreatePersonDt
775
796
  }
776
797
 
777
798
 
799
+ async getFieldMetadataRecursively(pathParts: string[], fields: FieldMetadata[]) {
800
+ if (!pathParts || pathParts.length === 0) {
801
+ throw new BadRequestException('Path parts cannot be empty');
802
+ }
803
+
804
+ const [currentPart, ...remainingParts] = pathParts;
805
+ const field = fields.find(field => field.name === currentPart);
806
+
807
+ if (!field) {
808
+ throw new BadRequestException(`Field ${currentPart} not found in model ${this.modelName}`);
809
+ }
810
+
811
+ // Base case: last part, return the field
812
+ if (remainingParts.length === 0) {
813
+ return field;
814
+ }
815
+
816
+ if (!field.relationCoModelSingularName) {
817
+ throw new BadRequestException(`Field ${field.name} does not define a relationCoModelSingularName`);
818
+ }
819
+
820
+ const relationCoModel = await this.entityManager.getRepository(ModelMetadata).findOne({
821
+ where: { singularName: field.relationCoModelSingularName },
822
+ relations: ['fields', 'fields.mediaStorageProvider', 'fields.model'],
823
+ });
824
+
825
+ if (!relationCoModel) {
826
+ throw new BadRequestException(`Model ${field.relationCoModelSingularName} not found`);
827
+ }
828
+
829
+ return this.getFieldMetadataRecursively(remainingParts, relationCoModel.fields);
830
+ }
778
831
  }
832
+
package/src/services/1.js DELETED
@@ -1,6 +0,0 @@
1
- 1. Do i need to create a storeStreams method for aws service too?
2
- - Handle later
3
- 2. queues handling -> if queues is enabled by default, i.e triggerExport(exportTransactionEntity.id).
4
- - startExport should either return the data or return the transaction id
5
- 3. How to handle scenarios wherein, nested related exist.(do i need to only get the userkey)
6
- - show the userKey