@exogee/graphweaver-mikroorm 0.1.1 → 0.1.3

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.
Files changed (54) hide show
  1. package/lib/base-resolver/assign.d.ts +1 -1
  2. package/lib/base-resolver/assign.js +14 -13
  3. package/lib/base-resolver/assign.js.map +7 -0
  4. package/lib/base-resolver/index.js +1 -0
  5. package/lib/base-resolver/index.js.map +7 -0
  6. package/lib/base-resolver/provider.d.ts +27 -19
  7. package/lib/base-resolver/provider.js +135 -73
  8. package/lib/base-resolver/provider.js.map +7 -0
  9. package/lib/config.js +1 -0
  10. package/lib/config.js.map +7 -0
  11. package/lib/database.d.ts +9 -4
  12. package/lib/database.js +34 -28
  13. package/lib/database.js.map +7 -0
  14. package/lib/decorators/external-id-field.d.ts +8 -0
  15. package/lib/decorators/external-id-field.js +36 -0
  16. package/lib/decorators/external-id-field.js.map +7 -0
  17. package/lib/decorators/index.d.ts +1 -0
  18. package/lib/decorators/index.js +19 -0
  19. package/lib/decorators/index.js.map +7 -0
  20. package/lib/entities/audit-change.js +1 -0
  21. package/lib/entities/audit-change.js.map +7 -0
  22. package/lib/entities/audit-related-entity-change.js +1 -0
  23. package/lib/entities/audit-related-entity-change.js.map +7 -0
  24. package/lib/entities/base-entity.d.ts +1 -1
  25. package/lib/entities/base-entity.js +2 -1
  26. package/lib/entities/base-entity.js.map +7 -0
  27. package/lib/entities/index.js +1 -0
  28. package/lib/entities/index.js.map +7 -0
  29. package/lib/index.d.ts +2 -1
  30. package/lib/index.js +2 -2
  31. package/lib/index.js.map +7 -0
  32. package/lib/types/date-type.js +1 -0
  33. package/lib/types/date-type.js.map +7 -0
  34. package/lib/types/decimal-type.js +1 -0
  35. package/lib/types/decimal-type.js.map +7 -0
  36. package/lib/types/index.js +1 -0
  37. package/lib/types/index.js.map +7 -0
  38. package/lib/types/time-type.js +1 -0
  39. package/lib/types/time-type.js.map +7 -0
  40. package/lib/utils/authentication-context.js +1 -0
  41. package/lib/utils/authentication-context.js.map +7 -0
  42. package/lib/utils/change-tracker.js +1 -0
  43. package/lib/utils/change-tracker.js.map +7 -0
  44. package/lib/utils/errors.js +1 -0
  45. package/lib/utils/errors.js.map +7 -0
  46. package/lib/utils/index.js +1 -0
  47. package/lib/utils/index.js.map +7 -0
  48. package/lib/utils/tracked-entity.js +1 -0
  49. package/lib/utils/tracked-entity.js.map +7 -0
  50. package/lib/utils/untracked-property.js +1 -0
  51. package/lib/utils/untracked-property.js.map +7 -0
  52. package/package.json +7 -6
  53. package/lib/utils/generate-db-schema.d.ts +0 -1
  54. package/lib/utils/generate-db-schema.js +0 -30
@@ -3,5 +3,5 @@ interface AssignOptions {
3
3
  create?: boolean;
4
4
  update?: boolean;
5
5
  }
6
- export declare const assign: <T extends Partial<T>>(entity: T, data: EntityData<T>, options?: AssignOptions, visited?: Set<Partial<any>>) => Promise<T>;
6
+ export declare const assign: <T extends Partial<T>>(entity: T, data: EntityData<T>, options?: AssignOptions, visited?: Set<Partial<any>>, em?: import("@mikro-orm/postgresql").EntityManager<import("@mikro-orm/postgresql").PostgreSqlDriver>) => Promise<T>;
7
7
  export {};
@@ -24,7 +24,7 @@ module.exports = __toCommonJS(assign_exports);
24
24
  var import_core = require("@mikro-orm/core");
25
25
  var import_logger = require("@exogee/logger");
26
26
  var import_database = require("../database");
27
- const assign = async (entity, data, options, visited = /* @__PURE__ */ new Set()) => {
27
+ const assign = async (entity, data, options, visited = /* @__PURE__ */ new Set(), em = import_database.ConnectionManager.default.em) => {
28
28
  var _a;
29
29
  if (visited.has(entity))
30
30
  return entity;
@@ -38,7 +38,7 @@ const assign = async (entity, data, options, visited = /* @__PURE__ */ new Set()
38
38
  throw new Error(
39
39
  `Value is not an array while trying to assign to collection property ${property} on entity ${metadata.name}`
40
40
  );
41
- if (!(entityPropertyValue instanceof import_core.Collection)) {
41
+ if (!import_core.Utils.isCollection(entityPropertyValue)) {
42
42
  throw new Error(
43
43
  `Tried to merge array into non-collection property ${property} on entity ${metadata.name}`
44
44
  );
@@ -47,15 +47,15 @@ const assign = async (entity, data, options, visited = /* @__PURE__ */ new Set()
47
47
  for (const subvalue of value) {
48
48
  let entity2;
49
49
  if (subvalue.id) {
50
- entity2 = import_database.Database.em.getUnitOfWork().getById(propertyMetadata.type, subvalue.id);
50
+ entity2 = em.getUnitOfWork().getById(propertyMetadata.type, subvalue.id);
51
51
  if (!entity2) {
52
52
  if (Object.keys(subvalue).length === 1) {
53
- entity2 = import_database.Database.em.getReference(propertyMetadata.type, subvalue.id);
53
+ entity2 = em.getReference(propertyMetadata.type, subvalue.id);
54
54
  } else {
55
55
  import_logger.logger.warn(
56
56
  `Doing a full database fetch for ${propertyMetadata.type} with id ${subvalue.id}, this should ideally be prefetched into the Unit of Work before calling assign() for performance`
57
57
  );
58
- entity2 = (_a = await import_database.Database.em.findOne(propertyMetadata.type, {
58
+ entity2 = (_a = await em.findOne(propertyMetadata.type, {
59
59
  id: subvalue.id
60
60
  })) != null ? _a : void 0;
61
61
  }
@@ -71,7 +71,8 @@ const assign = async (entity, data, options, visited = /* @__PURE__ */ new Set()
71
71
  entityType: propertyMetadata.type,
72
72
  data: subvalue,
73
73
  options,
74
- visited
74
+ visited,
75
+ em
75
76
  });
76
77
  entityPropertyValue.add(newEntity);
77
78
  visitedEntities.add(newEntity);
@@ -85,10 +86,7 @@ const assign = async (entity, data, options, visited = /* @__PURE__ */ new Set()
85
86
  } else {
86
87
  const valueKeys = Object.keys(value);
87
88
  if (valueKeys.length === 1 && valueKeys[0] === "id") {
88
- entity[property] = import_database.Database.em.getReference(
89
- propertyMetadata.type,
90
- value.id
91
- );
89
+ entity[property] = em.getReference(propertyMetadata.type, value.id);
92
90
  } else {
93
91
  if (entityPropertyValue && !import_core.Reference.isReference(entityPropertyValue)) {
94
92
  throw new Error(
@@ -105,7 +103,8 @@ const assign = async (entity, data, options, visited = /* @__PURE__ */ new Set()
105
103
  entityType: propertyMetadata.type,
106
104
  data: value,
107
105
  options,
108
- visited
106
+ visited,
107
+ em
109
108
  });
110
109
  entity[property] = import_core.Reference.create(newEntity);
111
110
  }
@@ -121,7 +120,8 @@ const createOrAssignEntity = ({
121
120
  entityType,
122
121
  data,
123
122
  options,
124
- visited
123
+ visited,
124
+ em
125
125
  }) => {
126
126
  var _a, _b;
127
127
  const create = (_a = options == null ? void 0 : options.create) != null ? _a : true;
@@ -150,7 +150,7 @@ const createOrAssignEntity = ({
150
150
  )} was passed which does not have an ID property.`
151
151
  );
152
152
  }
153
- const entity2 = import_database.Database.em.create(entityType, {});
153
+ const entity2 = em.create(entityType, {});
154
154
  return assign(entity2, data, options, visited);
155
155
  }
156
156
  };
@@ -158,3 +158,4 @@ const createOrAssignEntity = ({
158
158
  0 && (module.exports = {
159
159
  assign
160
160
  });
161
+ //# sourceMappingURL=assign.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/base-resolver/assign.ts"],
4
+ "sourcesContent": ["import {\n\tAnyEntity,\n\tCollection,\n\tEntityData,\n\tEntityManager,\n\tEntityProperty,\n\tReference,\n\tReferenceType,\n\tUtils,\n\twrap,\n} from '@mikro-orm/core';\nimport { logger } from '@exogee/logger';\n\nimport { ConnectionManager } from '../database';\n\n// This is how Mikro ORM does it within their own code, so in this file we're ok with non-null assertions.\n/* eslint-disable @typescript-eslint/no-non-null-assertion */\n\ninterface AssignOptions {\n\t// Whether this assign should be allowed to create new entities.\n\t// If false and a create is attempted, assign will throw.\n\t// Defaults to true if not specified.\n\tcreate?: boolean;\n\n\t// Whether this assign should be allowed update existing entities.\n\t// If false and an update is attempted, assign will throw.\n\t// Defaults to true if not specified.\n\tupdate?: boolean;\n}\n\nexport const assign = async <T extends AnyEntity<T>>(\n\tentity: T,\n\tdata: EntityData<T>,\n\toptions?: AssignOptions,\n\tvisited = new Set<AnyEntity<any>>(),\n\tem = ConnectionManager.default.em\n) => {\n\tif (visited.has(entity)) return entity;\n\tvisited.add(entity);\n\n\t// We'll need the metadata for this entity to be able to traverse the properties later.\n\tconst metadata = wrap(entity, true).__meta!;\n\n\tfor (const [property, value] of Object.entries(data)) {\n\t\tconst entityPropertyValue = (entity as any)[property];\n\n\t\t// We're going to need the metadata for this property so we can ensure it exists and so that we can\n\t\t// navigate to related entities.\n\t\tconst propertyMetadata = (metadata.properties as any)[property] as\n\t\t\t| EntityProperty<T>\n\t\t\t| undefined;\n\n\t\tif (\n\t\t\tpropertyMetadata?.reference === ReferenceType.MANY_TO_MANY ||\n\t\t\tpropertyMetadata?.reference === ReferenceType.ONE_TO_MANY\n\t\t) {\n\t\t\tif (!Array.isArray(value))\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Value is not an array while trying to assign to collection property ${property} on entity ${metadata.name}`\n\t\t\t\t);\n\n\t\t\t// Ensure the entity has a loaded collection at the same place.\n\t\t\tif (!Utils.isCollection<T, any>(entityPropertyValue)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Tried to merge array into non-collection property ${property} on entity ${metadata.name}`\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst visitedEntities = new Set<T>();\n\n\t\t\tfor (const subvalue of value) {\n\t\t\t\tlet entity: T | undefined;\n\n\t\t\t\tif (subvalue.id) {\n\t\t\t\t\t// Get the current entity from the ORM if there's an ID.\n\t\t\t\t\tentity = em.getUnitOfWork().getById(propertyMetadata.type, subvalue.id);\n\n\t\t\t\t\tif (!entity) {\n\t\t\t\t\t\t// There are two cases here: either the user is trying to assign properties to the entity as well as changing members of a collection,\n\t\t\t\t\t\t// or they're just changing members of a collection.\n\t\t\t\t\t\t// For the former we actually need the entity from the DB, while for the latter we can let it slide and just pass an ID entity on down.\n\t\t\t\t\t\tif (Object.keys(subvalue).length === 1) {\n\t\t\t\t\t\t\t// It's just the ID.\n\t\t\t\t\t\t\tentity = em.getReference(propertyMetadata.type, subvalue.id) as T;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tlogger.warn(\n\t\t\t\t\t\t\t\t`Doing a full database fetch for ${propertyMetadata.type} with id ${subvalue.id}, this should ideally be prefetched into the Unit of Work before calling assign() for performance`\n\t\t\t\t\t\t\t);\n\n\t\t\t\t\t\t\t// We should be prefetching for performance in most cases here but if we don't have it we can load it now.\n\t\t\t\t\t\t\t// From base resolver a reason this would be needed is when you're switching collection values from one entity to another, e.g.\n\t\t\t\t\t\t\t// Business unit 1 -> Business unit 2. In this scenario we prefetch the one that's currently on the entity, but the one we're changing\n\t\t\t\t\t\t\t// to is not in the unit of work.\n\t\t\t\t\t\t\tentity =\n\t\t\t\t\t\t\t\t((await em.findOne(propertyMetadata.type, {\n\t\t\t\t\t\t\t\t\tid: subvalue.id,\n\t\t\t\t\t\t\t\t})) as T | null) ?? undefined;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (!entity) {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t`Attempted to assign as an update to '${propertyMetadata.name}' property of ${metadata.name} Entity, but even after a full fetch to the database ${propertyMetadata.type} with ID of ${subvalue.id} could not be found.`\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst newEntity = await createOrAssignEntity<T>({\n\t\t\t\t\tentity,\n\t\t\t\t\tentityType: propertyMetadata.type,\n\t\t\t\t\tdata: subvalue,\n\t\t\t\t\toptions,\n\t\t\t\t\tvisited,\n\t\t\t\t\tem,\n\t\t\t\t});\n\n\t\t\t\t// Ok, now we've got the created or updated entity, ensure it's in the collection\n\t\t\t\t// so its foreign keys are set correctly. If it's already in the collection this is a noop.\n\t\t\t\tentityPropertyValue.add(newEntity);\n\n\t\t\t\t// We need to keep track of the fact that this entity belongs here so it doesn't get removed in the cleanup step down below.\n\t\t\t\tvisitedEntities.add(newEntity);\n\t\t\t}\n\n\t\t\t// Ok, at this point we know what IDs we visited. If anything is left in the collection that has an ID and has not been visited\n\t\t\t// it needs to be removed from the collection, because this is the canonical list of everything that's in the collection now.\n\t\t\t// ------------\n\t\t\t// \u2757\uD83D\uDC3B WARNING BEAR TRAP \uD83D\uDC3B\u2757: If you're looking at this going, \"But I just want to pass in the items I want to update and for it not to\n\t\t\t// mess with the rest of the collection\", this is here because without this behaviour, there's no way to remove items from\n\t\t\t// Many to many properties. Consider the case of tags on an entity, when we pass ['a', 'b', 'c'] as the list of tags, that\n\t\t\t// means we need to remove anything that isn't 'a', 'b', or 'c' because it's not in the array.\n\t\t\tentityPropertyValue.remove(\n\t\t\t\t...entityPropertyValue.getItems().filter((entity) => !visitedEntities.has(entity))\n\t\t\t);\n\t\t} else if (\n\t\t\tpropertyMetadata?.reference == ReferenceType.MANY_TO_ONE ||\n\t\t\tpropertyMetadata?.reference === ReferenceType.ONE_TO_ONE\n\t\t) {\n\t\t\tif (value === null) {\n\t\t\t\t// If the value is null, unset the reference\n\t\t\t\t(entity as any)[property] = null;\n\t\t\t} else {\n\t\t\t\tconst valueKeys = Object.keys(value as any);\n\t\t\t\tif (valueKeys.length === 1 && valueKeys[0] === 'id') {\n\t\t\t\t\t// Ok, this is just the ID, set the reference and move on.\n\t\t\t\t\t(entity as any)[property] = em.getReference(propertyMetadata.type, (value as any).id);\n\t\t\t\t} else {\n\t\t\t\t\tif (entityPropertyValue && !Reference.isReference(entityPropertyValue)) {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t`Trying to merge to related property ${property} on entity ${metadata.name} which is not a reference.`\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (entityPropertyValue && !entityPropertyValue.isInitialized()) {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t`Trying to merge to related property ${property} on entity ${metadata.name} which is not initialised.`\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\n\t\t\t\t\tconst newEntity = await createOrAssignEntity<T>({\n\t\t\t\t\t\tentity: entityPropertyValue?.unwrap() as T,\n\t\t\t\t\t\tentityType: propertyMetadata.type,\n\t\t\t\t\t\tdata: value as EntityData<T>,\n\t\t\t\t\t\toptions,\n\t\t\t\t\t\tvisited,\n\t\t\t\t\t\tem,\n\t\t\t\t\t});\n\n\t\t\t\t\t(entity as any)[property] = Reference.create(newEntity);\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\t// Ok, we're a simple scalar.\n\t\t\t(entity as any)[property] = value;\n\t\t}\n\t}\n\n\treturn entity;\n};\n\nconst createOrAssignEntity = <T extends AnyEntity<T>>({\n\tentity,\n\tentityType,\n\tdata,\n\toptions,\n\tvisited,\n\tem,\n}: {\n\tentity?: T;\n\tentityType: string;\n\tdata: EntityData<T>;\n\toptions?: AssignOptions;\n\tvisited: Set<AnyEntity<any>>;\n\tem: EntityManager;\n}) => {\n\tconst create = options?.create ?? true;\n\tconst update = options?.update ?? true;\n\n\tif ((data as any).id) {\n\t\tif (!update) {\n\t\t\tthrow new Error(\n\t\t\t\t`Updates are disabled, but update value ${JSON.stringify(\n\t\t\t\t\tdata\n\t\t\t\t)} was passed which has an ID property.`\n\t\t\t);\n\t\t}\n\n\t\tif (!entity) {\n\t\t\tthrow new Error(\n\t\t\t\t`Tried to update with data ${JSON.stringify(\n\t\t\t\t\tdata\n\t\t\t\t)} but entity could not be located to update.`\n\t\t\t);\n\t\t}\n\n\t\t// Ok, we need to recurse here.\n\t\treturn assign(entity, data, options, visited);\n\t} else {\n\t\tif (!create) {\n\t\t\tthrow new Error(\n\t\t\t\t`Creates are disabled, but update value ${JSON.stringify(\n\t\t\t\t\tdata\n\t\t\t\t)} was passed which does not have an ID property.`\n\t\t\t);\n\t\t}\n\n\t\t// We don't want Mikro to manage the data merging here, we'll do it in the next line.\n\t\tconst entity = em.create<T>(entityType, {} as any);\n\t\treturn assign(entity, data, options, visited);\n\t}\n};\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,kBAUO;AACP,oBAAuB;AAEvB,sBAAkC;AAiB3B,MAAM,SAAS,OACrB,QACA,MACA,SACA,UAAU,oBAAI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uBAAuB,CAAyB;AAAA,EACrD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACD,MAOM;AAlMN;AAmMC,QAAM,UAAS,wCAAS,WAAT,YAAmB;AAClC,QAAM,UAAS,wCAAS,WAAT,YAAmB;AAElC,MAAK,KAAa,IAAI;AACrB,QAAI,CAAC,QAAQ;AACZ,YAAM,IAAI;AAAA,QACT,0CAA0C,KAAK;AAAA,UAC9C;AAAA,QACD;AAAA,MACD;AAAA,IACD;AAEA,QAAI,CAAC,QAAQ;AACZ,YAAM,IAAI;AAAA,QACT,6BAA6B,KAAK;AAAA,UACjC;AAAA,QACD;AAAA,MACD;AAAA,IACD;AAGA,WAAO,OAAO,QAAQ,MAAM,SAAS,OAAO;AAAA,EAC7C,OAAO;AACN,QAAI,CAAC,QAAQ;AACZ,YAAM,IAAI;AAAA,QACT,0CAA0C,KAAK;AAAA,UAC9C;AAAA,QACD;AAAA,MACD;AAAA,IACD;AAGA,UAAMA,UAAS,GAAG,OAAU,YAAY,CAAC,CAAQ;AACjD,WAAO,OAAOA,SAAQ,MAAM,SAAS,OAAO;AAAA,EAC7C;AACD;",
6
+ "names": ["entity"]
7
+ }
@@ -16,3 +16,4 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
16
16
  var base_resolver_exports = {};
17
17
  module.exports = __toCommonJS(base_resolver_exports);
18
18
  __reExport(base_resolver_exports, require("./provider"), module.exports);
19
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/base-resolver/index.ts"],
4
+ "sourcesContent": ["export * from './provider';\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;AAAA;AAAA;AAAA,kCAAc,uBAAd;",
6
+ "names": []
7
+ }
@@ -1,28 +1,36 @@
1
- import { BackendProvider, PaginationOptions } from '@exogee/graphweaver';
2
- export declare const visitPathForPopulate: (entityName: string, updateArgBranch: any, populateBranch?: string) => Set<string>;
1
+ import { BackendProvider, PaginationOptions, Filter, GraphQLEntity, BaseDataEntity } from '@exogee/graphweaver';
2
+ import { IsolationLevel } from '..';
3
3
  export declare const gqlToMikro: (filter: any) => any;
4
- export declare const mapAndAssignKeys: <T>(result: T, entityType: new () => T, inputArgs: Partial<T>) => Promise<T>;
5
- export declare class MikroBackendProvider<T extends {}> implements BackendProvider<T> {
6
- readonly backendId = "mikro-orm";
7
- entityType: new () => T;
4
+ export declare class MikroBackendProvider<D extends BaseDataEntity, G extends GraphQLEntity<D>> implements BackendProvider<D, G> {
5
+ private _backendId;
6
+ entityType: new () => D;
7
+ connectionManagerId?: string;
8
+ private transactionIsolationLevel;
8
9
  readonly supportsInFilter = true;
10
+ get backendId(): string;
11
+ private get database();
12
+ get transactional(): <T>(callback: () => Promise<T>, isolationLevel?: IsolationLevel) => Promise<T>;
13
+ withTransaction<T>(callback: () => Promise<T>): Promise<T>;
14
+ get em(): import("@mikro-orm/postgresql").EntityManager<import("@mikro-orm/postgresql").PostgreSqlDriver>;
9
15
  private getRepository;
10
- constructor(mikroType: new () => T);
16
+ constructor(mikroType: new () => D, connectionManagerId?: string, transactionIsolationLevel?: IsolationLevel);
17
+ private mapAndAssignKeys;
18
+ private applyExternalIdFields;
19
+ visitPathForPopulate: (entityName: string, updateArgBranch: any, populateBranch?: string) => Set<string>;
11
20
  private applyWhereClause;
12
- find(filter: any, // @todo: Create a type for this
13
- pagination?: PaginationOptions, additionalOptionsForBackend?: any): Promise<T[]>;
14
- findOne(id: string): Promise<T | null>;
15
- findByRelatedId(entity: any, relatedField: string, relatedFieldIds: string[], filter?: any): Promise<T[]>;
16
- updateOne(id: string, updateArgs: Partial<T & {
21
+ find(filter: Filter<G>, pagination?: PaginationOptions, additionalOptionsForBackend?: any): Promise<D[]>;
22
+ findOne(filter: Filter<G>): Promise<D | null>;
23
+ findByRelatedId(entity: any, relatedField: string, relatedFieldIds: string[], filter?: any): Promise<D[]>;
24
+ updateOne(id: string, updateArgs: Partial<G & {
17
25
  version?: number;
18
- }>): Promise<T>;
19
- updateMany(updateItems: (Partial<T> & {
26
+ }>): Promise<D>;
27
+ updateMany(updateItems: (Partial<G> & {
20
28
  id: string;
21
- })[]): Promise<T[]>;
22
- createOrUpdateMany(items: Partial<T>[]): Promise<T[]>;
23
- createOne(createArgs: Partial<T>): Promise<T>;
24
- createMany(createItems: Partial<T>[]): Promise<T[]>;
25
- deleteOne(id: string): Promise<boolean>;
29
+ })[]): Promise<D[]>;
30
+ createOrUpdateMany(items: Partial<G>[]): Promise<D[]>;
31
+ createOne(createArgs: Partial<G>): Promise<D>;
32
+ createMany(createItems: Partial<G>[]): Promise<D[]>;
33
+ deleteOne(filter: Filter<G>): Promise<boolean>;
26
34
  deleteMany(ids: string[]): Promise<boolean>;
27
35
  getRelatedEntityId(entity: any, relatedIdField: string): any;
28
36
  isCollection(entity: any): boolean;
@@ -19,11 +19,10 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
19
19
  var provider_exports = {};
20
20
  __export(provider_exports, {
21
21
  MikroBackendProvider: () => MikroBackendProvider,
22
- gqlToMikro: () => gqlToMikro,
23
- mapAndAssignKeys: () => mapAndAssignKeys,
24
- visitPathForPopulate: () => visitPathForPopulate
22
+ gqlToMikro: () => gqlToMikro
25
23
  });
26
24
  module.exports = __toCommonJS(provider_exports);
25
+ var import_graphweaver = require("@exogee/graphweaver");
27
26
  var import_logger = require("@exogee/logger");
28
27
  var import__ = require("..");
29
28
  var import_errors = require("../utils/errors");
@@ -48,34 +47,6 @@ const nonJoinKeys = /* @__PURE__ */ new Set([
48
47
  "id"
49
48
  ]);
50
49
  const appendPath = (path, newPath) => path.length ? `${path}.${newPath}` : newPath;
51
- const visitPathForPopulate = (entityName, updateArgBranch, populateBranch = "") => {
52
- var _a, _b, _c, _d;
53
- const { properties } = import__.Database.em.getMetadata().get(entityName);
54
- const collectedPaths = populateBranch ? /* @__PURE__ */ new Set([populateBranch]) : /* @__PURE__ */ new Set([]);
55
- for (const [key, value] of Object.entries(updateArgBranch != null ? updateArgBranch : {})) {
56
- if (((_a = properties[key]) == null ? void 0 : _a.reference) === import__.ReferenceType.ONE_TO_ONE || ((_b = properties[key]) == null ? void 0 : _b.reference) === import__.ReferenceType.ONE_TO_MANY || ((_c = properties[key]) == null ? void 0 : _c.reference) === import__.ReferenceType.MANY_TO_ONE || ((_d = properties[key]) == null ? void 0 : _d.reference) === import__.ReferenceType.MANY_TO_MANY) {
57
- if (Array.isArray(value)) {
58
- collectedPaths.add(appendPath(populateBranch, key));
59
- for (const entry of value) {
60
- const newPaths = visitPathForPopulate(
61
- properties[key].type,
62
- entry,
63
- appendPath(populateBranch, key)
64
- );
65
- newPaths.forEach((path) => collectedPaths.add(path));
66
- }
67
- } else if (typeof value === "object") {
68
- const newPaths = visitPathForPopulate(
69
- properties[key].type,
70
- value,
71
- appendPath(populateBranch, key)
72
- );
73
- newPaths.forEach((path) => collectedPaths.add(path));
74
- }
75
- }
76
- }
77
- return collectedPaths;
78
- };
79
50
  const gqlToMikro = (filter) => {
80
51
  if (Array.isArray(filter)) {
81
52
  return filter.map((element) => gqlToMikro(element));
@@ -102,21 +73,108 @@ const gqlToMikro = (filter) => {
102
73
  }
103
74
  return filter;
104
75
  };
105
- const mapAndAssignKeys = (result, entityType, inputArgs) => {
106
- const cleanInput = JSON.parse(JSON.stringify(inputArgs));
107
- return (0, import_assign.assign)(result, cleanInput);
108
- };
109
76
  class MikroBackendProvider {
110
- constructor(mikroType) {
111
- this.backendId = "mikro-orm";
77
+ constructor(mikroType, connectionManagerId, transactionIsolationLevel = import__.IsolationLevel.REPEATABLE_READ) {
112
78
  this.supportsInFilter = true;
113
79
  this.getRepository = () => {
114
- const repository = import__.Database.em.getRepository(this.entityType);
80
+ const repository = this.database.em.getRepository(this.entityType);
115
81
  if (!repository)
116
82
  throw new Error("Could not find repository for " + this.entityType.name);
117
83
  return repository;
118
84
  };
85
+ this.mapAndAssignKeys = (result, entityType, inputArgs) => {
86
+ const assignmentObj = this.applyExternalIdFields(entityType, inputArgs);
87
+ return (0, import_assign.assign)(result, assignmentObj, void 0, void 0, this.database.em);
88
+ };
89
+ this.applyExternalIdFields = (target, values) => {
90
+ const targetName = typeof target === "string" ? target : target.name;
91
+ const map = import__.externalIdFieldMap.get(targetName);
92
+ const mapFieldNames = (partialFilterObj) => {
93
+ for (const [from, to] of Object.entries(map || {})) {
94
+ if (partialFilterObj[from] && typeof partialFilterObj[from].id !== "undefined") {
95
+ if (Object.keys(partialFilterObj[from]).length > 1) {
96
+ throw new Error(
97
+ `Expected precisely 1 key called 'id' in queryObj.${from} on ${target}, got ${JSON.stringify(
98
+ partialFilterObj[from],
99
+ null,
100
+ 4
101
+ )}`
102
+ );
103
+ }
104
+ partialFilterObj[to] = partialFilterObj[from].id;
105
+ delete partialFilterObj[from];
106
+ }
107
+ }
108
+ };
109
+ for (const rootLevelKey of Object.keys(values)) {
110
+ if (mikroObjectOperations.has(rootLevelKey)) {
111
+ for (const field of values[rootLevelKey]) {
112
+ mapFieldNames(field);
113
+ }
114
+ }
115
+ }
116
+ mapFieldNames(values);
117
+ const { properties } = this.database.em.getMetadata().get(targetName);
118
+ Object.values(properties).filter((property) => typeof property.entity !== "undefined" && values[property.name]).forEach((property) => {
119
+ if (Array.isArray(values[property.name])) {
120
+ values[property.name].forEach(
121
+ (value) => this.applyExternalIdFields(property.type, value)
122
+ );
123
+ } else {
124
+ values[property.name] = this.applyExternalIdFields(property.type, values[property.name]);
125
+ }
126
+ });
127
+ return values;
128
+ };
129
+ this.visitPathForPopulate = (entityName, updateArgBranch, populateBranch = "") => {
130
+ var _a, _b, _c, _d;
131
+ const { properties } = this.database.em.getMetadata().get(entityName);
132
+ const collectedPaths = populateBranch ? /* @__PURE__ */ new Set([populateBranch]) : /* @__PURE__ */ new Set([]);
133
+ for (const [key, value] of Object.entries(updateArgBranch != null ? updateArgBranch : {})) {
134
+ if (((_a = properties[key]) == null ? void 0 : _a.reference) === import__.ReferenceType.ONE_TO_ONE || ((_b = properties[key]) == null ? void 0 : _b.reference) === import__.ReferenceType.ONE_TO_MANY || ((_c = properties[key]) == null ? void 0 : _c.reference) === import__.ReferenceType.MANY_TO_ONE || ((_d = properties[key]) == null ? void 0 : _d.reference) === import__.ReferenceType.MANY_TO_MANY) {
135
+ if (Array.isArray(value)) {
136
+ collectedPaths.add(appendPath(populateBranch, key));
137
+ for (const entry of value) {
138
+ const newPaths = this.visitPathForPopulate(
139
+ properties[key].type,
140
+ entry,
141
+ appendPath(populateBranch, key)
142
+ );
143
+ newPaths.forEach((path) => collectedPaths.add(path));
144
+ }
145
+ } else if (typeof value === "object") {
146
+ const newPaths = this.visitPathForPopulate(
147
+ properties[key].type,
148
+ value,
149
+ appendPath(populateBranch, key)
150
+ );
151
+ newPaths.forEach((path) => collectedPaths.add(path));
152
+ }
153
+ }
154
+ }
155
+ return collectedPaths;
156
+ };
119
157
  this.entityType = mikroType;
158
+ this.connectionManagerId = connectionManagerId;
159
+ this._backendId = `mikro-orm-${connectionManagerId || ""}`;
160
+ this.transactionIsolationLevel = transactionIsolationLevel;
161
+ }
162
+ get backendId() {
163
+ return this._backendId;
164
+ }
165
+ get database() {
166
+ if (!this.connectionManagerId)
167
+ return import__.ConnectionManager.default;
168
+ return import__.ConnectionManager.database(this.connectionManagerId) || import__.ConnectionManager.default;
169
+ }
170
+ get transactional() {
171
+ return this.database.transactional;
172
+ }
173
+ async withTransaction(callback) {
174
+ return this.database.transactional(callback, this.transactionIsolationLevel);
175
+ }
176
+ get em() {
177
+ return this.database.em;
120
178
  }
121
179
  applyWhereClause(where) {
122
180
  const query = this.getRepository().createQueryBuilder();
@@ -158,13 +216,14 @@ class MikroBackendProvider {
158
216
  filter: JSON.stringify(filter)
159
217
  });
160
218
  const where = filter ? gqlToMikro(JSON.parse(JSON.stringify(filter))) : void 0;
161
- const query = this.applyWhereClause(where);
219
+ const whereWithAppliedExternalIdFields = where && this.applyExternalIdFields(this.entityType, where);
220
+ const query = this.applyWhereClause(whereWithAppliedExternalIdFields);
162
221
  (pagination == null ? void 0 : pagination.limit) && query.limit(pagination.limit);
163
222
  (pagination == null ? void 0 : pagination.offset) && query.offset(pagination.offset);
164
223
  (pagination == null ? void 0 : pagination.orderBy) && query.orderBy({ ...pagination.orderBy });
165
224
  query.setFlag(import__.QueryFlag.DISTINCT);
166
- const driver = import__.Database.em.getDriver();
167
- const meta = import__.Database.em.getMetadata().get(this.entityType.name);
225
+ const driver = this.database.em.getDriver();
226
+ const meta = this.database.em.getMetadata().get(this.entityType.name);
168
227
  query.populate(driver.autoJoinOneToOneOwner(meta, []));
169
228
  if (additionalOptionsForBackend == null ? void 0 : additionalOptionsForBackend.populate) {
170
229
  query.populate(additionalOptionsForBackend.populate);
@@ -173,9 +232,9 @@ class MikroBackendProvider {
173
232
  import_logger.logger.trace(`find ${this.entityType.name} result: ${result.length} rows`);
174
233
  return result;
175
234
  }
176
- async findOne(id) {
177
- import_logger.logger.trace(`Running findOne ${this.entityType.name} with ID ${id}`);
178
- const result = await import__.Database.em.findOne(this.entityType, id);
235
+ async findOne(filter) {
236
+ import_logger.logger.trace(`Running findOne ${this.entityType.name} with filter ${filter}`);
237
+ const [result] = await this.find(filter, { orderBy: { id: import_graphweaver.Sort.DESC }, offset: 0, limit: 1 });
179
238
  import_logger.logger.trace(`findOne ${this.entityType.name} result`, { result });
180
239
  return result;
181
240
  }
@@ -184,7 +243,9 @@ class MikroBackendProvider {
184
243
  $and: [{ [relatedField]: { $in: relatedFieldIds } }, ...[filter != null ? filter : []]]
185
244
  };
186
245
  const populate = [relatedField];
187
- const result = await import__.Database.em.find(entity, queryFilter, { populate });
246
+ const result = await this.database.em.find(entity, queryFilter, {
247
+ populate
248
+ });
188
249
  return result;
189
250
  }
190
251
  async updateOne(id, updateArgs) {
@@ -192,21 +253,21 @@ class MikroBackendProvider {
192
253
  id,
193
254
  updateArgs: JSON.stringify(updateArgs)
194
255
  });
195
- const entity = await import__.Database.em.findOne(this.entityType, id, {
196
- populate: [...visitPathForPopulate(this.entityType.name, updateArgs)]
256
+ const entity = await this.database.em.findOne(this.entityType, id, {
257
+ populate: [...this.visitPathForPopulate(this.entityType.name, updateArgs)]
197
258
  });
198
259
  if (entity === null) {
199
260
  throw new Error(`Unable to locate ${this.entityType.name} with ID: '${id}' for updating.`);
200
261
  }
201
262
  if (updateArgs == null ? void 0 : updateArgs.version) {
202
263
  try {
203
- await import__.Database.em.lock(entity, import__.LockMode.OPTIMISTIC, updateArgs.version);
264
+ await this.database.em.lock(entity, import__.LockMode.OPTIMISTIC, updateArgs.version);
204
265
  delete updateArgs.version;
205
266
  } catch (err) {
206
267
  throw new import_errors.OptimisticLockError(err == null ? void 0 : err.message, { entity });
207
268
  }
208
269
  }
209
- await mapAndAssignKeys(entity, this.entityType, updateArgs);
270
+ await this.mapAndAssignKeys(entity, this.entityType, updateArgs);
210
271
  await this.getRepository().persistAndFlush(entity);
211
272
  import_logger.logger.trace(`update ${this.entityType.name} entity`, entity);
212
273
  return entity;
@@ -215,16 +276,16 @@ class MikroBackendProvider {
215
276
  import_logger.logger.trace(`Running update many ${this.entityType.name} with args`, {
216
277
  updateItems: JSON.stringify(updateItems)
217
278
  });
218
- const entities = await import__.Database.transactional(async () => {
279
+ const entities = await this.database.transactional(async () => {
219
280
  return Promise.all(
220
281
  updateItems.map(async (item) => {
221
282
  if (!(item == null ? void 0 : item.id))
222
283
  throw new Error("You must pass an ID for this entity to update it.");
223
- const entity = await import__.Database.em.findOneOrFail(this.entityType, item.id, {
224
- populate: [...visitPathForPopulate(this.entityType.name, item)]
284
+ const entity = await this.database.em.findOneOrFail(this.entityType, item.id, {
285
+ populate: [...this.visitPathForPopulate(this.entityType.name, item)]
225
286
  });
226
- await mapAndAssignKeys(entity, this.entityType, item);
227
- import__.Database.em.persist(entity);
287
+ await this.mapAndAssignKeys(entity, this.entityType, item);
288
+ this.database.em.persist(entity);
228
289
  return entity;
229
290
  })
230
291
  );
@@ -236,27 +297,29 @@ class MikroBackendProvider {
236
297
  import_logger.logger.trace(`Running create or update many for ${this.entityType.name} with args`, {
237
298
  items: JSON.stringify(items)
238
299
  });
239
- const entities = await import__.Database.transactional(async () => {
300
+ const entities = await this.database.transactional(async () => {
240
301
  return Promise.all(
241
302
  items.map(async (item) => {
242
303
  let entity;
243
304
  const { id } = item;
244
305
  if (id) {
245
- entity = await import__.Database.em.findOneOrFail(this.entityType, id, {
246
- populate: [...visitPathForPopulate(this.entityType.name, item)]
306
+ entity = await this.database.em.findOneOrFail(this.entityType, id, {
307
+ populate: [
308
+ ...this.visitPathForPopulate(this.entityType.name, item)
309
+ ]
247
310
  });
248
311
  import_logger.logger.trace(`Running update on ${this.entityType.name} with item`, {
249
312
  item: JSON.stringify(item)
250
313
  });
251
- await mapAndAssignKeys(entity, this.entityType, item);
314
+ await this.mapAndAssignKeys(entity, this.entityType, item);
252
315
  } else {
253
316
  entity = new this.entityType();
254
- await mapAndAssignKeys(entity, this.entityType, item);
317
+ await this.mapAndAssignKeys(entity, this.entityType, item);
255
318
  import_logger.logger.trace(`Running create on ${this.entityType.name} with item`, {
256
319
  item: JSON.stringify(item)
257
320
  });
258
321
  }
259
- import__.Database.em.persist(entity);
322
+ this.database.em.persist(entity);
260
323
  return entity;
261
324
  })
262
325
  );
@@ -269,7 +332,7 @@ class MikroBackendProvider {
269
332
  createArgs: JSON.stringify(createArgs)
270
333
  });
271
334
  const entity = new this.entityType();
272
- await mapAndAssignKeys(entity, this.entityType, createArgs);
335
+ await this.mapAndAssignKeys(entity, this.entityType, createArgs);
273
336
  await this.getRepository().persistAndFlush(entity);
274
337
  import_logger.logger.trace(`create ${this.entityType.name} result`, entity);
275
338
  return entity;
@@ -278,12 +341,12 @@ class MikroBackendProvider {
278
341
  import_logger.logger.trace(`Running create ${this.entityType.name} with args`, {
279
342
  createArgs: JSON.stringify(createItems)
280
343
  });
281
- const entities = await import__.Database.transactional(async () => {
344
+ const entities = await this.database.transactional(async () => {
282
345
  return Promise.all(
283
346
  createItems.map(async (item) => {
284
347
  const entity = new this.entityType();
285
- await mapAndAssignKeys(entity, this.entityType, item);
286
- import__.Database.em.persist(entity);
348
+ await this.mapAndAssignKeys(entity, this.entityType, item);
349
+ this.database.em.persist(entity);
287
350
  return entity;
288
351
  })
289
352
  );
@@ -291,11 +354,11 @@ class MikroBackendProvider {
291
354
  import_logger.logger.trace(`created ${this.entityType.name} items `, entities);
292
355
  return entities;
293
356
  }
294
- async deleteOne(id) {
295
- import_logger.logger.trace(`Running delete ${this.entityType.name} with id ${id}`);
296
- const deletedRows = await this.getRepository().nativeDelete({
297
- id
298
- });
357
+ async deleteOne(filter) {
358
+ import_logger.logger.trace(`Running delete ${this.entityType.name} with filter ${filter}`);
359
+ const where = filter ? gqlToMikro(JSON.parse(JSON.stringify(filter))) : void 0;
360
+ const whereWithAppliedExternalIdFields = where && this.applyExternalIdFields(this.entityType, where);
361
+ const deletedRows = await this.getRepository().nativeDelete(whereWithAppliedExternalIdFields);
299
362
  if (deletedRows > 1) {
300
363
  throw new Error("Multiple deleted rows");
301
364
  }
@@ -304,7 +367,7 @@ class MikroBackendProvider {
304
367
  }
305
368
  async deleteMany(ids) {
306
369
  import_logger.logger.trace(`Running delete ${this.entityType.name} with ids ${ids}`);
307
- const deletedRows = await import__.Database.transactional(async () => {
370
+ const deletedRows = await this.database.transactional(async () => {
308
371
  const deletedCount = await this.getRepository().nativeDelete({
309
372
  id: { $in: ids }
310
373
  });
@@ -332,7 +395,6 @@ class MikroBackendProvider {
332
395
  // Annotate the CommonJS export names for ESM import in node:
333
396
  0 && (module.exports = {
334
397
  MikroBackendProvider,
335
- gqlToMikro,
336
- mapAndAssignKeys,
337
- visitPathForPopulate
398
+ gqlToMikro
338
399
  });
400
+ //# sourceMappingURL=provider.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/base-resolver/provider.ts"],
4
+ "sourcesContent": ["import {\n\tBackendProvider,\n\tPaginationOptions,\n\tSort,\n\tFilter,\n\tGraphQLEntity,\n\tBaseDataEntity,\n} from '@exogee/graphweaver';\nimport { logger } from '@exogee/logger';\n\nimport {\n\tFilterQuery,\n\tLockMode,\n\tQueryFlag,\n\tReferenceType,\n\tSqlEntityRepository,\n\tUtils,\n\tConnectionManager,\n\texternalIdFieldMap,\n\tAnyEntity,\n\tIsolationLevel,\n} from '..';\nimport { OptimisticLockError } from '../utils/errors';\nimport { assign } from './assign';\n\nconst objectOperations = new Set(['_and', '_or', '_not']);\nconst mikroObjectOperations = new Set(['$and', '$or', '$not']);\nconst nonJoinKeys = new Set([\n\t'$and',\n\t'$gt',\n\t'$gte',\n\t'$in',\n\t'$lt',\n\t'$lte',\n\t'$ne',\n\t'$nin',\n\t'$not',\n\t'$or',\n\t'$like',\n\t'$ilike',\n\t'$null',\n\t'$notnull',\n\t'id', // @todo: remove this? Why is it here?\n]);\n\nconst appendPath = (path: string, newPath: string) =>\n\tpath.length ? `${path}.${newPath}` : newPath;\n\nexport const gqlToMikro: (filter: any) => any = (filter: any) => {\n\tif (Array.isArray(filter)) {\n\t\treturn filter.map((element) => gqlToMikro(element));\n\t} else if (typeof filter === 'object') {\n\t\tfor (const key of Object.keys(filter)) {\n\t\t\t// A null here is a user-specified value and is valid to filter on\n\t\t\tif (filter[key] === null) continue;\n\n\t\t\tif (objectOperations.has(key)) {\n\t\t\t\t// { _not: '1' } => { $not: '1' }\n\t\t\t\tfilter[key.replace('_', '$')] = gqlToMikro(filter[key]);\n\t\t\t\tdelete filter[key];\n\t\t\t} else if (typeof filter[key] === 'object' && !Array.isArray(filter[key])) {\n\t\t\t\t// Recurse over nested filters only (arrays are an argument to a filter, not a nested filter)\n\t\t\t\tfilter[key] = gqlToMikro(filter[key]);\n\t\t\t} else if (key.indexOf('_') >= 0) {\n\t\t\t\t// { firstName_in: ['k', 'b'] } => { firstName: { $in: ['k', 'b'] } }\n\t\t\t\tconst [newKey, operator] = key.split('_');\n\t\t\t\tconst newValue = { [`$${operator}`]: gqlToMikro(filter[key]) };\n\n\t\t\t\t// They can construct multiple filters for the same key. In that case we need\n\t\t\t\t// to append them all into an object.\n\t\t\t\tif (typeof filter[newKey] !== 'undefined') {\n\t\t\t\t\tfilter[newKey] = { ...filter[newKey], ...newValue };\n\t\t\t\t} else {\n\t\t\t\t\tfilter[newKey] = newValue;\n\t\t\t\t}\n\n\t\t\t\tdelete filter[key];\n\t\t\t}\n\t\t}\n\t}\n\treturn filter;\n};\n\n// eslint-disable-next-line @typescript-eslint/ban-types\nexport class MikroBackendProvider<D extends BaseDataEntity, G extends GraphQLEntity<D>>\n\timplements BackendProvider<D, G>\n{\n\tprivate _backendId: string;\n\n\tpublic entityType: new () => D;\n\tpublic connectionManagerId?: string;\n\tprivate transactionIsolationLevel!: IsolationLevel;\n\n\tpublic readonly supportsInFilter = true;\n\n\tget backendId() {\n\t\treturn this._backendId;\n\t}\n\n\tprivate get database() {\n\t\t// If we have a connection manager ID then use that else fallback to the Database\n\t\tif (!this.connectionManagerId) return ConnectionManager.default;\n\t\treturn ConnectionManager.database(this.connectionManagerId) || ConnectionManager.default;\n\t}\n\n\t// This is exposed for use in the RLS package\n\tpublic get transactional() {\n\t\treturn this.database.transactional;\n\t}\n\n\tpublic async withTransaction<T>(callback: () => Promise<T>) {\n\t\treturn this.database.transactional<T>(callback, this.transactionIsolationLevel);\n\t}\n\n\t// This is exposed for use in the RLS package\n\tpublic get em() {\n\t\treturn this.database.em;\n\t}\n\n\tprivate getRepository: () => SqlEntityRepository<D> = () => {\n\t\tconst repository = this.database.em.getRepository<D>(this.entityType);\n\t\tif (!repository) throw new Error('Could not find repository for ' + this.entityType.name);\n\n\t\treturn repository as SqlEntityRepository<D>;\n\t};\n\n\tpublic constructor(\n\t\tmikroType: new () => D,\n\t\tconnectionManagerId?: string,\n\t\ttransactionIsolationLevel: IsolationLevel = IsolationLevel.REPEATABLE_READ\n\t) {\n\t\tthis.entityType = mikroType;\n\t\tthis.connectionManagerId = connectionManagerId;\n\t\tthis._backendId = `mikro-orm-${connectionManagerId || ''}`;\n\t\tthis.transactionIsolationLevel = transactionIsolationLevel;\n\t}\n\n\tprivate mapAndAssignKeys = (result: D, entityType: new () => D, inputArgs: Partial<G>) => {\n\t\t// Clean the input and remove any GraphQL classes from the object\n\t\t// const cleanInput = JSON.parse(JSON.stringify(inputArgs));\n\t\tconst assignmentObj = this.applyExternalIdFields(entityType, inputArgs);\n\t\treturn assign(result, assignmentObj, undefined, undefined, this.database.em);\n\t};\n\n\tprivate applyExternalIdFields = (target: AnyEntity | string, values: any) => {\n\t\tconst targetName = typeof target === 'string' ? target : target.name;\n\t\tconst map = externalIdFieldMap.get(targetName);\n\n\t\tconst mapFieldNames = (partialFilterObj: any) => {\n\t\t\tfor (const [from, to] of Object.entries(map || {})) {\n\t\t\t\tif (partialFilterObj[from] && typeof partialFilterObj[from].id !== 'undefined') {\n\t\t\t\t\tif (Object.keys(partialFilterObj[from]).length > 1) {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t`Expected precisely 1 key called 'id' in queryObj.${from} on ${target}, got ${JSON.stringify(\n\t\t\t\t\t\t\t\tpartialFilterObj[from],\n\t\t\t\t\t\t\t\tnull,\n\t\t\t\t\t\t\t\t4\n\t\t\t\t\t\t\t)}`\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\n\t\t\t\t\tpartialFilterObj[to] = partialFilterObj[from].id;\n\t\t\t\t\tdelete partialFilterObj[from];\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\n\t\t// Check for and/or/etc at the root level and handle correctly\n\t\tfor (const rootLevelKey of Object.keys(values)) {\n\t\t\tif (mikroObjectOperations.has(rootLevelKey)) {\n\t\t\t\tfor (const field of values[rootLevelKey]) {\n\t\t\t\t\tmapFieldNames(field);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// Map the rest of the field names as well\n\t\tmapFieldNames(values);\n\n\t\t// Traverse the nested entities\n\t\tconst { properties } = this.database.em.getMetadata().get(targetName);\n\t\tObject.values(properties)\n\t\t\t.filter((property) => typeof property.entity !== 'undefined' && values[property.name])\n\t\t\t.forEach((property) => {\n\t\t\t\tif (Array.isArray(values[property.name])) {\n\t\t\t\t\tvalues[property.name].forEach((value: any) =>\n\t\t\t\t\t\tthis.applyExternalIdFields(property.type, value)\n\t\t\t\t\t);\n\t\t\t\t} else {\n\t\t\t\t\tvalues[property.name] = this.applyExternalIdFields(property.type, values[property.name]);\n\t\t\t\t}\n\t\t\t});\n\n\t\treturn values;\n\t};\n\n\t// Check if we have any keys that are a collection of entities\n\tpublic visitPathForPopulate = (entityName: string, updateArgBranch: any, populateBranch = '') => {\n\t\tconst { properties } = this.database.em.getMetadata().get(entityName);\n\t\tconst collectedPaths = populateBranch ? new Set<string>([populateBranch]) : new Set<string>([]);\n\n\t\tfor (const [key, value] of Object.entries(updateArgBranch ?? {})) {\n\t\t\tif (\n\t\t\t\t// If it's a relationship, go ahead and and '.' it in, recurse.\n\t\t\t\tproperties[key]?.reference === ReferenceType.ONE_TO_ONE ||\n\t\t\t\tproperties[key]?.reference === ReferenceType.ONE_TO_MANY ||\n\t\t\t\tproperties[key]?.reference === ReferenceType.MANY_TO_ONE ||\n\t\t\t\tproperties[key]?.reference === ReferenceType.MANY_TO_MANY\n\t\t\t) {\n\t\t\t\tif (Array.isArray(value)) {\n\t\t\t\t\t// In the case where the array is empty we also need to make sure we load the collection.\n\t\t\t\t\tcollectedPaths.add(appendPath(populateBranch, key));\n\n\t\t\t\t\tfor (const entry of value) {\n\t\t\t\t\t\t// Recurse\n\t\t\t\t\t\tconst newPaths = this.visitPathForPopulate(\n\t\t\t\t\t\t\tproperties[key].type,\n\t\t\t\t\t\t\tentry,\n\t\t\t\t\t\t\tappendPath(populateBranch, key)\n\t\t\t\t\t\t);\n\t\t\t\t\t\tnewPaths.forEach((path) => collectedPaths.add(path));\n\t\t\t\t\t}\n\t\t\t\t} else if (typeof value === 'object') {\n\t\t\t\t\t// Recurse\n\t\t\t\t\tconst newPaths = this.visitPathForPopulate(\n\t\t\t\t\t\tproperties[key].type,\n\t\t\t\t\t\tvalue,\n\t\t\t\t\t\tappendPath(populateBranch, key)\n\t\t\t\t\t);\n\t\t\t\t\tnewPaths.forEach((path) => collectedPaths.add(path));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn collectedPaths;\n\t};\n\n\tprivate applyWhereClause(where: any) {\n\t\tconst query = this.getRepository().createQueryBuilder();\n\t\tconst joinKeysUsed = new Map<string, number>();\n\n\t\tif (where) {\n\t\t\tconst visit = (current: any, table = 'e0') => {\n\t\t\t\tif (Array.isArray(current)) {\n\t\t\t\t\tfor (const element of current) {\n\t\t\t\t\t\tvisit(element, table);\n\t\t\t\t\t}\n\t\t\t\t} else if (typeof current === 'object') {\n\t\t\t\t\tfor (const key of Object.keys(current)) {\n\t\t\t\t\t\tconst shouldJoin =\n\t\t\t\t\t\t\tcurrent[key] !== null &&\n\t\t\t\t\t\t\ttypeof current[key] === 'object' &&\n\t\t\t\t\t\t\tObject.keys(current[key]).filter((key) => !nonJoinKeys.has(key)).length > 0;\n\n\t\t\t\t\t\t// Only join if it's not $and, $or, $not, and if it's one of those object operations\n\t\t\t\t\t\t// pass the parent and current table on down without any change.\n\t\t\t\t\t\tif (mikroObjectOperations.has(key)) {\n\t\t\t\t\t\t\tvisit(current[key], table);\n\t\t\t\t\t\t} else if (shouldJoin) {\n\t\t\t\t\t\t\t// Otherwise ensure we've actually got a full on nested object,\n\t\t\t\t\t\t\t// not just a filter property.\n\t\t\t\t\t\t\tconst keyUseCount = joinKeysUsed.has(key) ? (joinKeysUsed.get(key) ?? 0) + 1 : 1;\n\t\t\t\t\t\t\tconst joinKey = joinKeysUsed.has(key) ? `${key}${keyUseCount}` : key;\n\t\t\t\t\t\t\tquery.leftJoin(`${table}.${key}`, joinKey);\n\t\t\t\t\t\t\t// Certain filters can result in the same table being joined\n\t\t\t\t\t\t\t// on different criteria - keep track and avoid using the same alias\n\t\t\t\t\t\t\tjoinKeysUsed.set(joinKey, keyUseCount);\n\t\t\t\t\t\t\tvisit(current[key], key);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Filter out empty objects\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\tcurrent[key] !== null &&\n\t\t\t\t\t\t\ttypeof current[key] === 'object' &&\n\t\t\t\t\t\t\tObject.keys(current[key]).length === 0\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tdelete current[key];\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tvisit(where);\n\n\t\t\tif (Object.keys(where).length > 0) {\n\t\t\t\tquery.andWhere(where);\n\t\t\t}\n\t\t}\n\n\t\treturn query;\n\t}\n\n\tpublic async find(\n\t\tfilter: Filter<G>,\n\t\tpagination?: PaginationOptions,\n\t\tadditionalOptionsForBackend?: any // @todo: Create a type for this\n\t): Promise<D[]> {\n\t\tlogger.trace(`Running find ${this.entityType.name} with filter`, {\n\t\t\tfilter: JSON.stringify(filter),\n\t\t});\n\n\t\t// Strip custom types out of the equation.\n\t\t// This query only works if we JSON.parse(JSON.stringify(filter)):\n\t\t//\n\t\t// query {\n\t\t// drivers (filter: { region: { name: \"North Shore\" }}) {\n\t\t// id\n\t\t// }\n\t\t// }\n\t\tconst where = filter ? gqlToMikro(JSON.parse(JSON.stringify(filter))) : undefined;\n\n\t\t// Convert from: { account: {id: '6' }}\n\t\t// to { accountId: '6' }\n\t\t// This conversion only works on root level objects\n\t\tconst whereWithAppliedExternalIdFields =\n\t\t\twhere && this.applyExternalIdFields(this.entityType, where);\n\n\t\t// Regions need some fancy handling with Query Builder. Process the where further\n\t\t// and return a Query Builder instance.\n\t\tconst query = this.applyWhereClause(whereWithAppliedExternalIdFields);\n\n\t\t// If we have specified a limit, offset or order then update the query\n\t\tpagination?.limit && query.limit(pagination.limit);\n\t\tpagination?.offset && query.offset(pagination.offset);\n\t\tpagination?.orderBy && query.orderBy({ ...pagination.orderBy });\n\n\t\t// Certain query filters can result in duplicate records once all joins are resolved\n\t\t// These duplicates can be discarded as related entities are returned to the\n\t\t// API consumer via field resolvers\n\t\tquery.setFlag(QueryFlag.DISTINCT);\n\n\t\t// 1:1 relations that aren't on the owning side need to get populated so the references get set.\n\t\t// This method is protected, but we need to use it from here, hence the `as any`.\n\t\tconst driver = this.database.em.getDriver();\n\t\tconst meta = this.database.em.getMetadata().get(this.entityType.name);\n\t\tquery.populate((driver as any).autoJoinOneToOneOwner(meta, []));\n\n\t\tif (additionalOptionsForBackend?.populate) {\n\t\t\tquery.populate(additionalOptionsForBackend.populate);\n\t\t}\n\n\t\tconst result = await query.getResult();\n\t\tlogger.trace(`find ${this.entityType.name} result: ${result.length} rows`);\n\n\t\treturn result;\n\t}\n\n\tpublic async findOne(filter: Filter<G>): Promise<D | null> {\n\t\tlogger.trace(`Running findOne ${this.entityType.name} with filter ${filter}`);\n\n\t\tconst [result] = await this.find(filter, { orderBy: { id: Sort.DESC }, offset: 0, limit: 1 });\n\n\t\tlogger.trace(`findOne ${this.entityType.name} result`, { result });\n\n\t\treturn result;\n\t}\n\n\tpublic async findByRelatedId(\n\t\tentity: any,\n\t\trelatedField: string,\n\t\trelatedFieldIds: string[],\n\t\tfilter?: any\n\t): Promise<D[]> {\n\t\tconst queryFilter = {\n\t\t\t$and: [{ [relatedField]: { $in: relatedFieldIds } }, ...[filter ?? []]],\n\t\t};\n\n\t\tconst populate = [relatedField as `${string}.`];\n\t\tconst result = await this.database.em.find(entity, queryFilter, {\n\t\t\tpopulate,\n\t\t});\n\n\t\treturn result as D[];\n\t}\n\n\tpublic async updateOne(id: string, updateArgs: Partial<G & { version?: number }>): Promise<D> {\n\t\tlogger.trace(`Running update ${this.entityType.name} with args`, {\n\t\t\tid,\n\t\t\tupdateArgs: JSON.stringify(updateArgs),\n\t\t});\n\n\t\tconst entity = await this.database.em.findOne(this.entityType, id, {\n\t\t\t// This is an optimisation so that assign() doesn't have to go fetch everything one at a time.\n\t\t\tpopulate: [...this.visitPathForPopulate(this.entityType.name, updateArgs)] as `${string}.`[],\n\t\t});\n\n\t\tif (entity === null) {\n\t\t\tthrow new Error(`Unable to locate ${this.entityType.name} with ID: '${id}' for updating.`);\n\t\t}\n\n\t\t// If a version has been sent, let's check it\n\t\tif (updateArgs?.version) {\n\t\t\ttry {\n\t\t\t\tawait this.database.em.lock(entity, LockMode.OPTIMISTIC, updateArgs.version);\n\t\t\t\tdelete updateArgs.version;\n\t\t\t} catch (err) {\n\t\t\t\tthrow new OptimisticLockError((err as Error)?.message, { entity });\n\t\t\t}\n\t\t}\n\n\t\tawait this.mapAndAssignKeys(entity, this.entityType, updateArgs);\n\t\tawait this.getRepository().persistAndFlush(entity);\n\n\t\tlogger.trace(`update ${this.entityType.name} entity`, entity);\n\n\t\treturn entity;\n\t}\n\n\tpublic async updateMany(updateItems: (Partial<G> & { id: string })[]): Promise<D[]> {\n\t\tlogger.trace(`Running update many ${this.entityType.name} with args`, {\n\t\t\tupdateItems: JSON.stringify(updateItems),\n\t\t});\n\n\t\tconst entities = await this.database.transactional<D[]>(async () => {\n\t\t\treturn Promise.all<D>(\n\t\t\t\tupdateItems.map(async (item) => {\n\t\t\t\t\tif (!item?.id) throw new Error('You must pass an ID for this entity to update it.');\n\n\t\t\t\t\t// Find the entity in the database\n\t\t\t\t\tconst entity = await this.database.em.findOneOrFail(this.entityType, item.id, {\n\t\t\t\t\t\tpopulate: [...this.visitPathForPopulate(this.entityType.name, item)] as `${string}.`[],\n\t\t\t\t\t});\n\t\t\t\t\tawait this.mapAndAssignKeys(entity, this.entityType, item);\n\t\t\t\t\tthis.database.em.persist(entity);\n\t\t\t\t\treturn entity;\n\t\t\t\t})\n\t\t\t);\n\t\t});\n\n\t\tlogger.trace(`updated ${this.entityType.name} items `, entities);\n\n\t\treturn entities;\n\t}\n\n\tpublic async createOrUpdateMany(items: Partial<G>[]): Promise<D[]> {\n\t\tlogger.trace(`Running create or update many for ${this.entityType.name} with args`, {\n\t\t\titems: JSON.stringify(items),\n\t\t});\n\n\t\tconst entities = await this.database.transactional<D[]>(async () => {\n\t\t\treturn Promise.all<D>(\n\t\t\t\titems.map(async (item) => {\n\t\t\t\t\tlet entity;\n\t\t\t\t\tconst { id } = item as any;\n\t\t\t\t\tif (id) {\n\t\t\t\t\t\tentity = await this.database.em.findOneOrFail(this.entityType, id, {\n\t\t\t\t\t\t\tpopulate: [\n\t\t\t\t\t\t\t\t...this.visitPathForPopulate(this.entityType.name, item),\n\t\t\t\t\t\t\t] as `${string}.`[],\n\t\t\t\t\t\t});\n\t\t\t\t\t\tlogger.trace(`Running update on ${this.entityType.name} with item`, {\n\t\t\t\t\t\t\titem: JSON.stringify(item),\n\t\t\t\t\t\t});\n\t\t\t\t\t\tawait this.mapAndAssignKeys(entity, this.entityType, item);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tentity = new this.entityType();\n\t\t\t\t\t\tawait this.mapAndAssignKeys(entity, this.entityType, item);\n\t\t\t\t\t\tlogger.trace(`Running create on ${this.entityType.name} with item`, {\n\t\t\t\t\t\t\titem: JSON.stringify(item),\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tthis.database.em.persist(entity);\n\t\t\t\t\treturn entity;\n\t\t\t\t})\n\t\t\t);\n\t\t});\n\n\t\tlogger.trace(`created or updated ${this.entityType.name} items `, entities);\n\n\t\treturn entities;\n\t}\n\n\tpublic async createOne(createArgs: Partial<G>): Promise<D> {\n\t\tlogger.trace(`Running create ${this.entityType.name} with args`, {\n\t\t\tcreateArgs: JSON.stringify(createArgs),\n\t\t});\n\n\t\tconst entity = new this.entityType();\n\t\tawait this.mapAndAssignKeys(entity, this.entityType, createArgs);\n\t\tawait this.getRepository().persistAndFlush(entity);\n\n\t\tlogger.trace(`create ${this.entityType.name} result`, entity);\n\n\t\treturn entity;\n\t}\n\n\tpublic async createMany(createItems: Partial<G>[]): Promise<D[]> {\n\t\tlogger.trace(`Running create ${this.entityType.name} with args`, {\n\t\t\tcreateArgs: JSON.stringify(createItems),\n\t\t});\n\n\t\tconst entities = await this.database.transactional<D[]>(async () => {\n\t\t\treturn Promise.all<D>(\n\t\t\t\tcreateItems.map(async (item) => {\n\t\t\t\t\tconst entity = new this.entityType();\n\t\t\t\t\tawait this.mapAndAssignKeys(entity, this.entityType, item);\n\t\t\t\t\tthis.database.em.persist(entity);\n\t\t\t\t\treturn entity;\n\t\t\t\t})\n\t\t\t);\n\t\t});\n\n\t\tlogger.trace(`created ${this.entityType.name} items `, entities);\n\n\t\treturn entities;\n\t}\n\n\tpublic async deleteOne(filter: Filter<G>): Promise<boolean> {\n\t\tlogger.trace(`Running delete ${this.entityType.name} with filter ${filter}`);\n\t\tconst where = filter ? gqlToMikro(JSON.parse(JSON.stringify(filter))) : undefined;\n\t\tconst whereWithAppliedExternalIdFields =\n\t\t\twhere && this.applyExternalIdFields(this.entityType, where);\n\n\t\tconst deletedRows = await this.getRepository().nativeDelete(whereWithAppliedExternalIdFields);\n\n\t\tif (deletedRows > 1) {\n\t\t\tthrow new Error('Multiple deleted rows');\n\t\t}\n\n\t\tlogger.trace(`delete ${this.entityType.name} result: deleted ${deletedRows} row(s)`);\n\n\t\treturn deletedRows === 1;\n\t}\n\n\tpublic async deleteMany(ids: string[]): Promise<boolean> {\n\t\tlogger.trace(`Running delete ${this.entityType.name} with ids ${ids}`);\n\n\t\tconst deletedRows = await this.database.transactional<number>(async () => {\n\t\t\tconst deletedCount = await this.getRepository().nativeDelete({\n\t\t\t\tid: { $in: ids },\n\t\t\t} as FilterQuery<any>); // We can remove this cast when Typescript knows that T has an `id` property.\n\n\t\t\tif (deletedCount !== ids.length) {\n\t\t\t\tthrow new Error('We did not delete all the rows, rolling back');\n\t\t\t}\n\n\t\t\treturn deletedCount;\n\t\t});\n\n\t\tlogger.trace(`delete ${this.entityType.name} result: deleted ${deletedRows} row(s)`);\n\n\t\treturn deletedRows === ids.length;\n\t}\n\n\tpublic getRelatedEntityId(entity: any, relatedIdField: string) {\n\t\tif (typeof entity === 'string') {\n\t\t\treturn entity;\n\t\t}\n\t\tif (entity.id) {\n\t\t\treturn entity.id;\n\t\t}\n\t\t// No need to unwrap in Mikroorm version 5\n\t\tthrow new Error(`Unknown entity without an id: ${JSON.stringify(entity)}`);\n\t}\n\n\tpublic isCollection(entity: any) {\n\t\treturn Utils.isCollection(entity);\n\t}\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,yBAOO;AACP,oBAAuB;AAEvB,eAWO;AACP,oBAAoC;AACpC,oBAAuB;AAEvB,MAAM,mBAAmB,oBAAI,IAAI,CAAC,QAAQ,OAAO,MAAM,CAAC;AACxD,MAAM,wBAAwB,oBAAI,IAAI,CAAC,QAAQ,OAAO,MAAM,CAAC;AAC7D,MAAM,cAAc,oBAAI,IAAI;AAAA,EAC3B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACD,CAAC;AAED,MAAM,aAAa,CAAC,MAAc,YACjC,KAAK,SAAS,GAAG,QAAQ,YAAY;AAE/B,MAAM,aAAmC,CAAC,WAAgB;AAChE,MAAI,MAAM,QAAQ,MAAM,GAAG;AAC1B,WAAO,OAAO,IAAI,CAAC,YAAY,WAAW,OAAO,CAAC;AAAA,EACnD,WAAW,OAAO,WAAW,UAAU;AACtC,eAAW,OAAO,OAAO,KAAK,MAAM,GAAG;AAEtC,UAAI,OAAO,SAAS;AAAM;AAE1B,UAAI,iBAAiB,IAAI,GAAG,GAAG;AAE9B,eAAO,IAAI,QAAQ,KAAK,GAAG,KAAK,WAAW,OAAO,IAAI;AACtD,eAAO,OAAO;AAAA,MACf,WAAW,OAAO,OAAO,SAAS,YAAY,CAAC,MAAM,QAAQ,OAAO,IAAI,GAAG;AAE1E,eAAO,OAAO,WAAW,OAAO,IAAI;AAAA,MACr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AK,sBAAsB,KAAK,YAAY,KAAK;AAE3D,UAAM,cAAc,MAAM,KAAK,cAAc,EAAE,aAAa,gCAAgC;AAE5F,QAAI,cAAc,GAAG;AACpB,YAAM,IAAI,MAAM,uBAAuB;AAAA,IACxC;AAEA,yBAAO,MAAM,UAAU,KAAK,WAAW,wBAAwB,oBAAoB;AAEnF,WAAO,gBAAgB;AAAA,EACxB;AAAA,EAEA,MAAa,WAAW,KAAiC;AACxD,yBAAO,MAAM,kBAAkB,KAAK,WAAW,iBAAiB,KAAK;AAErE,UAAM,cAAc,MAAM,KAAK,SAAS,cAAsB,YAAY;AACzE,YAAM,eAAe,MAAM,KAAK,cAAc,EAAE,aAAa;AAAA,QAC5D,IAAI,EAAE,KAAK,IAAI;AAAA,MAChB,CAAqB;AAErB,UAAI,iBAAiB,IAAI,QAAQ;AAChC,cAAM,IAAI,MAAM,8CAA8C;AAAA,MAC/D;AAEA,aAAO;AAAA,IACR,CAAC;AAED,yBAAO,MAAM,UAAU,KAAK,WAAW,wBAAwB,oBAAoB;AAEnF,WAAO,gBAAgB,IAAI;AAAA,EAC5B;AAAA,EAEO,mBAAmB,QAAa,gBAAwB;AAC9D,QAAI,OAAO,WAAW,UAAU;AAC/B,aAAO;AAAA,IACR;AACA,QAAI,OAAO,IAAI;AACd,aAAO,OAAO;AAAA,IACf;AAEA,UAAM,IAAI,MAAM,iCAAiC,KAAK,UAAU,MAAM,GAAG;AAAA,EAC1E;AAAA,EAEO,aAAa,QAAa;AAChC,WAAO,eAAM,aAAa,MAAM;AAAA,EACjC;AACD;",
6
+ "names": ["key"]
7
+ }
package/lib/config.js CHANGED
@@ -40,3 +40,4 @@ const config = {};
40
40
  config,
41
41
  requireEnvironmentVariable
42
42
  });
43
+ //# sourceMappingURL=config.js.map