@exogee/graphweaver-mikroorm 2.0.5 → 2.0.7

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/lib/database.js CHANGED
@@ -116,6 +116,7 @@ class DatabaseImplementation {
116
116
  const orm = await import_core.MikroORM.init({
117
117
  validateRequired: false,
118
118
  // Since v5, new entities are validated on runtime (just before executing insert queries), based on the entity metadata
119
+ contextName: connectionOptions?.connectionManagerId ?? "default",
119
120
  implicitTransactions: false,
120
121
  metadataProvider: import_core.ReflectMetadataProvider,
121
122
  discovery: {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/database.ts"],
4
- "sourcesContent": ["import './utils/change-tracker';\n\nimport {\n\tAnyEntity,\n\tConnection,\n\tEntityName,\n\tIDatabaseDriver,\n\tMikroORM,\n\tOptions,\n\tReflectMetadataProvider,\n} from '@mikro-orm/core';\nimport { logger } from '@exogee/logger';\nimport { SecretsManagerClient, GetSecretValueCommand } from '@aws-sdk/client-secrets-manager';\n\nimport type { EntityManager as PgEntityManager, PostgreSqlDriver } from '@mikro-orm/postgresql';\nimport type { EntityManager as MyEntityManager, MySqlDriver } from '@mikro-orm/mysql';\nimport type { EntityManager as SqliteEntityManager, SqliteDriver } from '@mikro-orm/sqlite';\ntype EntityManager =\n\t| PgEntityManager<PostgreSqlDriver>\n\t| MyEntityManager<MySqlDriver>\n\t| SqliteEntityManager<SqliteDriver>;\n\nexport type DatabaseType = 'mysql' | 'postgresql' | 'sqlite';\n\nexport interface ConnectionOptions {\n\tmikroOrmConfig?: Options | (() => Options | Promise<Options>);\n\tsecretArn?: string;\n\tconnectionManagerId?: string;\n}\n\nexport enum IsolationLevel {\n\tSERIALIZABLE = 'SERIALIZABLE',\n\tREPEATABLE_READ = 'REPEATABLE READ',\n\tREAD_COMMITTED = 'READ COMMITTED',\n\tREAD_UNCOMMITTED = 'READ UNCOMMITTED',\n}\n\nconst NumericIsolationLevels = {\n\t[IsolationLevel.SERIALIZABLE]: 4,\n\t[IsolationLevel.REPEATABLE_READ]: 3,\n\t[IsolationLevel.READ_COMMITTED]: 2,\n\t[IsolationLevel.READ_UNCOMMITTED]: 1,\n};\n\nexport type Database = typeof DatabaseImplementation.prototype;\n\nclass DatabaseImplementation {\n\tprivate cachedOrm?: MikroORM<IDatabaseDriver<Connection>>;\n\tprivate transactionalEm?: EntityManager;\n\tprivate transactionInProgressIsolationLevel?: IsolationLevel;\n\tprivate connectionOptions?: ConnectionOptions;\n\n\tpublic get orm() {\n\t\tif (!this.cachedOrm) {\n\t\t\tconst error = new Error('Tried to get the ORM before it was connected.');\n\t\t\tlogger.error(error);\n\t\t\tthrow error;\n\t\t}\n\n\t\treturn this.cachedOrm;\n\t}\n\n\tpublic get em() {\n\t\treturn this.transactionalEm || (this.orm.em as EntityManager);\n\t}\n\n\tpublic async transactional<T>(\n\t\tcallback: () => Promise<T>,\n\t\tisolationLevel: IsolationLevel = IsolationLevel.READ_COMMITTED\n\t) {\n\t\tlogger.trace('Database::transactional() enter');\n\n\t\tif (\n\t\t\tthis.transactionInProgressIsolationLevel &&\n\t\t\tNumericIsolationLevels[this.transactionInProgressIsolationLevel] <\n\t\t\t\tNumericIsolationLevels[isolationLevel]\n\t\t) {\n\t\t\tconst error = new Error(\n\t\t\t\t`Transaction in progress is ${this.transactionInProgressIsolationLevel} isolation level, but ${isolationLevel} was requested, which is more restrictive. Since we can't upgrade, this is an error.`\n\t\t\t);\n\t\t\tlogger.error(error);\n\t\t\tthrow error;\n\t\t}\n\n\t\tif (this.transactionalEm) {\n\t\t\t// Transaction is already in progress that is isolated enough. Run the callback without starting a new one.\n\t\t\tlogger.trace(\n\t\t\t\t'Transaction already in progress with sufficient isolation, proceeding without new transaction.'\n\t\t\t);\n\n\t\t\treturn callback();\n\t\t} else {\n\t\t\t// Ok, start a new one.\n\t\t\tlogger.trace('Starting transaction');\n\n\t\t\treturn this.em.transactional(async (em) => {\n\t\t\t\tthis.transactionalEm = em;\n\t\t\t\tthis.transactionInProgressIsolationLevel = isolationLevel;\n\n\t\t\t\tconst driver = this.em.getDriver();\n\t\t\t\tif (driver.constructor.name === 'SqliteDriver') {\n\t\t\t\t\tlogger.trace('All transactions in SQLite are SERIALIZABLE');\n\t\t\t\t} else {\n\t\t\t\t\tawait em.execute(`SET SESSION TRANSACTION ISOLATION LEVEL ${isolationLevel}`);\n\t\t\t\t}\n\n\t\t\t\tlet result: T;\n\t\t\t\ttry {\n\t\t\t\t\tresult = await callback();\n\t\t\t\t} finally {\n\t\t\t\t\tdelete this.transactionalEm;\n\t\t\t\t\tdelete this.transactionInProgressIsolationLevel;\n\t\t\t\t}\n\t\t\t\treturn result;\n\t\t\t});\n\t\t}\n\t}\n\n\tpublic isolatedTest(test: () => any) {\n\t\treturn async () => {\n\t\t\ttry {\n\t\t\t\tawait this.transactional(async () => {\n\t\t\t\t\tawait test();\n\t\t\t\t\tthrow new Error('Rollback transaction for test');\n\t\t\t\t}, IsolationLevel.SERIALIZABLE);\n\t\t\t} catch (error) {\n\t\t\t\t// Only need to care if this isn't our rollback from above.\n\t\t\t\t// Otherwise just gobble it.\n\t\t\t\tif ((error as Error).message !== 'Rollback transaction for test') {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t}\n\n\tpublic get rawConnection() {\n\t\treturn this.em.getDriver().getConnection();\n\t}\n\n\tprivate getEnvironmentOverrides = async (secretArn?: string): Promise<Options> => {\n\t\tlogger.trace('Database::getEnvironmentOverrides() - Enter');\n\t\tconst secret = secretArn ?? process.env.DATABASE_SECRET_ARN;\n\t\tif (secret) {\n\t\t\tconst client = new SecretsManagerClient({\n\t\t\t\tregion: process.env.AWS_REGION,\n\t\t\t});\n\t\t\tconst command = new GetSecretValueCommand({ SecretId: secret });\n\n\t\t\ttry {\n\t\t\t\tlogger.trace('Fetching secret from Secrets Manager');\n\t\t\t\tconst response = await client.send(command);\n\t\t\t\tconst secret = JSON.parse(response.SecretString as string);\n\t\t\t\tlogger.trace('Secret fetched from Secrets Manager');\n\n\t\t\t\treturn {\n\t\t\t\t\thost: secret.host,\n\t\t\t\t\tport: secret.port,\n\t\t\t\t\tuser: secret.username,\n\t\t\t\t\tpassword: secret.password,\n\t\t\t\t\tdbName: secret.dbname,\n\t\t\t\t\tdriverOptions: {\n\t\t\t\t\t\tconnection: { ssl: true },\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t} catch (error) {\n\t\t\t\tlogger.error('Error fetching secret from Secrets Manager');\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t}\n\n\t\tlogger.trace('No secret ARN provided, using environment variables');\n\n\t\treturn {\n\t\t\thost: process.env.DATABASE_HOST,\n\t\t\tport: process.env.DATABASE_PORT ? Number(process.env.DATABASE_PORT) : undefined,\n\t\t\tuser: process.env.DATABASE_USERNAME,\n\t\t\tpassword: process.env.DATABASE_PASSWORD,\n\t\t\tdbName: process.env.DATABASE_NAME,\n\t\t};\n\t};\n\n\tprivate getConnectionInfo = async (connectionOptions?: ConnectionOptions): Promise<Options> => {\n\t\tlogger.trace('Database::getConnectionInfo() - Enter');\n\n\t\t// We have some defaults\n\t\tconst defaults: Options = {\n\t\t\thost: 'localhost',\n\t\t\tport: 5432,\n\t\t\tdbName: 'graphweaver',\n\t\t};\n\n\t\tconst resolvedMikroOrmConfig =\n\t\t\ttypeof connectionOptions?.mikroOrmConfig === 'function'\n\t\t\t\t? await connectionOptions.mikroOrmConfig()\n\t\t\t\t: connectionOptions?.mikroOrmConfig;\n\n\t\t// And finally we can override all of this with environment variables if needed.\n\t\tconst environmentOverrides = await this.getEnvironmentOverrides(connectionOptions?.secretArn);\n\n\t\t// Create a function we can use to filter out undefined values in the object.\n\t\tconst filterUndefined = (obj?: Options) => {\n\t\t\tif (!obj) return {};\n\n\t\t\tfor (const key of Object.keys(obj) as Array<keyof Options>) {\n\t\t\t\tif (obj[key] === undefined) delete obj[key];\n\t\t\t}\n\n\t\t\treturn obj;\n\t\t};\n\n\t\t// Apply each in order so the correct value wins.\n\t\treturn {\n\t\t\t...defaults,\n\t\t\t...filterUndefined(environmentOverrides),\n\t\t\t...filterUndefined(resolvedMikroOrmConfig),\n\t\t};\n\t};\n\n\tpublic getRepository = <T extends AnyEntity<T>>(entityName: EntityName<T>) =>\n\t\tthis.em.getRepository(entityName);\n\n\tpublic connect = async (connectionOptions?: ConnectionOptions) => {\n\t\tlogger.trace('Database::connect() - Enter');\n\t\tthis.connectionOptions = connectionOptions;\n\n\t\tif (this.cachedOrm) {\n\t\t\tlogger.trace('Returning cached ORM');\n\t\t\treturn this.cachedOrm;\n\t\t}\n\n\t\tlogger.trace('Creating new ORM');\n\t\tlogger.trace('Getting connection info');\n\n\t\tconst params = await this.getConnectionInfo(connectionOptions);\n\n\t\tlogger.trace('Initialising ORM');\n\n\t\tlogger.trace(`${params.entities?.length}x entities`);\n\n\t\tconst orm = await MikroORM.init({\n\t\t\tvalidateRequired: false, // Since v5, new entities are validated on runtime (just before executing insert queries), based on the entity metadata\n\n\t\t\timplicitTransactions: false,\n\t\t\tmetadataProvider: ReflectMetadataProvider,\n\t\t\tdiscovery: {\n\t\t\t\tdisableDynamicFileAccess: true,\n\t\t\t\trequireEntitiesArray: false,\n\t\t\t\twarnWhenNoEntities: false,\n\t\t\t},\n\t\t\tallowGlobalContext: true,\n\n\t\t\t// Ensure we only ever create one connection to the database.\n\t\t\tpool: {\n\t\t\t\tmin: 1,\n\t\t\t\tmax: 1,\n\t\t\t},\n\t\t\t...params,\n\t\t});\n\n\t\tlogger.trace('Creating connection to %s on %s', params.dbName, params.host);\n\t\tawait orm.connect();\n\n\t\tlogger.trace('Caching connection');\n\t\tthis.cachedOrm = orm;\n\t\treturn orm;\n\t};\n\n\tpublic close = async () => {\n\t\tlogger.trace('Closing database connection');\n\n\t\tawait this.orm.close(true);\n\t\tdelete this.cachedOrm;\n\t};\n}\n\nclass ConnectionsManager {\n\tprivate connections: Map<string, DatabaseImplementation>;\n\n\tconstructor() {\n\t\tthis.connections = new Map<string, DatabaseImplementation>();\n\t}\n\n\tgetConnections() {\n\t\treturn Array.from(this.connections.values());\n\t}\n\n\tget default(): DatabaseImplementation {\n\t\tconst [defaultConnection] = [...this.connections];\n\t\tif (!defaultConnection)\n\t\t\tthrow new Error(\n\t\t\t\t'Error: No database connections. There should be at least one database connection.'\n\t\t\t);\n\t\tconst [_, databaseConnection] = defaultConnection;\n\t\treturn databaseConnection;\n\t}\n\n\tpublic connect = async (id?: string, connectionOptions?: ConnectionOptions) => {\n\t\tif (!id) throw new Error('Error: No id attached to connection.');\n\n\t\tif (this.connections.has(id)) return this.connections.get(id);\n\t\tconst database = new DatabaseImplementation();\n\t\tif (connectionOptions) await database.connect(connectionOptions);\n\t\tlogger.trace(`Saving database connection with id \"${id}\".`);\n\t\tthis.connections.set(id, database);\n\t};\n\n\tpublic database(id: string) {\n\t\tlogger.trace(`Finding database connection for id \"${id}\"`);\n\t\treturn this.connections.get(id);\n\t}\n\n\tpublic async close(id: string) {\n\t\tconst database = this.database(id);\n\t\tawait database?.close();\n\t\treturn true;\n\t}\n}\nexport const ConnectionManager = new ConnectionsManager();\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,4BAAO;AAEP,kBAQO;AACP,oBAAuB;AACvB,oCAA4D;AAkBrD,IAAK,iBAAL,kBAAKA,oBAAL;AACN,EAAAA,gBAAA,kBAAe;AACf,EAAAA,gBAAA,qBAAkB;AAClB,EAAAA,gBAAA,oBAAiB;AACjB,EAAAA,gBAAA,sBAAmB;AAJR,SAAAA;AAAA,GAAA;AAOZ,MAAM,yBAAyB;AAAA,EAC9B,CAAC,iCAA2B,GAAG;AAAA,EAC/B,CAAC,uCAA8B,GAAG;AAAA,EAClC,CAAC,qCAA6B,GAAG;AAAA,EACjC,CAAC,yCAA+B,GAAG;AACpC;AAIA,MAAM,uBAAuB;AAAA,EAA7B;AA6FC,SAAQ,0BAA0B,OA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;AACtB,WAAO;AAAA,EACR;AACD;AACO,MAAM,oBAAoB,IAAI,mBAAmB;",
4
+ "sourcesContent": ["import './utils/change-tracker';\n\nimport {\n\tAnyEntity,\n\tConnection,\n\tEntityName,\n\tIDatabaseDriver,\n\tMikroORM,\n\tOptions,\n\tReflectMetadataProvider,\n} from '@mikro-orm/core';\nimport { logger } from '@exogee/logger';\nimport { SecretsManagerClient, GetSecretValueCommand } from '@aws-sdk/client-secrets-manager';\n\nimport type { EntityManager as PgEntityManager, PostgreSqlDriver } from '@mikro-orm/postgresql';\nimport type { EntityManager as MyEntityManager, MySqlDriver } from '@mikro-orm/mysql';\nimport type { EntityManager as SqliteEntityManager, SqliteDriver } from '@mikro-orm/sqlite';\ntype EntityManager =\n\t| PgEntityManager<PostgreSqlDriver>\n\t| MyEntityManager<MySqlDriver>\n\t| SqliteEntityManager<SqliteDriver>;\n\nexport type DatabaseType = 'mysql' | 'postgresql' | 'sqlite';\n\nexport interface ConnectionOptions {\n\tmikroOrmConfig?: Options | (() => Options | Promise<Options>);\n\tsecretArn?: string;\n\tconnectionManagerId?: string;\n}\n\nexport enum IsolationLevel {\n\tSERIALIZABLE = 'SERIALIZABLE',\n\tREPEATABLE_READ = 'REPEATABLE READ',\n\tREAD_COMMITTED = 'READ COMMITTED',\n\tREAD_UNCOMMITTED = 'READ UNCOMMITTED',\n}\n\nconst NumericIsolationLevels = {\n\t[IsolationLevel.SERIALIZABLE]: 4,\n\t[IsolationLevel.REPEATABLE_READ]: 3,\n\t[IsolationLevel.READ_COMMITTED]: 2,\n\t[IsolationLevel.READ_UNCOMMITTED]: 1,\n};\n\nexport type Database = typeof DatabaseImplementation.prototype;\n\nclass DatabaseImplementation {\n\tprivate cachedOrm?: MikroORM<IDatabaseDriver<Connection>>;\n\tprivate transactionalEm?: EntityManager;\n\tprivate transactionInProgressIsolationLevel?: IsolationLevel;\n\tprivate connectionOptions?: ConnectionOptions;\n\n\tpublic get orm() {\n\t\tif (!this.cachedOrm) {\n\t\t\tconst error = new Error('Tried to get the ORM before it was connected.');\n\t\t\tlogger.error(error);\n\t\t\tthrow error;\n\t\t}\n\n\t\treturn this.cachedOrm;\n\t}\n\n\tpublic get em() {\n\t\treturn this.transactionalEm || (this.orm.em as EntityManager);\n\t}\n\n\tpublic async transactional<T>(\n\t\tcallback: () => Promise<T>,\n\t\tisolationLevel: IsolationLevel = IsolationLevel.READ_COMMITTED\n\t) {\n\t\tlogger.trace('Database::transactional() enter');\n\n\t\tif (\n\t\t\tthis.transactionInProgressIsolationLevel &&\n\t\t\tNumericIsolationLevels[this.transactionInProgressIsolationLevel] <\n\t\t\t\tNumericIsolationLevels[isolationLevel]\n\t\t) {\n\t\t\tconst error = new Error(\n\t\t\t\t`Transaction in progress is ${this.transactionInProgressIsolationLevel} isolation level, but ${isolationLevel} was requested, which is more restrictive. Since we can't upgrade, this is an error.`\n\t\t\t);\n\t\t\tlogger.error(error);\n\t\t\tthrow error;\n\t\t}\n\n\t\tif (this.transactionalEm) {\n\t\t\t// Transaction is already in progress that is isolated enough. Run the callback without starting a new one.\n\t\t\tlogger.trace(\n\t\t\t\t'Transaction already in progress with sufficient isolation, proceeding without new transaction.'\n\t\t\t);\n\n\t\t\treturn callback();\n\t\t} else {\n\t\t\t// Ok, start a new one.\n\t\t\tlogger.trace('Starting transaction');\n\n\t\t\treturn this.em.transactional(async (em) => {\n\t\t\t\tthis.transactionalEm = em;\n\t\t\t\tthis.transactionInProgressIsolationLevel = isolationLevel;\n\n\t\t\t\tconst driver = this.em.getDriver();\n\t\t\t\tif (driver.constructor.name === 'SqliteDriver') {\n\t\t\t\t\tlogger.trace('All transactions in SQLite are SERIALIZABLE');\n\t\t\t\t} else {\n\t\t\t\t\tawait em.execute(`SET SESSION TRANSACTION ISOLATION LEVEL ${isolationLevel}`);\n\t\t\t\t}\n\n\t\t\t\tlet result: T;\n\t\t\t\ttry {\n\t\t\t\t\tresult = await callback();\n\t\t\t\t} finally {\n\t\t\t\t\tdelete this.transactionalEm;\n\t\t\t\t\tdelete this.transactionInProgressIsolationLevel;\n\t\t\t\t}\n\t\t\t\treturn result;\n\t\t\t});\n\t\t}\n\t}\n\n\tpublic isolatedTest(test: () => any) {\n\t\treturn async () => {\n\t\t\ttry {\n\t\t\t\tawait this.transactional(async () => {\n\t\t\t\t\tawait test();\n\t\t\t\t\tthrow new Error('Rollback transaction for test');\n\t\t\t\t}, IsolationLevel.SERIALIZABLE);\n\t\t\t} catch (error) {\n\t\t\t\t// Only need to care if this isn't our rollback from above.\n\t\t\t\t// Otherwise just gobble it.\n\t\t\t\tif ((error as Error).message !== 'Rollback transaction for test') {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t}\n\n\tpublic get rawConnection() {\n\t\treturn this.em.getDriver().getConnection();\n\t}\n\n\tprivate getEnvironmentOverrides = async (secretArn?: string): Promise<Options> => {\n\t\tlogger.trace('Database::getEnvironmentOverrides() - Enter');\n\t\tconst secret = secretArn ?? process.env.DATABASE_SECRET_ARN;\n\t\tif (secret) {\n\t\t\tconst client = new SecretsManagerClient({\n\t\t\t\tregion: process.env.AWS_REGION,\n\t\t\t});\n\t\t\tconst command = new GetSecretValueCommand({ SecretId: secret });\n\n\t\t\ttry {\n\t\t\t\tlogger.trace('Fetching secret from Secrets Manager');\n\t\t\t\tconst response = await client.send(command);\n\t\t\t\tconst secret = JSON.parse(response.SecretString as string);\n\t\t\t\tlogger.trace('Secret fetched from Secrets Manager');\n\n\t\t\t\treturn {\n\t\t\t\t\thost: secret.host,\n\t\t\t\t\tport: secret.port,\n\t\t\t\t\tuser: secret.username,\n\t\t\t\t\tpassword: secret.password,\n\t\t\t\t\tdbName: secret.dbname,\n\t\t\t\t\tdriverOptions: {\n\t\t\t\t\t\tconnection: { ssl: true },\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t} catch (error) {\n\t\t\t\tlogger.error('Error fetching secret from Secrets Manager');\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t}\n\n\t\tlogger.trace('No secret ARN provided, using environment variables');\n\n\t\treturn {\n\t\t\thost: process.env.DATABASE_HOST,\n\t\t\tport: process.env.DATABASE_PORT ? Number(process.env.DATABASE_PORT) : undefined,\n\t\t\tuser: process.env.DATABASE_USERNAME,\n\t\t\tpassword: process.env.DATABASE_PASSWORD,\n\t\t\tdbName: process.env.DATABASE_NAME,\n\t\t};\n\t};\n\n\tprivate getConnectionInfo = async (connectionOptions?: ConnectionOptions): Promise<Options> => {\n\t\tlogger.trace('Database::getConnectionInfo() - Enter');\n\n\t\t// We have some defaults\n\t\tconst defaults: Options = {\n\t\t\thost: 'localhost',\n\t\t\tport: 5432,\n\t\t\tdbName: 'graphweaver',\n\t\t};\n\n\t\tconst resolvedMikroOrmConfig =\n\t\t\ttypeof connectionOptions?.mikroOrmConfig === 'function'\n\t\t\t\t? await connectionOptions.mikroOrmConfig()\n\t\t\t\t: connectionOptions?.mikroOrmConfig;\n\n\t\t// And finally we can override all of this with environment variables if needed.\n\t\tconst environmentOverrides = await this.getEnvironmentOverrides(connectionOptions?.secretArn);\n\n\t\t// Create a function we can use to filter out undefined values in the object.\n\t\tconst filterUndefined = (obj?: Options) => {\n\t\t\tif (!obj) return {};\n\n\t\t\tfor (const key of Object.keys(obj) as Array<keyof Options>) {\n\t\t\t\tif (obj[key] === undefined) delete obj[key];\n\t\t\t}\n\n\t\t\treturn obj;\n\t\t};\n\n\t\t// Apply each in order so the correct value wins.\n\t\treturn {\n\t\t\t...defaults,\n\t\t\t...filterUndefined(environmentOverrides),\n\t\t\t...filterUndefined(resolvedMikroOrmConfig),\n\t\t};\n\t};\n\n\tpublic getRepository = <T extends AnyEntity<T>>(entityName: EntityName<T>) =>\n\t\tthis.em.getRepository(entityName);\n\n\tpublic connect = async (connectionOptions?: ConnectionOptions) => {\n\t\tlogger.trace('Database::connect() - Enter');\n\t\tthis.connectionOptions = connectionOptions;\n\n\t\tif (this.cachedOrm) {\n\t\t\tlogger.trace('Returning cached ORM');\n\t\t\treturn this.cachedOrm;\n\t\t}\n\n\t\tlogger.trace('Creating new ORM');\n\t\tlogger.trace('Getting connection info');\n\n\t\tconst params = await this.getConnectionInfo(connectionOptions);\n\n\t\tlogger.trace('Initialising ORM');\n\n\t\tlogger.trace(`${params.entities?.length}x entities`);\n\n\t\tconst orm = await MikroORM.init({\n\t\t\tvalidateRequired: false, // Since v5, new entities are validated on runtime (just before executing insert queries), based on the entity metadata\n\t\t\tcontextName: connectionOptions?.connectionManagerId ?? 'default',\n\t\t\timplicitTransactions: false,\n\t\t\tmetadataProvider: ReflectMetadataProvider,\n\t\t\tdiscovery: {\n\t\t\t\tdisableDynamicFileAccess: true,\n\t\t\t\trequireEntitiesArray: false,\n\t\t\t\twarnWhenNoEntities: false,\n\t\t\t},\n\t\t\tallowGlobalContext: true,\n\n\t\t\t// Ensure we only ever create one connection to the database.\n\t\t\tpool: {\n\t\t\t\tmin: 1,\n\t\t\t\tmax: 1,\n\t\t\t},\n\t\t\t...params,\n\t\t});\n\n\t\tlogger.trace('Creating connection to %s on %s', params.dbName, params.host);\n\t\tawait orm.connect();\n\n\t\tlogger.trace('Caching connection');\n\t\tthis.cachedOrm = orm;\n\t\treturn orm;\n\t};\n\n\tpublic close = async () => {\n\t\tlogger.trace('Closing database connection');\n\n\t\tawait this.orm.close(true);\n\t\tdelete this.cachedOrm;\n\t};\n}\n\nclass ConnectionsManager {\n\tprivate connections: Map<string, DatabaseImplementation>;\n\n\tconstructor() {\n\t\tthis.connections = new Map<string, DatabaseImplementation>();\n\t}\n\n\tgetConnections() {\n\t\treturn Array.from(this.connections.values());\n\t}\n\n\tget default(): DatabaseImplementation {\n\t\tconst [defaultConnection] = [...this.connections];\n\t\tif (!defaultConnection)\n\t\t\tthrow new Error(\n\t\t\t\t'Error: No database connections. There should be at least one database connection.'\n\t\t\t);\n\t\tconst [_, databaseConnection] = defaultConnection;\n\t\treturn databaseConnection;\n\t}\n\n\tpublic connect = async (id?: string, connectionOptions?: ConnectionOptions) => {\n\t\tif (!id) throw new Error('Error: No id attached to connection.');\n\n\t\tif (this.connections.has(id)) return this.connections.get(id);\n\t\tconst database = new DatabaseImplementation();\n\t\tif (connectionOptions) await database.connect(connectionOptions);\n\t\tlogger.trace(`Saving database connection with id \"${id}\".`);\n\t\tthis.connections.set(id, database);\n\t};\n\n\tpublic database(id: string) {\n\t\tlogger.trace(`Finding database connection for id \"${id}\"`);\n\t\treturn this.connections.get(id);\n\t}\n\n\tpublic async close(id: string) {\n\t\tconst database = this.database(id);\n\t\tawait database?.close();\n\t\treturn true;\n\t}\n}\nexport const ConnectionManager = new ConnectionsManager();\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,4BAAO;AAEP,kBAQO;AACP,oBAAuB;AACvB,oCAA4D;AAkBrD,IAAK,iBAAL,kBAAKA,oBAAL;AACN,EAAAA,gBAAA,kBAAe;AACf,EAAAA,gBAAA,qBAAkB;AAClB,EAAAA,gBAAA,oBAAiB;AACjB,EAAAA,gBAAA,sBAAmB;AAJR,SAAAA;AAAA,GAAA;AAOZ,MAAM,yBAAyB;AAAA,EAC9B,CAAC,iCAA2B,GAAG;AAAA,EAC/B,CAAC,uCAA8B,GAAG;AAAA,EAClC,CAAC,qCAA6B,GAAG;AAAA,EACjC,CAAC,yCAA+B,GAAG;AACpC;AAIA,MAAM,uBAAuB;AAAA,EAA7B;AA6FC,SAAQ,0BAA0B,OAAO,cAAyC;AACjF,2BAAO,MAAM,6CAA6C;AAC1D,YAAM,SAAS,aAAa,QAAQ,IAAI;AACxC,UAAI,QAAQ;AACX,cAAM,SAAS,IAAI,mDAAqB;AAAA,UACvC,QAAQ,QAAQ,IAAI;AAAA,QACrB,CAAC;AACD,cAAM,UAAU,IAAI,oDAAsB,EAAE,UAAU,OAAO,CAAC;AAE9D,YAAI;AACH,+BAAO,MAAM,sCAAsC;AACnD,gBAAM,WAAW,MAAM,OAAO,KAAK,OAAO;AAC1C,gBA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E,cAAc;AAAA,EAC1C;AAwID;AAEA,MAAM,mBAAmB;AAAA,EAGxB,cAAc;AAkBd,SAAO,UAAU,OAAO,IAAa,sBAA0C;AAC9E,UAAI,CAAC,GAAI,OAAM,IAAI,MAAM,sCAAsC;AAE/D,UAAI,KAAK,YAAY,IAAI,EAAE,EAAG,QAAO,KAAK,YAAY,IAAI,EAAE;AAC5D,YAAM,WAAW,IAAI,uBAAuB;AAC5C,UAAI,kBAAmB,OAAM,SAAS,QAAQ,iBAAiB;AAC/D,2BAAO,MAAM,uCAAuC,EAAE,IAAI;AAC1D,WAAK,YAAY,IAAI,IAAI,QAAQ;AAAA,IAClC;AAzBC,SAAK,cAAc,oBAAI,IAAoC;AAAA,EAC5D;AAAA,EAEA,iBAAiB;AAChB,WAAO,MAAM,KAAK,KAAK,YAAY,OAAO,CAAC;AAAA,EAC5C;AAAA,EAEA,IAAI,UAAkC;AACrC,UAAM,CAAC,iBAAiB,IAAI,CAAC,GAAG,KAAK,WAAW;AAChD,QAAI,CAAC;AACJ,YAAM,IAAI;AAAA,QACT;AAAA,MACD;AACD,UAAM,CAAC,GAAG,kBAAkB,IAAI;AAChC,WAAO;AAAA,EACR;AAAA,EAYO,SAAS,IAAY;AAC3B,yBAAO,MAAM,uCAAuC,EAAE,GAAG;AACzD,WAAO,KAAK,YAAY,IAAI,EAAE;AAAA,EAC/B;AAAA,EAEA,MAAa,MAAM,IAAY;AAC9B,UAAM,WAAW,KAAK,SAAS,EAAE;AACjC,UAAM,UAAU,MAAM;AACtB,WAAO;AAAA,EACR;AACD;AACO,MAAM,oBAAoB,IAAI,mBAAmB;",
6
6
  "names": ["IsolationLevel", "secret"]
7
7
  }
@@ -86,6 +86,9 @@ ${file}`;
86
86
  return file;
87
87
  }
88
88
  getPropertyType(prop) {
89
+ if ([import_core.ReferenceKind.ONE_TO_ONE, import_core.ReferenceKind.MANY_TO_ONE].includes(prop.kind)) {
90
+ return prop.type.charAt(0).toUpperCase() + prop.type.slice(1);
91
+ }
89
92
  const columnType = prop.columnTypes?.[0]?.toLowerCase();
90
93
  if (["jsonb", "json", "any"].includes(columnType)) {
91
94
  return `Record<string, unknown>`;
@@ -95,7 +98,7 @@ ${file}`;
95
98
  return "string";
96
99
  }
97
100
  }
98
- return prop.type;
101
+ return prop.runtimeType;
99
102
  }
100
103
  getPropertyDefinition(prop) {
101
104
  const padding = " ";
@@ -120,7 +123,7 @@ ${file}`;
120
123
  `;
121
124
  }
122
125
  if (prop.enum && typeof prop.default === "string") {
123
- return `${padding}${file} = ${prop.type}.${prop.default.toUpperCase()};
126
+ return `${padding}${file} = ${prop.runtimeType}.${(0, import_utils.identifierForEnumValue)(prop.default)};
124
127
  `;
125
128
  }
126
129
  return `${padding}${prop.name} = ${prop.default};
@@ -131,7 +134,7 @@ ${file}`;
131
134
  let file = `export enum ${enumClassName} {
132
135
  `;
133
136
  for (const enumValue of enumValues) {
134
- file += `${padding}${enumValue.toUpperCase()} = '${enumValue}',
137
+ file += `${padding}${(0, import_utils.identifierForEnumValue)(enumValue)} = '${enumValue}',
135
138
  `;
136
139
  }
137
140
  file += "}\n";
@@ -163,7 +166,7 @@ ${file}`;
163
166
  this.getScalarPropertyDecoratorOptions(options, prop);
164
167
  }
165
168
  if (prop.enum) {
166
- options.items = `() => ${prop.type}`;
169
+ options.items = `() => ${prop.runtimeType}`;
167
170
  }
168
171
  this.getCommonDecoratorOptions(options, prop);
169
172
  const indexes = this.getPropertyIndexes(prop, options);
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/introspection/files/data-entity-file.ts"],
4
- "sourcesContent": ["// This file is a modified version of source from MikroORM, located here:\n// https://github.com/mikro-orm/mikro-orm/blob/6ba3d4004deef00b754a4ca2011cf64e44a4a3a3/packages/entity-generator/src/SourceFile.ts\n//\n// MIT License\n//\n// Copyright (c) 2018 Martin Ad\u00E1mek\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\nimport type {\n\tDictionary,\n\tEntityMetadata,\n\tEntityOptions,\n\tEntityProperty,\n\tNamingStrategy,\n\tPlatform,\n} from '@mikro-orm/core';\nimport { ReferenceKind, UnknownType, Utils } from '@mikro-orm/core';\nimport { BaseFile } from './base-file';\nimport { DatabaseType } from '../../database';\nimport { pascalToKebabCaseString } from '../utils';\n\nexport class DataEntityFile extends BaseFile {\n\tprotected readonly coreImports = new Set<string>();\n\tprotected readonly entityImports = new Set<string>();\n\n\tconstructor(\n\t\tprotected readonly meta: EntityMetadata,\n\t\tprotected readonly namingStrategy: NamingStrategy,\n\t\tprotected readonly platform: Platform,\n\t\tprotected readonly databaseType: DatabaseType\n\t) {\n\t\tsuper(meta, namingStrategy, platform);\n\t}\n\n\tgetBasePath() {\n\t\treturn `backend/entities/${this.databaseType}/`;\n\t}\n\n\tgetBaseName() {\n\t\tconst fileName = pascalToKebabCaseString(this.meta.className);\n\t\treturn `${fileName}.ts`;\n\t}\n\n\tgenerate(): string {\n\t\tconst enumDefinitions: string[] = [];\n\t\tlet classBody = '';\n\t\tconst props = Object.values(this.meta.properties);\n\t\tprops.forEach((prop) => {\n\t\t\tconst decorator = this.getPropertyDecorator(prop);\n\t\t\tconst definition = this.getPropertyDefinition(prop);\n\n\t\t\tif (!classBody.endsWith('\\n\\n')) {\n\t\t\t\tclassBody += '\\n';\n\t\t\t}\n\n\t\t\tclassBody += decorator;\n\t\t\tclassBody += definition;\n\n\t\t\tif (props[props.length - 1] !== prop) classBody += '\\n';\n\n\t\t\tif (prop.enum) {\n\t\t\t\tconst enumClassName = this.namingStrategy.getClassName(\n\t\t\t\t\tthis.meta.collection + '_' + prop.fieldNames[0],\n\t\t\t\t\t'_'\n\t\t\t\t);\n\t\t\t\tenumDefinitions.push(this.getEnumClassDefinition(enumClassName, prop.items as string[]));\n\t\t\t}\n\t\t});\n\n\t\tlet file = ``;\n\n\t\tthis.coreImports.add('Entity');\n\t\tconst imports = [\n\t\t\t`import { ${[...this.coreImports].sort().join(', ')} } from '@mikro-orm/core';`,\n\t\t];\n\t\tconst entityImports = [...this.entityImports].filter((e) => e !== this.meta.className);\n\t\tentityImports.sort().forEach((entity) => {\n\t\t\timports.push(`import { ${entity} } from './${pascalToKebabCaseString(entity)}';`);\n\t\t});\n\n\t\tif (enumDefinitions.length) {\n\t\t\tfile += enumDefinitions.join('\\n');\n\t\t\tfile += '\\n';\n\t\t}\n\n\t\tfile += `@Entity(${this.getCollectionDecl()})\\n`;\n\t\tfile += `export class ${this.meta.className} {`;\n\n\t\tfile += `${classBody}}\\n`;\n\n\t\tfile = `${imports.join('\\n')}\\n\\n${file}`;\n\n\t\treturn file;\n\t}\n\n\tprotected getPropertyType(prop: EntityProperty): string {\n\t\tconst columnType = prop.columnTypes?.[0]?.toLowerCase();\n\n\t\tif (['jsonb', 'json', 'any'].includes(columnType)) {\n\t\t\treturn `Record<string, unknown>`;\n\t\t}\n\n\t\t// Mikro doesn't infer column types for some columns very well. We can augment.\n\t\tif (prop.type === 'unknown') {\n\t\t\tif (columnType?.startsWith('nvarchar(') || columnType?.startsWith('varchar(')) {\n\t\t\t\treturn 'string';\n\t\t\t}\n\t\t}\n\n\t\treturn prop.type;\n\t}\n\n\tprotected getPropertyDefinition(prop: EntityProperty): string {\n\t\tconst padding = '\\t';\n\n\t\tif ([ReferenceKind.ONE_TO_MANY, ReferenceKind.MANY_TO_MANY].includes(prop.kind)) {\n\t\t\tthis.coreImports.add('Collection');\n\t\t\tthis.entityImports.add(prop.type);\n\t\t\treturn `${padding}${prop.name} = new Collection<${prop.type}>(this);\\n`;\n\t\t}\n\n\t\t// string defaults are usually things like SQL functions, but can be also enums, for that `useDefault` should be true\n\t\tconst isEnumOrNonStringDefault = prop.enum || typeof prop.default !== 'string';\n\t\tconst useDefault = prop.default != null && isEnumOrNonStringDefault;\n\t\tconst optional = prop.nullable ? '?' : useDefault ? '' : '!';\n\n\t\tif (prop.ref) {\n\t\t\tthis.coreImports.add('Ref');\n\t\t\tthis.entityImports.add(prop.type);\n\t\t\treturn `${padding}${prop.name}${optional}: Ref<${prop.type}>;\\n`;\n\t\t}\n\n\t\tconst file = `${prop.name}${optional}: ${this.getPropertyType(prop)}`;\n\n\t\tif (!useDefault) {\n\t\t\treturn `${padding + file};\\n`;\n\t\t}\n\n\t\tif (prop.enum && typeof prop.default === 'string') {\n\t\t\treturn `${padding}${file} = ${prop.type}.${prop.default.toUpperCase()};\\n`;\n\t\t}\n\n\t\treturn `${padding}${prop.name} = ${prop.default};\\n`;\n\t}\n\n\tprotected getEnumClassDefinition(enumClassName: string, enumValues: string[]): string {\n\t\tconst padding = '\\t';\n\t\tlet file = `export enum ${enumClassName} {\\n`;\n\n\t\tfor (const enumValue of enumValues) {\n\t\t\tfile += `${padding}${enumValue.toUpperCase()} = '${enumValue}',\\n`;\n\t\t}\n\n\t\tfile += '}\\n';\n\n\t\treturn file;\n\t}\n\n\tprivate getCollectionDecl() {\n\t\tconst options: EntityOptions<unknown> = {};\n\n\t\toptions.tableName = this.quote(this.meta.collection);\n\n\t\tif (this.meta.schema && this.meta.schema !== this.platform.getDefaultSchemaName()) {\n\t\t\toptions.schema = this.quote(this.meta.schema);\n\t\t}\n\n\t\tif (!Utils.hasObjectKeys(options)) {\n\t\t\treturn '';\n\t\t}\n\n\t\treturn `{ ${Object.entries(options)\n\t\t\t.map(([opt, val]) => `${opt}: ${val}`)\n\t\t\t.join(', ')} }`;\n\t}\n\n\tprivate getPropertyDecorator(prop: EntityProperty): string {\n\t\tconst padding = '\\t';\n\t\tconst options = {} as Dictionary;\n\t\tlet decorator = this.getDecoratorType(prop);\n\t\tthis.coreImports.add(decorator.substring(1));\n\n\t\tif (prop.kind === ReferenceKind.MANY_TO_MANY) {\n\t\t\tthis.getManyToManyDecoratorOptions(options, prop);\n\t\t} else if (prop.kind === ReferenceKind.ONE_TO_MANY) {\n\t\t\tthis.getOneToManyDecoratorOptions(options, prop);\n\t\t} else if (prop.kind !== ReferenceKind.SCALAR) {\n\t\t\tthis.getForeignKeyDecoratorOptions(options, prop);\n\t\t} else {\n\t\t\tthis.getScalarPropertyDecoratorOptions(options, prop);\n\t\t}\n\n\t\tif (prop.enum) {\n\t\t\toptions.items = `() => ${prop.type}`;\n\t\t}\n\n\t\tthis.getCommonDecoratorOptions(options, prop);\n\t\tconst indexes = this.getPropertyIndexes(prop, options);\n\t\tdecorator = [...indexes.sort(), decorator].map((d) => padding + d).join('\\n');\n\n\t\tif (!Utils.hasObjectKeys(options)) {\n\t\t\treturn `${decorator}()\\n`;\n\t\t}\n\n\t\treturn `${decorator}({ ${Object.entries(options)\n\t\t\t.map(([opt, val]) => `${opt}: ${val}`)\n\t\t\t.join(', ')} })\\n`;\n\t}\n\n\tprotected getPropertyIndexes(prop: EntityProperty, options: Dictionary): string[] {\n\t\tif (prop.kind === ReferenceKind.SCALAR) {\n\t\t\tconst ret: string[] = [];\n\n\t\t\tif (prop.index) {\n\t\t\t\tthis.coreImports.add('Index');\n\t\t\t\tret.push(`@Index({ name: '${prop.index}' })`);\n\t\t\t}\n\n\t\t\tif (prop.unique) {\n\t\t\t\tthis.coreImports.add('Unique');\n\t\t\t\tret.push(`@Unique({ name: '${prop.unique}' })`);\n\t\t\t}\n\n\t\t\treturn ret;\n\t\t}\n\n\t\tconst processIndex = (type: 'index' | 'unique') => {\n\t\t\tif (!prop[type]) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst defaultName = this.platform.getIndexName(this.meta.collection, prop.fieldNames, type);\n\t\t\toptions[type] = defaultName === prop[type] ? 'true' : `'${prop[type]}'`;\n\t\t\tconst expected = {\n\t\t\t\tindex: this.platform.indexForeignKeys(),\n\t\t\t\tunique: prop.kind === ReferenceKind.ONE_TO_ONE,\n\t\t\t};\n\n\t\t\tif (expected[type] && options[type] === 'true') {\n\t\t\t\tdelete options[type];\n\t\t\t}\n\t\t};\n\n\t\tprocessIndex('index');\n\t\tprocessIndex('unique');\n\n\t\treturn [];\n\t}\n\n\tprotected getCommonDecoratorOptions(options: Dictionary, prop: EntityProperty): void {\n\t\tif (prop.nullable && !prop.mappedBy) {\n\t\t\toptions.nullable = true;\n\t\t}\n\n\t\tif (prop.default == null) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (typeof prop.default !== 'string') {\n\t\t\toptions.default = prop.default;\n\t\t\treturn;\n\t\t}\n\n\t\tif ([`''`, ''].includes(prop.default)) {\n\t\t\toptions.default = `''`;\n\t\t} else if (prop.defaultRaw === this.quote(prop.default)) {\n\t\t\toptions.default = this.quote(prop.default);\n\t\t} else {\n\t\t\toptions.defaultRaw = `\\`${prop.default}\\``;\n\t\t}\n\t}\n\n\tprotected getScalarPropertyDecoratorOptions(options: Dictionary, prop: EntityProperty): void {\n\t\tlet t = prop.type.toLowerCase();\n\n\t\tif (t === 'date') {\n\t\t\tt = 'datetime';\n\t\t}\n\n\t\tif (prop.fieldNames[0] !== this.namingStrategy.propertyToColumnName(prop.name)) {\n\t\t\toptions.fieldName = `'${prop.fieldNames[0]}'`;\n\t\t}\n\n\t\t// for enum properties, we don't need a column type or the property length\n\t\t// in the decorator so return early.\n\t\tif (prop.enum) {\n\t\t\toptions.type = this.quote('string');\n\t\t\treturn;\n\t\t}\n\n\t\tconst mappedType1 = this.platform.getMappedType(t);\n\t\tconst mappedType2 = this.platform.getMappedType(prop.columnTypes[0]);\n\t\tconst columnType1 = mappedType1.getColumnType({ ...prop, autoincrement: false }, this.platform);\n\t\tconst columnType2 = mappedType2.getColumnType({ ...prop, autoincrement: false }, this.platform);\n\n\t\tif (\n\t\t\tcolumnType1 !== columnType2 ||\n\t\t\t[mappedType1, mappedType2].some((t) => t instanceof UnknownType)\n\t\t) {\n\t\t\toptions.type = this.quote(prop.columnTypes[0]);\n\t\t} else {\n\t\t\toptions.type = this.quote(prop.type);\n\t\t}\n\n\t\tif (prop.length) {\n\t\t\toptions.length = prop.length;\n\t\t}\n\t}\n\n\tprotected getManyToManyDecoratorOptions(options: Dictionary, prop: EntityProperty) {\n\t\tthis.entityImports.add(prop.type);\n\t\toptions.entity = `() => ${prop.type}`;\n\n\t\tif (prop.mappedBy) {\n\t\t\toptions.mappedBy = this.quote(prop.mappedBy);\n\t\t\treturn;\n\t\t}\n\n\t\tif (\n\t\t\tprop.pivotTable !==\n\t\t\tthis.namingStrategy.joinTableName(this.meta.collection, prop.type, prop.name)\n\t\t) {\n\t\t\toptions.pivotTable = this.quote(prop.pivotTable);\n\t\t}\n\n\t\tif (prop.joinColumns.length === 1) {\n\t\t\toptions.joinColumn = this.quote(prop.joinColumns[0]);\n\t\t} else {\n\t\t\toptions.joinColumns = `[${prop.joinColumns.map(this.quote).join(', ')}]`;\n\t\t}\n\n\t\tif (prop.inverseJoinColumns.length === 1) {\n\t\t\toptions.inverseJoinColumn = this.quote(prop.inverseJoinColumns[0]);\n\t\t} else {\n\t\t\toptions.inverseJoinColumns = `[${prop.inverseJoinColumns.map(this.quote).join(', ')}]`;\n\t\t}\n\t}\n\n\tprotected getOneToManyDecoratorOptions(options: Dictionary, prop: EntityProperty) {\n\t\tthis.entityImports.add(prop.type);\n\t\toptions.entity = `() => ${prop.type}`;\n\t\toptions.mappedBy = this.quote(prop.mappedBy);\n\t}\n\n\tprotected getForeignKeyDecoratorOptions(options: Dictionary, prop: EntityProperty) {\n\t\tthis.entityImports.add(prop.type);\n\t\toptions.entity = `() => ${prop.type}`;\n\n\t\tif (prop.ref) {\n\t\t\toptions.ref = true;\n\t\t}\n\n\t\tif (prop.mappedBy) {\n\t\t\toptions.mappedBy = this.quote(prop.mappedBy);\n\t\t\treturn;\n\t\t}\n\n\t\tif (\n\t\t\tprop.fieldNames[0] !==\n\t\t\tthis.namingStrategy.joinKeyColumnName(prop.name, prop.referencedColumnNames[0])\n\t\t) {\n\t\t\toptions.fieldName = this.quote(prop.fieldNames[0]);\n\t\t}\n\n\t\tif (prop.primary) {\n\t\t\toptions.primary = true;\n\t\t}\n\t}\n\n\tprotected getDecoratorType(prop: EntityProperty): string {\n\t\tif (prop.kind === ReferenceKind.ONE_TO_ONE) {\n\t\t\treturn '@OneToOne';\n\t\t}\n\n\t\tif (prop.kind === ReferenceKind.MANY_TO_ONE) {\n\t\t\treturn '@ManyToOne';\n\t\t}\n\n\t\tif (prop.kind === ReferenceKind.ONE_TO_MANY) {\n\t\t\treturn '@OneToMany';\n\t\t}\n\n\t\tif (prop.kind === ReferenceKind.MANY_TO_MANY) {\n\t\t\treturn '@ManyToMany';\n\t\t}\n\n\t\tif (prop.primary) {\n\t\t\treturn '@PrimaryKey';\n\t\t}\n\n\t\tif (prop.enum) {\n\t\t\treturn '@Enum';\n\t\t}\n\n\t\treturn '@Property';\n\t}\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAiCA,kBAAkD;AAClD,uBAAyB;AAEzB,mBAAwC;AAEjC,MAAM,uBAAuB,0BAAS;AAAA,EAI5C,YACoB,MACA,gBACA,UACA,cAClB;AACD,UAAM,MAAM,gBAAgB,QAAQ;AALjB;AACA;AACA;AACA;AAPpB,SAAmB,cAAc,oBAAI,IAA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AAC;AAAA,IACpF;AAAA,EACD;AAAA,EAEU,6BAA6B,SAAqB,MAAsB;AACjF,SAAK,cAAc,IAAI,KAAK,IAAI;AAChC,YAAQ,SAAS,SAAS,KAAK,IAAI;AACnC,YAAQ,WAAW,KAAK,MAAM,KAAK,QAAQ;AAAA,EAC5C;AAAA,EAEU,8BAA8B,SAAqB,MAAsB;AAClF,SAAK,cAAc,IAAI,KAAK,IAAI;AAChC,YAAQ,SAAS,SAAS,KAAK,IAAI;AAEnC,QAAI,KAAK,KAAK;AACb,cAAQ,MAAM;AAAA,IACf;AAEA,QAAI,KAAK,UAAU;AAClB,cAAQ,WAAW,KAAK,MAAM,KAAK,QAAQ;AAC3C;AAAA,IACD;AAEA,QACC,KAAK,WAAW,CAAC,MACjB,KAAK,eAAe,kBAAkB,KAAK,MAAM,KAAK,sBAAsB,CAAC,CAAC,GAC7E;AACD,cAAQ,YAAY,KAAK,MAAM,KAAK,WAAW,CAAC,CAAC;AAAA,IAClD;AAEA,QAAI,KAAK,SAAS;AACjB,cAAQ,UAAU;AAAA,IACnB;AAAA,EACD;AAAA,EAEU,iBAAiB,MAA8B;AACxD,QAAI,KAAK,SAAS,0BAAc,YAAY;AAC3C,aAAO;AAAA,IACR;AAEA,QAAI,KAAK,SAAS,0BAAc,aAAa;AAC5C,aAAO;AAAA,IACR;AAEA,QAAI,KAAK,SAAS,0BAAc,aAAa;AAC5C,aAAO;AAAA,IACR;AAEA,QAAI,KAAK,SAAS,0BAAc,cAAc;AAC7C,aAAO;AAAA,IACR;AAEA,QAAI,KAAK,SAAS;AACjB,aAAO;AAAA,IACR;AAEA,QAAI,KAAK,MAAM;AACd,aAAO;AAAA,IACR;AAEA,WAAO;AAAA,EACR;AACD;",
4
+ "sourcesContent": ["// This file is a modified version of source from MikroORM, located here:\n// https://github.com/mikro-orm/mikro-orm/blob/6ba3d4004deef00b754a4ca2011cf64e44a4a3a3/packages/entity-generator/src/SourceFile.ts\n//\n// MIT License\n//\n// Copyright (c) 2018 Martin Ad\u00E1mek\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\nimport type {\n\tDictionary,\n\tEntityMetadata,\n\tEntityOptions,\n\tEntityProperty,\n\tNamingStrategy,\n\tPlatform,\n} from '@mikro-orm/core';\nimport { ReferenceKind, UnknownType, Utils } from '@mikro-orm/core';\nimport { BaseFile } from './base-file';\nimport { DatabaseType } from '../../database';\nimport { identifierForEnumValue, pascalToKebabCaseString } from '../utils';\n\nexport class DataEntityFile extends BaseFile {\n\tprotected readonly coreImports = new Set<string>();\n\tprotected readonly entityImports = new Set<string>();\n\n\tconstructor(\n\t\tprotected readonly meta: EntityMetadata,\n\t\tprotected readonly namingStrategy: NamingStrategy,\n\t\tprotected readonly platform: Platform,\n\t\tprotected readonly databaseType: DatabaseType\n\t) {\n\t\tsuper(meta, namingStrategy, platform);\n\t}\n\n\tgetBasePath() {\n\t\treturn `backend/entities/${this.databaseType}/`;\n\t}\n\n\tgetBaseName() {\n\t\tconst fileName = pascalToKebabCaseString(this.meta.className);\n\t\treturn `${fileName}.ts`;\n\t}\n\n\tgenerate(): string {\n\t\tconst enumDefinitions: string[] = [];\n\t\tlet classBody = '';\n\t\tconst props = Object.values(this.meta.properties);\n\t\tprops.forEach((prop) => {\n\t\t\tconst decorator = this.getPropertyDecorator(prop);\n\t\t\tconst definition = this.getPropertyDefinition(prop);\n\n\t\t\tif (!classBody.endsWith('\\n\\n')) {\n\t\t\t\tclassBody += '\\n';\n\t\t\t}\n\n\t\t\tclassBody += decorator;\n\t\t\tclassBody += definition;\n\n\t\t\tif (props[props.length - 1] !== prop) classBody += '\\n';\n\n\t\t\tif (prop.enum) {\n\t\t\t\tconst enumClassName = this.namingStrategy.getClassName(\n\t\t\t\t\tthis.meta.collection + '_' + prop.fieldNames[0],\n\t\t\t\t\t'_'\n\t\t\t\t);\n\t\t\t\tenumDefinitions.push(this.getEnumClassDefinition(enumClassName, prop.items as string[]));\n\t\t\t}\n\t\t});\n\n\t\tlet file = ``;\n\n\t\tthis.coreImports.add('Entity');\n\t\tconst imports = [\n\t\t\t`import { ${[...this.coreImports].sort().join(', ')} } from '@mikro-orm/core';`,\n\t\t];\n\t\tconst entityImports = [...this.entityImports].filter((e) => e !== this.meta.className);\n\t\tentityImports.sort().forEach((entity) => {\n\t\t\timports.push(`import { ${entity} } from './${pascalToKebabCaseString(entity)}';`);\n\t\t});\n\n\t\tif (enumDefinitions.length) {\n\t\t\tfile += enumDefinitions.join('\\n');\n\t\t\tfile += '\\n';\n\t\t}\n\n\t\tfile += `@Entity(${this.getCollectionDecl()})\\n`;\n\t\tfile += `export class ${this.meta.className} {`;\n\n\t\tfile += `${classBody}}\\n`;\n\n\t\tfile = `${imports.join('\\n')}\\n\\n${file}`;\n\n\t\treturn file;\n\t}\n\n\tprotected getPropertyType(prop: EntityProperty): string {\n\t\tif ([ReferenceKind.ONE_TO_ONE, ReferenceKind.MANY_TO_ONE].includes(prop.kind)) {\n\t\t\treturn prop.type.charAt(0).toUpperCase() + prop.type.slice(1);\n\t\t}\n\n\t\tconst columnType = prop.columnTypes?.[0]?.toLowerCase();\n\n\t\tif (['jsonb', 'json', 'any'].includes(columnType)) {\n\t\t\treturn `Record<string, unknown>`;\n\t\t}\n\n\t\t// Mikro doesn't infer column types for some columns very well. We can augment.\n\t\tif (prop.type === 'unknown') {\n\t\t\tif (columnType?.startsWith('nvarchar(') || columnType?.startsWith('varchar(')) {\n\t\t\t\treturn 'string';\n\t\t\t}\n\t\t}\n\n\t\treturn prop.runtimeType;\n\t}\n\n\tprotected getPropertyDefinition(prop: EntityProperty): string {\n\t\tconst padding = '\\t';\n\n\t\tif ([ReferenceKind.ONE_TO_MANY, ReferenceKind.MANY_TO_MANY].includes(prop.kind)) {\n\t\t\tthis.coreImports.add('Collection');\n\t\t\tthis.entityImports.add(prop.type);\n\t\t\treturn `${padding}${prop.name} = new Collection<${prop.type}>(this);\\n`;\n\t\t}\n\n\t\t// string defaults are usually things like SQL functions, but can be also enums, for that `useDefault` should be true\n\t\tconst isEnumOrNonStringDefault = prop.enum || typeof prop.default !== 'string';\n\t\tconst useDefault = prop.default != null && isEnumOrNonStringDefault;\n\t\tconst optional = prop.nullable ? '?' : useDefault ? '' : '!';\n\n\t\tif (prop.ref) {\n\t\t\tthis.coreImports.add('Ref');\n\t\t\tthis.entityImports.add(prop.type);\n\t\t\treturn `${padding}${prop.name}${optional}: Ref<${prop.type}>;\\n`;\n\t\t}\n\n\t\tconst file = `${prop.name}${optional}: ${this.getPropertyType(prop)}`;\n\n\t\tif (!useDefault) {\n\t\t\treturn `${padding + file};\\n`;\n\t\t}\n\n\t\tif (prop.enum && typeof prop.default === 'string') {\n\t\t\treturn `${padding}${file} = ${prop.runtimeType}.${identifierForEnumValue(prop.default)};\\n`;\n\t\t}\n\n\t\treturn `${padding}${prop.name} = ${prop.default};\\n`;\n\t}\n\n\tprotected getEnumClassDefinition(enumClassName: string, enumValues: string[]): string {\n\t\tconst padding = '\\t';\n\t\tlet file = `export enum ${enumClassName} {\\n`;\n\n\t\tfor (const enumValue of enumValues) {\n\t\t\tfile += `${padding}${identifierForEnumValue(enumValue)} = '${enumValue}',\\n`;\n\t\t}\n\n\t\tfile += '}\\n';\n\n\t\treturn file;\n\t}\n\n\tprivate getCollectionDecl() {\n\t\tconst options: EntityOptions<unknown> = {};\n\n\t\toptions.tableName = this.quote(this.meta.collection);\n\n\t\tif (this.meta.schema && this.meta.schema !== this.platform.getDefaultSchemaName()) {\n\t\t\toptions.schema = this.quote(this.meta.schema);\n\t\t}\n\n\t\tif (!Utils.hasObjectKeys(options)) {\n\t\t\treturn '';\n\t\t}\n\n\t\treturn `{ ${Object.entries(options)\n\t\t\t.map(([opt, val]) => `${opt}: ${val}`)\n\t\t\t.join(', ')} }`;\n\t}\n\n\tprivate getPropertyDecorator(prop: EntityProperty): string {\n\t\tconst padding = '\\t';\n\t\tconst options = {} as Dictionary;\n\t\tlet decorator = this.getDecoratorType(prop);\n\t\tthis.coreImports.add(decorator.substring(1));\n\n\t\tif (prop.kind === ReferenceKind.MANY_TO_MANY) {\n\t\t\tthis.getManyToManyDecoratorOptions(options, prop);\n\t\t} else if (prop.kind === ReferenceKind.ONE_TO_MANY) {\n\t\t\tthis.getOneToManyDecoratorOptions(options, prop);\n\t\t} else if (prop.kind !== ReferenceKind.SCALAR) {\n\t\t\tthis.getForeignKeyDecoratorOptions(options, prop);\n\t\t} else {\n\t\t\tthis.getScalarPropertyDecoratorOptions(options, prop);\n\t\t}\n\n\t\tif (prop.enum) {\n\t\t\toptions.items = `() => ${prop.runtimeType}`;\n\t\t}\n\n\t\tthis.getCommonDecoratorOptions(options, prop);\n\t\tconst indexes = this.getPropertyIndexes(prop, options);\n\t\tdecorator = [...indexes.sort(), decorator].map((d) => padding + d).join('\\n');\n\n\t\tif (!Utils.hasObjectKeys(options)) {\n\t\t\treturn `${decorator}()\\n`;\n\t\t}\n\n\t\treturn `${decorator}({ ${Object.entries(options)\n\t\t\t.map(([opt, val]) => `${opt}: ${val}`)\n\t\t\t.join(', ')} })\\n`;\n\t}\n\n\tprotected getPropertyIndexes(prop: EntityProperty, options: Dictionary): string[] {\n\t\tif (prop.kind === ReferenceKind.SCALAR) {\n\t\t\tconst ret: string[] = [];\n\n\t\t\tif (prop.index) {\n\t\t\t\tthis.coreImports.add('Index');\n\t\t\t\tret.push(`@Index({ name: '${prop.index}' })`);\n\t\t\t}\n\n\t\t\tif (prop.unique) {\n\t\t\t\tthis.coreImports.add('Unique');\n\t\t\t\tret.push(`@Unique({ name: '${prop.unique}' })`);\n\t\t\t}\n\n\t\t\treturn ret;\n\t\t}\n\n\t\tconst processIndex = (type: 'index' | 'unique') => {\n\t\t\tif (!prop[type]) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst defaultName = this.platform.getIndexName(this.meta.collection, prop.fieldNames, type);\n\t\t\toptions[type] = defaultName === prop[type] ? 'true' : `'${prop[type]}'`;\n\t\t\tconst expected = {\n\t\t\t\tindex: this.platform.indexForeignKeys(),\n\t\t\t\tunique: prop.kind === ReferenceKind.ONE_TO_ONE,\n\t\t\t};\n\n\t\t\tif (expected[type] && options[type] === 'true') {\n\t\t\t\tdelete options[type];\n\t\t\t}\n\t\t};\n\n\t\tprocessIndex('index');\n\t\tprocessIndex('unique');\n\n\t\treturn [];\n\t}\n\n\tprotected getCommonDecoratorOptions(options: Dictionary, prop: EntityProperty): void {\n\t\tif (prop.nullable && !prop.mappedBy) {\n\t\t\toptions.nullable = true;\n\t\t}\n\n\t\tif (prop.default == null) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (typeof prop.default !== 'string') {\n\t\t\toptions.default = prop.default;\n\t\t\treturn;\n\t\t}\n\n\t\tif ([`''`, ''].includes(prop.default)) {\n\t\t\toptions.default = `''`;\n\t\t} else if (prop.defaultRaw === this.quote(prop.default)) {\n\t\t\toptions.default = this.quote(prop.default);\n\t\t} else {\n\t\t\toptions.defaultRaw = `\\`${prop.default}\\``;\n\t\t}\n\t}\n\n\tprotected getScalarPropertyDecoratorOptions(options: Dictionary, prop: EntityProperty): void {\n\t\tlet t = prop.type.toLowerCase();\n\n\t\tif (t === 'date') {\n\t\t\tt = 'datetime';\n\t\t}\n\n\t\tif (prop.fieldNames[0] !== this.namingStrategy.propertyToColumnName(prop.name)) {\n\t\t\toptions.fieldName = `'${prop.fieldNames[0]}'`;\n\t\t}\n\n\t\t// for enum properties, we don't need a column type or the property length\n\t\t// in the decorator so return early.\n\t\tif (prop.enum) {\n\t\t\toptions.type = this.quote('string');\n\t\t\treturn;\n\t\t}\n\n\t\tconst mappedType1 = this.platform.getMappedType(t);\n\t\tconst mappedType2 = this.platform.getMappedType(prop.columnTypes[0]);\n\t\tconst columnType1 = mappedType1.getColumnType({ ...prop, autoincrement: false }, this.platform);\n\t\tconst columnType2 = mappedType2.getColumnType({ ...prop, autoincrement: false }, this.platform);\n\n\t\tif (\n\t\t\tcolumnType1 !== columnType2 ||\n\t\t\t[mappedType1, mappedType2].some((t) => t instanceof UnknownType)\n\t\t) {\n\t\t\toptions.type = this.quote(prop.columnTypes[0]);\n\t\t} else {\n\t\t\toptions.type = this.quote(prop.type);\n\t\t}\n\n\t\tif (prop.length) {\n\t\t\toptions.length = prop.length;\n\t\t}\n\t}\n\n\tprotected getManyToManyDecoratorOptions(options: Dictionary, prop: EntityProperty) {\n\t\tthis.entityImports.add(prop.type);\n\t\toptions.entity = `() => ${prop.type}`;\n\n\t\tif (prop.mappedBy) {\n\t\t\toptions.mappedBy = this.quote(prop.mappedBy);\n\t\t\treturn;\n\t\t}\n\n\t\tif (\n\t\t\tprop.pivotTable !==\n\t\t\tthis.namingStrategy.joinTableName(this.meta.collection, prop.type, prop.name)\n\t\t) {\n\t\t\toptions.pivotTable = this.quote(prop.pivotTable);\n\t\t}\n\n\t\tif (prop.joinColumns.length === 1) {\n\t\t\toptions.joinColumn = this.quote(prop.joinColumns[0]);\n\t\t} else {\n\t\t\toptions.joinColumns = `[${prop.joinColumns.map(this.quote).join(', ')}]`;\n\t\t}\n\n\t\tif (prop.inverseJoinColumns.length === 1) {\n\t\t\toptions.inverseJoinColumn = this.quote(prop.inverseJoinColumns[0]);\n\t\t} else {\n\t\t\toptions.inverseJoinColumns = `[${prop.inverseJoinColumns.map(this.quote).join(', ')}]`;\n\t\t}\n\t}\n\n\tprotected getOneToManyDecoratorOptions(options: Dictionary, prop: EntityProperty) {\n\t\tthis.entityImports.add(prop.type);\n\t\toptions.entity = `() => ${prop.type}`;\n\t\toptions.mappedBy = this.quote(prop.mappedBy);\n\t}\n\n\tprotected getForeignKeyDecoratorOptions(options: Dictionary, prop: EntityProperty) {\n\t\tthis.entityImports.add(prop.type);\n\t\toptions.entity = `() => ${prop.type}`;\n\n\t\tif (prop.ref) {\n\t\t\toptions.ref = true;\n\t\t}\n\n\t\tif (prop.mappedBy) {\n\t\t\toptions.mappedBy = this.quote(prop.mappedBy);\n\t\t\treturn;\n\t\t}\n\n\t\tif (\n\t\t\tprop.fieldNames[0] !==\n\t\t\tthis.namingStrategy.joinKeyColumnName(prop.name, prop.referencedColumnNames[0])\n\t\t) {\n\t\t\toptions.fieldName = this.quote(prop.fieldNames[0]);\n\t\t}\n\n\t\tif (prop.primary) {\n\t\t\toptions.primary = true;\n\t\t}\n\t}\n\n\tprotected getDecoratorType(prop: EntityProperty): string {\n\t\tif (prop.kind === ReferenceKind.ONE_TO_ONE) {\n\t\t\treturn '@OneToOne';\n\t\t}\n\n\t\tif (prop.kind === ReferenceKind.MANY_TO_ONE) {\n\t\t\treturn '@ManyToOne';\n\t\t}\n\n\t\tif (prop.kind === ReferenceKind.ONE_TO_MANY) {\n\t\t\treturn '@OneToMany';\n\t\t}\n\n\t\tif (prop.kind === ReferenceKind.MANY_TO_MANY) {\n\t\t\treturn '@ManyToMany';\n\t\t}\n\n\t\tif (prop.primary) {\n\t\t\treturn '@PrimaryKey';\n\t\t}\n\n\t\tif (prop.enum) {\n\t\t\treturn '@Enum';\n\t\t}\n\n\t\treturn '@Property';\n\t}\n}\n"],
5
+ "mappings": ";;;;;;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AAA,IACR;AAEA,QAAI,KAAK,SAAS,0BAAc,aAAa;AAC5C,aAAO;AAAA,IACR;AAEA,QAAI,KAAK,SAAS,0BAAc,cAAc;AAC7C,aAAO;AAAA,IACR;AAEA,QAAI,KAAK,SAAS;AACjB,aAAO;AAAA,IACR;AAEA,QAAI,KAAK,MAAM;AACd,aAAO;AAAA,IACR;AAEA,WAAO;AAAA,EACR;AACD;",
6
6
  "names": ["t"]
7
7
  }
@@ -112,6 +112,9 @@ ${file}`;
112
112
  return file;
113
113
  }
114
114
  getTypescriptPropertyType(prop) {
115
+ if ([import_core.ReferenceKind.ONE_TO_ONE, import_core.ReferenceKind.MANY_TO_ONE].includes(prop.kind)) {
116
+ return prop.type.charAt(0).toUpperCase() + prop.type.slice(1);
117
+ }
115
118
  if (["jsonb", "json", "any"].includes(prop.columnTypes?.[0])) {
116
119
  return `Record<string, unknown>`;
117
120
  }
@@ -121,7 +124,7 @@ ${file}`;
121
124
  if (prop.type === "unknown") {
122
125
  return "string";
123
126
  }
124
- return prop.type;
127
+ return prop.runtimeType;
125
128
  }
126
129
  getPropertyDefinition(prop) {
127
130
  const padding = " ";
@@ -139,46 +142,58 @@ ${file}`;
139
142
  `;
140
143
  }
141
144
  if (prop.enum && typeof prop.default === "string") {
142
- return `${padding}${file} = ${prop.type}.${prop.default.toUpperCase()};
145
+ return `${padding}${file} = ${prop.runtimeType}.${(0, import_utils.identifierForEnumValue)(prop.default)};
143
146
  `;
144
147
  }
145
148
  return `${padding}${prop.name} = ${prop.default};
146
149
  `;
147
150
  }
148
151
  getEnumClassDefinition(enumClassName) {
149
- this.coreImports.add("registerEnumType");
152
+ this.coreImports.add("graphweaverMetadata");
150
153
  this.enumImports.add(enumClassName);
151
- return `registerEnumType(${enumClassName}, { name: ${this.quote(enumClassName)} });`;
154
+ return `graphweaverMetadata.collectEnumInformation({ target: ${enumClassName}, name: ${this.quote(enumClassName)} });`;
152
155
  }
153
156
  getGraphQLPropertyType(prop) {
154
157
  if (prop.primary) {
155
158
  this.coreImports.add("ID");
156
159
  return "ID";
157
160
  }
158
- if (prop.type === "Date") {
161
+ if (prop.runtimeType === "Date") {
159
162
  this.scalarImports.add("ISODateStringScalar");
160
163
  return "ISODateStringScalar";
161
164
  }
162
165
  if (prop.columnTypes?.[0] === "date") {
163
166
  return "Date";
164
167
  }
165
- if (prop.type === "unknown") {
168
+ if (prop.runtimeType === "unknown") {
166
169
  return "String";
167
170
  }
171
+ if (prop.runtimeType === "bigint") {
172
+ this.scalarImports.add("GraphQLBigInt");
173
+ return "GraphQLBigInt";
174
+ }
168
175
  if (["jsonb", "json", "any"].includes(prop.columnTypes?.[0])) {
169
176
  this.scalarImports.add("GraphQLJSON");
170
177
  return `GraphQLJSON`;
171
178
  }
172
- if (prop.type.includes("[]")) {
179
+ if (prop.runtimeType?.includes("[]")) {
173
180
  return `[${prop.type.charAt(0).toUpperCase() + prop.type.slice(1).replace("[]", "")}]`;
174
181
  }
182
+ if ([import_core.ReferenceKind.ONE_TO_ONE, import_core.ReferenceKind.MANY_TO_ONE].includes(prop.kind)) {
183
+ return prop.type.charAt(0).toUpperCase() + prop.type.slice(1);
184
+ }
175
185
  if ([import_core.ReferenceKind.MANY_TO_MANY, import_core.ReferenceKind.ONE_TO_MANY].includes(prop.kind)) {
176
186
  return `[${prop.type.charAt(0).toUpperCase() + prop.type.slice(1).replace("[]", "")}]`;
177
187
  }
178
188
  if (prop.pivotTable) {
179
189
  return `[${prop.type.charAt(0).toUpperCase() + prop.type.slice(1)}]`;
180
190
  }
181
- return prop.type.charAt(0).toUpperCase() + prop.type.slice(1);
191
+ const lastChanceType = prop.runtimeType ?? prop.type;
192
+ if (!lastChanceType) {
193
+ console.error(`Property is malformed, it has no type or runtimeType:`, prop);
194
+ throw new Error(`Property ${prop.name} on ${prop.entity} entity has no type or runtimeType.`);
195
+ }
196
+ return lastChanceType.charAt(0).toUpperCase() + lastChanceType.slice(1);
182
197
  }
183
198
  getPropertyDecorator(prop) {
184
199
  const padding = " ";
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/introspection/files/schema-entity-file.ts"],
4
- "sourcesContent": ["import type {\n\tDictionary,\n\tEntityMetadata,\n\tEntityProperty,\n\tNamingStrategy,\n\tPlatform,\n} from '@mikro-orm/core';\nimport { ReferenceKind, Utils } from '@mikro-orm/core';\n\nimport { BaseFile } from './base-file';\nimport { pascalToCamelCaseString, pascalToKebabCaseString } from '../utils';\nimport pluralize from 'pluralize';\n\nexport class SchemaEntityFile extends BaseFile {\n\tprotected readonly coreImports = new Set<string>();\n\tprotected readonly scalarImports = new Set<string>();\n\tprotected readonly entityImports = new Set<string>();\n\tprotected readonly enumImports = new Set<string>();\n\n\tconstructor(\n\t\tprotected readonly meta: EntityMetadata,\n\t\tprotected readonly namingStrategy: NamingStrategy,\n\t\tprotected readonly platform: Platform,\n\t\tprotected readonly entityLookup: Map<string, EntityMetadata<any>>\n\t) {\n\t\tsuper(meta, namingStrategy, platform);\n\t}\n\n\tgetBasePath() {\n\t\treturn `backend/schema/`;\n\t}\n\n\tgetBaseName() {\n\t\tconst fileName = pascalToKebabCaseString(this.meta.className);\n\t\treturn `${fileName}.ts`;\n\t}\n\n\tgenerate(): string {\n\t\tconst enumDefinitions: string[] = [];\n\t\tlet classBody = '';\n\t\tconst props = Object.values(this.meta.properties);\n\t\tprops.forEach((prop) => {\n\t\t\tconst decorator = this.getPropertyDecorator(prop);\n\t\t\tconst definition = this.getPropertyDefinition(prop);\n\n\t\t\tif (classBody && !classBody.endsWith('\\n\\n')) {\n\t\t\t\tclassBody += '\\n';\n\t\t\t}\n\n\t\t\tclassBody += decorator;\n\t\t\tclassBody += definition;\n\n\t\t\tif (props[props.length - 1] !== prop) classBody += '\\n';\n\n\t\t\tif (prop.enum) {\n\t\t\t\tconst enumClassName = this.namingStrategy.getClassName(\n\t\t\t\t\tthis.meta.collection + '_' + prop.fieldNames[0],\n\t\t\t\t\t'_'\n\t\t\t\t);\n\t\t\t\tenumDefinitions.push(this.getEnumClassDefinition(enumClassName));\n\t\t\t}\n\t\t});\n\n\t\tlet file = '';\n\n\t\tif (enumDefinitions.length) {\n\t\t\tfile += enumDefinitions.join('\\n');\n\t\t\tfile += '\\n\\n';\n\t\t}\n\n\t\tthis.coreImports.add('Entity');\n\t\tfile += `@Entity<${this.meta.className}>(${this.quote(this.meta.className)}, {\\n\\tprovider: new MikroBackendProvider(Orm${this.meta.className}, connection),\\n})\\n`;\n\t\tfile += `export class ${this.meta.className} {\\n`;\n\t\tfile += `${classBody}}\\n`;\n\t\tconst imports = [\n\t\t\t`import { ${[...this.coreImports].sort().join(', ')} } from '@exogee/graphweaver';`,\n\t\t];\n\n\t\tif (this.scalarImports.size > 0) {\n\t\t\timports.push(\n\t\t\t\t`import { ${[...this.scalarImports]\n\t\t\t\t\t.sort()\n\t\t\t\t\t.join(', ')} } from '@exogee/graphweaver-scalars';`\n\t\t\t);\n\t\t}\n\n\t\timports.push(`import { MikroBackendProvider } from '@exogee/graphweaver-mikroorm';`);\n\n\t\tconst entityImports = [...this.entityImports].filter((e) => e !== this.meta.className);\n\t\tentityImports.sort().forEach((entity) => {\n\t\t\timports.push(`import { ${entity} } from './${pascalToKebabCaseString(entity)}';`);\n\t\t});\n\n\t\timports.push(\n\t\t\t`import { ${this.enumImports.size > 0 ? [...this.enumImports].sort().join(', ') + ', ' : ''}${\n\t\t\t\tthis.meta.className\n\t\t\t} as Orm${this.meta.className} } from '../entities';`,\n\t\t\t`import { connection } from '../database';`\n\t\t);\n\n\t\tfile = `${imports.join('\\n')}\\n\\n${file}`;\n\n\t\treturn file;\n\t}\n\n\tprotected getTypescriptPropertyType(prop: EntityProperty): string {\n\t\tif (['jsonb', 'json', 'any'].includes(prop.columnTypes?.[0])) {\n\t\t\treturn `Record<string, unknown>`;\n\t\t}\n\n\t\tif (prop.columnTypes?.[0] === 'date') {\n\t\t\treturn 'Date';\n\t\t}\n\n\t\tif (prop.type === 'unknown') {\n\t\t\t//fallback to string if unknown\n\t\t\treturn 'string';\n\t\t}\n\n\t\treturn prop.type;\n\t}\n\n\tprotected getPropertyDefinition(prop: EntityProperty): string {\n\t\tconst padding = '\\t';\n\n\t\tif ([ReferenceKind.ONE_TO_MANY, ReferenceKind.MANY_TO_MANY].includes(prop.kind)) {\n\t\t\tthis.entityImports.add(prop.type);\n\t\t\treturn `${padding}${prop.name}!: ${prop.type}[];\\n`;\n\t\t}\n\n\t\t// string defaults are usually things like SQL functions, but can be also enums, for that `useDefault` should be true\n\t\tconst isEnumOrNonStringDefault = prop.enum || typeof prop.default !== 'string';\n\t\tconst useDefault = prop.default != null && isEnumOrNonStringDefault;\n\t\tconst optional = prop.nullable ? '?' : useDefault ? '' : '!';\n\n\t\tconst file = `${prop.name}${optional}: ${this.getTypescriptPropertyType(prop)}`;\n\n\t\tif (!useDefault) {\n\t\t\treturn `${padding + file};\\n`;\n\t\t}\n\n\t\tif (prop.enum && typeof prop.default === 'string') {\n\t\t\treturn `${padding}${file} = ${prop.type}.${prop.default.toUpperCase()};\\n`;\n\t\t}\n\n\t\treturn `${padding}${prop.name} = ${prop.default};\\n`;\n\t}\n\n\tprotected getEnumClassDefinition(enumClassName: string): string {\n\t\tthis.coreImports.add('registerEnumType');\n\t\tthis.enumImports.add(enumClassName);\n\t\treturn `registerEnumType(${enumClassName}, { name: ${this.quote(enumClassName)} });`;\n\t}\n\n\tprivate getGraphQLPropertyType(prop: EntityProperty): string {\n\t\tif (prop.primary) {\n\t\t\tthis.coreImports.add('ID');\n\t\t\treturn 'ID';\n\t\t}\n\n\t\tif (prop.type === 'Date') {\n\t\t\tthis.scalarImports.add('ISODateStringScalar');\n\t\t\treturn 'ISODateStringScalar';\n\t\t}\n\n\t\tif (prop.columnTypes?.[0] === 'date') {\n\t\t\treturn 'Date';\n\t\t}\n\n\t\tif (prop.type === 'unknown') {\n\t\t\treturn 'String';\n\t\t}\n\n\t\tif (['jsonb', 'json', 'any'].includes(prop.columnTypes?.[0])) {\n\t\t\tthis.scalarImports.add('GraphQLJSON');\n\t\t\treturn `GraphQLJSON`;\n\t\t}\n\n\t\tif (prop.type.includes('[]')) {\n\t\t\treturn `[${prop.type.charAt(0).toUpperCase() + prop.type.slice(1).replace('[]', '')}]`;\n\t\t}\n\n\t\tif ([ReferenceKind.MANY_TO_MANY, ReferenceKind.ONE_TO_MANY].includes(prop.kind)) {\n\t\t\treturn `[${prop.type.charAt(0).toUpperCase() + prop.type.slice(1).replace('[]', '')}]`;\n\t\t}\n\n\t\tif (prop.pivotTable) {\n\t\t\treturn `[${prop.type.charAt(0).toUpperCase() + prop.type.slice(1)}]`;\n\t\t}\n\n\t\treturn prop.type.charAt(0).toUpperCase() + prop.type.slice(1);\n\t}\n\n\tprivate getPropertyDecorator(prop: EntityProperty): string {\n\t\tconst padding = '\\t';\n\t\tconst options = {} as Dictionary;\n\t\tlet decorator = this.getDecoratorType(prop);\n\n\t\tif (prop.kind === ReferenceKind.MANY_TO_MANY) {\n\t\t\tthis.getManyToManyDecoratorOptions(options, prop);\n\t\t} else if (prop.kind === ReferenceKind.ONE_TO_MANY) {\n\t\t\tthis.getOneToManyDecoratorOptions(options, prop);\n\t\t} else if (prop.kind !== ReferenceKind.SCALAR) {\n\t\t\tthis.getForeignKeyDecoratorOptions(options, prop);\n\t\t}\n\n\t\tthis.getCommonDecoratorOptions(options, prop);\n\t\tdecorator = [decorator].map((d) => padding + d).join('\\n');\n\n\t\tif (!Utils.hasObjectKeys(options)) {\n\t\t\treturn `${decorator}(() => ${this.getGraphQLPropertyType(prop)})\\n`;\n\t\t}\n\n\t\treturn `${decorator}(() => ${this.getGraphQLPropertyType(prop)}, { ${Object.entries(options)\n\t\t\t.map(([opt, val]) => `${opt}: ${JSON.stringify(val).replaceAll('\"', '')}`)\n\t\t\t.join(', ')} })\\n`;\n\t}\n\n\tprotected getCommonDecoratorOptions(options: Dictionary, prop: EntityProperty): void {\n\t\tif (prop.nullable && !prop.mappedBy) {\n\t\t\toptions.nullable = true;\n\t\t}\n\n\t\tif (prop.primary) {\n\t\t\toptions.primaryKeyField = true;\n\t\t}\n\n\t\t// If there's a property called 'name' it should be the summary field. If not, and there's a field called 'title'\n\t\t// then it should be the summary field.\n\t\tif (prop.name === 'name') {\n\t\t\toptions.adminUIOptions = { summaryField: true };\n\t\t} else if (prop.name === 'title' && !this.meta.props.find((prop) => prop.name === 'name')) {\n\t\t\toptions.adminUIOptions = { summaryField: true };\n\t\t}\n\t}\n\n\tprotected getManyToManyDecoratorOptions(options: Dictionary, prop: EntityProperty) {\n\t\tthis.entityImports.add(prop.type);\n\t\toptions.relatedField = this.quote(pluralize(pascalToCamelCaseString(this.meta.className)));\n\t}\n\n\tprotected getOneToManyDecoratorOptions(options: Dictionary, prop: EntityProperty) {\n\t\tthis.entityImports.add(prop.type);\n\t\toptions.relatedField = this.quote(prop.mappedBy);\n\t}\n\n\tprotected getForeignKeyDecoratorOptions(options: Dictionary, prop: EntityProperty) {\n\t\tthis.entityImports.add(prop.type);\n\n\t\tconst relatedEntity = this.entityLookup.get(prop.type);\n\t\tif (!relatedEntity) {\n\t\t\tthrow new Error(\n\t\t\t\t`Internal Error: Related entity ${prop.type} should exist but could not be found in the entity lookup.`\n\t\t\t);\n\t\t}\n\t\tif (relatedEntity.primaryKeys.length !== 1) {\n\t\t\tthrow new Error(`Composite primary keys are not supported.`);\n\t\t}\n\t\tconst [primaryKey] = relatedEntity.getPrimaryProps();\n\n\t\toptions.id = `(entity) => entity.${prop.name}?.${primaryKey.name}`;\n\t}\n\n\tprotected getDecoratorType(prop: EntityProperty): string {\n\t\tif ([ReferenceKind.ONE_TO_ONE, ReferenceKind.MANY_TO_ONE].includes(prop.kind)) {\n\t\t\tthis.coreImports.add('RelationshipField');\n\t\t\treturn `@RelationshipField<${this.meta.className}>`;\n\t\t}\n\n\t\tif ([ReferenceKind.ONE_TO_MANY, ReferenceKind.MANY_TO_MANY].includes(prop.kind)) {\n\t\t\tthis.coreImports.add('RelationshipField');\n\t\t\treturn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,IAAI,KAAK,IAAI;AAEhC,UAAM,gBAAgB,KAAK,aAAa,IAAI,KAAK,IAAI;AACrD,QAAI,CAAC,eAAe;AACnB,YAAM,IAAI;AAAA,QACT,kCAAkC,KAAK,IAAI;AAAA,MAC5C;AAAA,IACD;AACA,QAAI,cAAc,YAAY,WAAW,GAAG;AAC3C,YAAM,IAAI,MAAM,2CAA2C;AAAA,IAC5D;AACA,UAAM,CAAC,UAAU,IAAI,cAAc,gBAAgB;AAEnD,YAAQ,KAAK,sBAAsB,KAAK,IAAI,KAAK,WAAW,IAAI;AAAA,EACjE;AAAA,EAEU,iBAAiB,MAA8B;AACxD,QAAI,CAAC,0BAAc,YAAY,0BAAc,WAAW,EAAE,SAAS,KAAK,IAAI,GAAG;AAC9E,WAAK,YAAY,IAAI,mBAAmB;AACxC,aAAO,sBAAsB,KAAK,KAAK,SAAS;AAAA,IACjD;AAEA,QAAI,CAAC,0BAAc,aAAa,0BAAc,YAAY,EAAE,SAAS,KAAK,IAAI,GAAG;AAChF,WAAK,YAAY,IAAI,mBAAmB;AACxC,aAAO,sBAAsB,KAAK,IAAI;AAAA,IACvC;AAEA,SAAK,YAAY,IAAI,OAAO;AAC5B,WAAO;AAAA,EACR;AACD;",
4
+ "sourcesContent": ["import type {\n\tDictionary,\n\tEntityMetadata,\n\tEntityProperty,\n\tNamingStrategy,\n\tPlatform,\n} from '@mikro-orm/core';\nimport { ReferenceKind, Utils } from '@mikro-orm/core';\n\nimport { BaseFile } from './base-file';\nimport { identifierForEnumValue, pascalToCamelCaseString, pascalToKebabCaseString } from '../utils';\nimport pluralize from 'pluralize';\n\nexport class SchemaEntityFile extends BaseFile {\n\tprotected readonly coreImports = new Set<string>();\n\tprotected readonly scalarImports = new Set<string>();\n\tprotected readonly entityImports = new Set<string>();\n\tprotected readonly enumImports = new Set<string>();\n\n\tconstructor(\n\t\tprotected readonly meta: EntityMetadata,\n\t\tprotected readonly namingStrategy: NamingStrategy,\n\t\tprotected readonly platform: Platform,\n\t\tprotected readonly entityLookup: Map<string, EntityMetadata<any>>\n\t) {\n\t\tsuper(meta, namingStrategy, platform);\n\t}\n\n\tgetBasePath() {\n\t\treturn `backend/schema/`;\n\t}\n\n\tgetBaseName() {\n\t\tconst fileName = pascalToKebabCaseString(this.meta.className);\n\t\treturn `${fileName}.ts`;\n\t}\n\n\tgenerate(): string {\n\t\tconst enumDefinitions: string[] = [];\n\t\tlet classBody = '';\n\t\tconst props = Object.values(this.meta.properties);\n\t\tprops.forEach((prop) => {\n\t\t\tconst decorator = this.getPropertyDecorator(prop);\n\t\t\tconst definition = this.getPropertyDefinition(prop);\n\n\t\t\tif (classBody && !classBody.endsWith('\\n\\n')) {\n\t\t\t\tclassBody += '\\n';\n\t\t\t}\n\n\t\t\tclassBody += decorator;\n\t\t\tclassBody += definition;\n\n\t\t\tif (props[props.length - 1] !== prop) classBody += '\\n';\n\n\t\t\tif (prop.enum) {\n\t\t\t\tconst enumClassName = this.namingStrategy.getClassName(\n\t\t\t\t\tthis.meta.collection + '_' + prop.fieldNames[0],\n\t\t\t\t\t'_'\n\t\t\t\t);\n\t\t\t\tenumDefinitions.push(this.getEnumClassDefinition(enumClassName));\n\t\t\t}\n\t\t});\n\n\t\tlet file = '';\n\n\t\tif (enumDefinitions.length) {\n\t\t\tfile += enumDefinitions.join('\\n');\n\t\t\tfile += '\\n\\n';\n\t\t}\n\n\t\tthis.coreImports.add('Entity');\n\t\tfile += `@Entity<${this.meta.className}>(${this.quote(this.meta.className)}, {\\n\\tprovider: new MikroBackendProvider(Orm${this.meta.className}, connection),\\n})\\n`;\n\t\tfile += `export class ${this.meta.className} {\\n`;\n\t\tfile += `${classBody}}\\n`;\n\t\tconst imports = [\n\t\t\t`import { ${[...this.coreImports].sort().join(', ')} } from '@exogee/graphweaver';`,\n\t\t];\n\n\t\tif (this.scalarImports.size > 0) {\n\t\t\timports.push(\n\t\t\t\t`import { ${[...this.scalarImports]\n\t\t\t\t\t.sort()\n\t\t\t\t\t.join(', ')} } from '@exogee/graphweaver-scalars';`\n\t\t\t);\n\t\t}\n\n\t\timports.push(`import { MikroBackendProvider } from '@exogee/graphweaver-mikroorm';`);\n\n\t\tconst entityImports = [...this.entityImports].filter((e) => e !== this.meta.className);\n\t\tentityImports.sort().forEach((entity) => {\n\t\t\timports.push(`import { ${entity} } from './${pascalToKebabCaseString(entity)}';`);\n\t\t});\n\n\t\timports.push(\n\t\t\t`import { ${this.enumImports.size > 0 ? [...this.enumImports].sort().join(', ') + ', ' : ''}${\n\t\t\t\tthis.meta.className\n\t\t\t} as Orm${this.meta.className} } from '../entities';`,\n\t\t\t`import { connection } from '../database';`\n\t\t);\n\n\t\tfile = `${imports.join('\\n')}\\n\\n${file}`;\n\n\t\treturn file;\n\t}\n\n\tprotected getTypescriptPropertyType(prop: EntityProperty): string {\n\t\tif ([ReferenceKind.ONE_TO_ONE, ReferenceKind.MANY_TO_ONE].includes(prop.kind)) {\n\t\t\treturn prop.type.charAt(0).toUpperCase() + prop.type.slice(1);\n\t\t}\n\n\t\tif (['jsonb', 'json', 'any'].includes(prop.columnTypes?.[0])) {\n\t\t\treturn `Record<string, unknown>`;\n\t\t}\n\n\t\tif (prop.columnTypes?.[0] === 'date') {\n\t\t\treturn 'Date';\n\t\t}\n\n\t\tif (prop.type === 'unknown') {\n\t\t\t//fallback to string if unknown\n\t\t\treturn 'string';\n\t\t}\n\n\t\treturn prop.runtimeType;\n\t}\n\n\tprotected getPropertyDefinition(prop: EntityProperty): string {\n\t\tconst padding = '\\t';\n\n\t\tif ([ReferenceKind.ONE_TO_MANY, ReferenceKind.MANY_TO_MANY].includes(prop.kind)) {\n\t\t\tthis.entityImports.add(prop.type);\n\t\t\treturn `${padding}${prop.name}!: ${prop.type}[];\\n`;\n\t\t}\n\n\t\t// string defaults are usually things like SQL functions, but can be also enums, for that `useDefault` should be true\n\t\tconst isEnumOrNonStringDefault = prop.enum || typeof prop.default !== 'string';\n\t\tconst useDefault = prop.default != null && isEnumOrNonStringDefault;\n\t\tconst optional = prop.nullable ? '?' : useDefault ? '' : '!';\n\n\t\tconst file = `${prop.name}${optional}: ${this.getTypescriptPropertyType(prop)}`;\n\n\t\tif (!useDefault) {\n\t\t\treturn `${padding + file};\\n`;\n\t\t}\n\n\t\tif (prop.enum && typeof prop.default === 'string') {\n\t\t\treturn `${padding}${file} = ${prop.runtimeType}.${identifierForEnumValue(prop.default)};\\n`;\n\t\t}\n\n\t\treturn `${padding}${prop.name} = ${prop.default};\\n`;\n\t}\n\n\tprotected getEnumClassDefinition(enumClassName: string): string {\n\t\tthis.coreImports.add('graphweaverMetadata');\n\t\tthis.enumImports.add(enumClassName);\n\t\treturn `graphweaverMetadata.collectEnumInformation({ target: ${enumClassName}, name: ${this.quote(enumClassName)} });`;\n\t}\n\n\tprivate getGraphQLPropertyType(prop: EntityProperty): string {\n\t\tif (prop.primary) {\n\t\t\tthis.coreImports.add('ID');\n\t\t\treturn 'ID';\n\t\t}\n\n\t\tif (prop.runtimeType === 'Date') {\n\t\t\tthis.scalarImports.add('ISODateStringScalar');\n\t\t\treturn 'ISODateStringScalar';\n\t\t}\n\n\t\tif (prop.columnTypes?.[0] === 'date') {\n\t\t\treturn 'Date';\n\t\t}\n\n\t\tif (prop.runtimeType === 'unknown') {\n\t\t\treturn 'String';\n\t\t}\n\n\t\tif (prop.runtimeType === 'bigint') {\n\t\t\tthis.scalarImports.add('GraphQLBigInt');\n\t\t\treturn 'GraphQLBigInt';\n\t\t}\n\n\t\tif (['jsonb', 'json', 'any'].includes(prop.columnTypes?.[0])) {\n\t\t\tthis.scalarImports.add('GraphQLJSON');\n\t\t\treturn `GraphQLJSON`;\n\t\t}\n\n\t\tif (prop.runtimeType?.includes('[]')) {\n\t\t\treturn `[${prop.type.charAt(0).toUpperCase() + prop.type.slice(1).replace('[]', '')}]`;\n\t\t}\n\n\t\tif ([ReferenceKind.ONE_TO_ONE, ReferenceKind.MANY_TO_ONE].includes(prop.kind)) {\n\t\t\treturn prop.type.charAt(0).toUpperCase() + prop.type.slice(1);\n\t\t}\n\n\t\tif ([ReferenceKind.MANY_TO_MANY, ReferenceKind.ONE_TO_MANY].includes(prop.kind)) {\n\t\t\treturn `[${prop.type.charAt(0).toUpperCase() + prop.type.slice(1).replace('[]', '')}]`;\n\t\t}\n\n\t\tif (prop.pivotTable) {\n\t\t\treturn `[${prop.type.charAt(0).toUpperCase() + prop.type.slice(1)}]`;\n\t\t}\n\n\t\tconst lastChanceType = prop.runtimeType ?? prop.type;\n\n\t\tif (!lastChanceType) {\n\t\t\tconsole.error(`Property is malformed, it has no type or runtimeType:`, prop);\n\t\t\tthrow new Error(`Property ${prop.name} on ${prop.entity} entity has no type or runtimeType.`);\n\t\t}\n\n\t\treturn lastChanceType.charAt(0).toUpperCase() + lastChanceType.slice(1);\n\t}\n\n\tprivate getPropertyDecorator(prop: EntityProperty): string {\n\t\tconst padding = '\\t';\n\t\tconst options = {} as Dictionary;\n\t\tlet decorator = this.getDecoratorType(prop);\n\n\t\tif (prop.kind === ReferenceKind.MANY_TO_MANY) {\n\t\t\tthis.getManyToManyDecoratorOptions(options, prop);\n\t\t} else if (prop.kind === ReferenceKind.ONE_TO_MANY) {\n\t\t\tthis.getOneToManyDecoratorOptions(options, prop);\n\t\t} else if (prop.kind !== ReferenceKind.SCALAR) {\n\t\t\tthis.getForeignKeyDecoratorOptions(options, prop);\n\t\t}\n\n\t\tthis.getCommonDecoratorOptions(options, prop);\n\t\tdecorator = [decorator].map((d) => padding + d).join('\\n');\n\n\t\tif (!Utils.hasObjectKeys(options)) {\n\t\t\treturn `${decorator}(() => ${this.getGraphQLPropertyType(prop)})\\n`;\n\t\t}\n\n\t\treturn `${decorator}(() => ${this.getGraphQLPropertyType(prop)}, { ${Object.entries(options)\n\t\t\t.map(([opt, val]) => `${opt}: ${JSON.stringify(val).replaceAll('\"', '')}`)\n\t\t\t.join(', ')} })\\n`;\n\t}\n\n\tprotected getCommonDecoratorOptions(options: Dictionary, prop: EntityProperty): void {\n\t\tif (prop.nullable && !prop.mappedBy) {\n\t\t\toptions.nullable = true;\n\t\t}\n\n\t\tif (prop.primary) {\n\t\t\toptions.primaryKeyField = true;\n\t\t}\n\n\t\t// If there's a property called 'name' it should be the summary field. If not, and there's a field called 'title'\n\t\t// then it should be the summary field.\n\t\tif (prop.name === 'name') {\n\t\t\toptions.adminUIOptions = { summaryField: true };\n\t\t} else if (prop.name === 'title' && !this.meta.props.find((prop) => prop.name === 'name')) {\n\t\t\toptions.adminUIOptions = { summaryField: true };\n\t\t}\n\t}\n\n\tprotected getManyToManyDecoratorOptions(options: Dictionary, prop: EntityProperty) {\n\t\tthis.entityImports.add(prop.type);\n\t\toptions.relatedField = this.quote(pluralize(pascalToCamelCaseString(this.meta.className)));\n\t}\n\n\tprotected getOneToManyDecoratorOptions(options: Dictionary, prop: EntityProperty) {\n\t\tthis.entityImports.add(prop.type);\n\t\toptions.relatedField = this.quote(prop.mappedBy);\n\t}\n\n\tprotected getForeignKeyDecoratorOptions(options: Dictionary, prop: EntityProperty) {\n\t\tthis.entityImports.add(prop.type);\n\n\t\tconst relatedEntity = this.entityLookup.get(prop.type);\n\t\tif (!relatedEntity) {\n\t\t\tthrow new Error(\n\t\t\t\t`Internal Error: Related entity ${prop.type} should exist but could not be found in the entity lookup.`\n\t\t\t);\n\t\t}\n\t\tif (relatedEntity.primaryKeys.length !== 1) {\n\t\t\tthrow new Error(`Composite primary keys are not supported.`);\n\t\t}\n\t\tconst [primaryKey] = relatedEntity.getPrimaryProps();\n\n\t\toptions.id = `(entity) => entity.${prop.name}?.${primaryKey.name}`;\n\t}\n\n\tprotected getDecoratorType(prop: EntityProperty): string {\n\t\tif ([ReferenceKind.ONE_TO_ONE, ReferenceKind.MANY_TO_ONE].includes(prop.kind)) {\n\t\t\tthis.coreImports.add('RelationshipField');\n\t\t\treturn `@RelationshipField<${this.meta.className}>`;\n\t\t}\n\n\t\tif ([ReferenceKind.ONE_TO_MANY, ReferenceKind.MANY_TO_MANY].includes(prop.kind)) {\n\t\t\tthis.coreImports.add('RelationshipField');\n\t\t\treturn `@RelationshipField<${prop.type}>`;\n\t\t}\n\n\t\tthis.coreImports.add('Field');\n\t\treturn '@Field';\n\t}\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAOA,kBAAqC;AAErC,uBAAyB;AACzB,mBAAyF;AACzF,uBAAsB;AAEf,MAAM,yBAAyB,0BAAS;AAAA,EAM9C,YACoB,MACA,gBACA,UACA,cAClB;AACD,UAAM,MAAM,gBAAgB,QAAQ;AALjB;AACA;AACA;AACA;AATpB,SAAmB,cAAc,oBAAI,IAAY;AACjD,SAAmB,gBAAgB,oBAAI,IAAY;AACnD,SAAmB,gBAAgB,oBAAI,IAAY;AACnD,SAAmB,cAAc,oBAAI,IAAY;AAAA,EASjD;AAAA,EAEA,cAAc;AACb,WAAO;AAAA,EACR;AAAA,EAEA,cAAc;AACb,UAAM,eAAW,sCAAwB,KAAK,KAAK,SAAS;AAC5D,WAAO,GAAG,QAAQ;AAAA,EACnB;AAAA,EAEA,WAAmB;AAClB,UAAM,kBAA4B,CAAC;AACnC,QAAI,YAAY;AAChB,UAAM,QAAQ,OAAO,OAAO,KAAK,KAAK,UAAU;AAChD,UAAM,QAAQ,CAAC,SAAS;AACvB,YAAM,YAAY,KAAK,qBAAqB,IAAI;AAChD,YAAM,aAAa,KAAK,sBAAsB,IAAI;AAElD,UAAI,aAAa,CAAC,UAAU,SAAS,MAAM,GAAG;AAC7C,qBAAa;AAAA,MACd;AAEA,mBAAa;AACb,mBAAa;AAEb,UAAI,MAAM,MAAM,SAAS,CAAC,MAAM,KAAM,cAAa;AAEnD,UAAI,KAAK,MAAM;AACd,cAAM,gBAAgB,KAAK,eAAe;AAAA,UACzC,KAAK,KAAK,aAAa,MAAM,KAAK,WAAW,CAAC;AAAA,UAC9C;AAAA,QACD;AACA,wBAAgB,KAAK,KAAK,uBAAuB,aAAa,CAAC;AAAA,MA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AAE,SAAS,KAAK,IAAI,GAAG;AAChF,WAAK,YAAY,IAAI,mBAAmB;AACxC,aAAO,sBAAsB,KAAK,IAAI;AAAA,IACvC;AAEA,SAAK,YAAY,IAAI,OAAO;AAC5B,WAAO;AAAA,EACR;AACD;",
6
6
  "names": ["prop", "pluralize"]
7
7
  }
@@ -254,6 +254,8 @@ Imported ${summaryOfEntities.length} entities, creating the above files in your
254
254
  return files;
255
255
  } catch (err) {
256
256
  if (err instanceof IntrospectionError) throw err;
257
+ console.error("Got error during introspection:");
258
+ console.error(err);
257
259
  throw new IntrospectionError(
258
260
  `Warning: Unable to connect to database.`,
259
261
  hasErrorMessage(err) ? err.message : "Please check the connection settings and try again"
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/introspection/generate.ts"],
4
- "sourcesContent": ["import { DatabaseSchema, AbstractSqlPlatform, DatabaseTable } from '@mikro-orm/knex';\nimport {\n\tEntityMetadata,\n\tEntityProperty,\n\tNamingStrategy,\n\tReferenceKind,\n\tUtils,\n} from '@mikro-orm/core';\nimport pluralize from 'pluralize';\n\nimport { ConnectionManager, ConnectionOptions, DatabaseType } from '../database';\nimport {\n\tDataEntityFile,\n\tDataEntityIndexFile,\n\tDataSourceIndexFile,\n\tSchemaEntityFile,\n\tSchemaIndexFile,\n\tDatabaseFile,\n} from './files';\nimport { pascalToCamelCaseString } from './utils';\n\nconst CONNECTION_MANAGER_ID = 'generate';\n\nexport class IntrospectionError extends Error {\n\tprotected type: string;\n\tconstructor(\n\t\tprotected title = '',\n\t\tmessage = ''\n\t) {\n\t\tsuper(message);\n\t\tthis.type = 'IntrospectionError';\n\t\tthis.title = title;\n\t\tthis.message = message;\n\t}\n}\n\nconst hasErrorMessage = (error: any): error is { message: string } => error.message;\n\nconst generateBidirectionalRelations = (metadata: EntityMetadata[]): void => {\n\tfor (const meta of metadata.filter((m) => !m.pivotTable)) {\n\t\tfor (const prop of meta.relations) {\n\t\t\tif (!prop.name.includes('Inverse')) {\n\t\t\t\tconst targetMeta = metadata.find((m) => m.className === prop.type);\n\t\t\t\tconst newProp = {\n\t\t\t\t\tname: prop.name + 'Inverse',\n\t\t\t\t\ttype: meta.className,\n\t\t\t\t\tjoinColumns: prop.fieldNames,\n\t\t\t\t\treferencedTableName: meta.tableName,\n\t\t\t\t\treferencedColumnNames: Utils.flatten(\n\t\t\t\t\t\t(targetMeta?.getPrimaryProps() ?? []).map((pk) => pk.fieldNames)\n\t\t\t\t\t),\n\t\t\t\t\tmappedBy: prop.name,\n\t\t\t\t} as EntityProperty;\n\n\t\t\t\t// Add reference to the inverse entity\n\t\t\t\tconst inverseMeta = metadata.find((m) => m.className === meta.className);\n\t\t\t\tconst inverseProp = inverseMeta?.props.find((p) => p.name === newProp.mappedBy);\n\t\t\t\tif (inverseProp) inverseProp.inversedBy = newProp.name;\n\n\t\t\t\tif (prop.kind === ReferenceKind.MANY_TO_ONE) {\n\t\t\t\t\tconst name = pascalToCamelCaseString(meta.className);\n\t\t\t\t\tnewProp.name = pluralize(name);\n\t\t\t\t\tnewProp.kind = ReferenceKind.ONE_TO_MANY;\n\t\t\t\t} else if (prop.kind === ReferenceKind.ONE_TO_ONE && !prop.mappedBy) {\n\t\t\t\t\tnewProp.kind = ReferenceKind.ONE_TO_ONE;\n\t\t\t\t\tnewProp.nullable = true;\n\t\t\t\t} else if (prop.kind === ReferenceKind.MANY_TO_MANY && !prop.mappedBy) {\n\t\t\t\t\tconst name = pascalToCamelCaseString(meta.className);\n\t\t\t\t\tnewProp.name = pluralize(name);\n\t\t\t\t\tnewProp.kind = ReferenceKind.MANY_TO_MANY;\n\t\t\t\t} else {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\ttargetMeta?.addProperty(newProp);\n\t\t\t}\n\t\t}\n\t}\n};\n\nconst detectManyToManyRelations = (metadata: EntityMetadata[]) => {\n\tfor (const meta of metadata) {\n\t\tif (\n\t\t\tmeta.compositePK && // needs to have composite PK\n\t\t\tmeta.primaryKeys.length === meta.relations.length && // all relations are PKs\n\t\t\tmeta.relations.length === 2 && // there are exactly two relation properties\n\t\t\tmeta.relations.length === meta.props.length && // all properties are relations\n\t\t\tmeta.relations.every((prop) => prop.kind === ReferenceKind.MANY_TO_ONE) // all relations are m:1\n\t\t) {\n\t\t\tmeta.pivotTable = true;\n\t\t\tconst owner = metadata.find((m) => m.className === meta.relations[0].type);\n\t\t\tif (!owner) throw new Error('No Owner');\n\t\t\tconst name = pascalToCamelCaseString(meta.relations?.[1]?.type);\n\t\t\towner.addProperty({\n\t\t\t\tname: pluralize(name),\n\t\t\t\tkind: ReferenceKind.MANY_TO_MANY,\n\t\t\t\tpivotTable: meta.tableName,\n\t\t\t\ttype: meta.relations[1].type,\n\t\t\t\tjoinColumns: meta.relations[0].fieldNames,\n\t\t\t\tinverseJoinColumns: meta.relations[1].fieldNames,\n\t\t\t} as EntityProperty);\n\t\t}\n\t}\n};\n\nconst generateIdentifiedReferences = (metadata: EntityMetadata[]): void => {\n\tfor (const meta of metadata.filter((m) => !m.pivotTable)) {\n\t\tfor (const prop of meta.relations) {\n\t\t\tif ([ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind)) {\n\t\t\t\tconst name = pascalToCamelCaseString(prop.type);\n\t\t\t\tprop.name = pluralize.singular(name);\n\t\t\t\tprop.ref = true;\n\t\t\t}\n\t\t}\n\t}\n};\n\nconst generateSingularTypeReferences = (metadata: EntityMetadata[]): void => {\n\tfor (const meta of metadata.filter((m) => !m.pivotTable)) {\n\t\tmeta.className = pluralize.singular(meta.className);\n\t\tfor (const prop of meta.relations) {\n\t\t\tprop.type = pluralize.singular(prop.type);\n\t\t}\n\t}\n};\n\n// Convert properties like FirstName to firstName\nconst convertToCamelCasePropertyNames = (metadata: EntityMetadata[]): void => {\n\tfor (const meta of metadata.filter((m) => !m.pivotTable)) {\n\t\tconst props = Object.values(meta.properties);\n\t\tprops.forEach((prop) => {\n\t\t\tprop.name = pascalToCamelCaseString(prop.name);\n\t\t});\n\t}\n};\n\nconst assertUniqueForeignKeys = (table: DatabaseTable): void => {\n\tconst uniqueForeignKeys = new Set();\n\tconst definedForeignKeys = Object.values(table.getForeignKeys());\n\n\tfor (const foreignKey of definedForeignKeys) {\n\t\tconst { localTableName, referencedTableName, columnNames, referencedColumnNames } = foreignKey;\n\t\tconst serializedValue = JSON.stringify({\n\t\t\tlocalTableName,\n\t\t\tcolumnNames: columnNames.sort(),\n\t\t\treferencedTableName,\n\t\t\treferencedColumnNames: referencedColumnNames.sort(),\n\t\t});\n\n\t\tif (uniqueForeignKeys.has(serializedValue)) {\n\t\t\tthrow new Error(\n\t\t\t\t`\\n\\nImport Failed: Duplicate foreign keys detected on column/s (${columnNames.toString()}) in table \"${\n\t\t\t\t\ttable.name\n\t\t\t\t}\".`\n\t\t\t);\n\t\t}\n\n\t\tuniqueForeignKeys.add(serializedValue);\n\t}\n};\n\nconst convertSchemaToMetadata = async (\n\tschema: DatabaseSchema,\n\tplatform: AbstractSqlPlatform,\n\tnamingStrategy: NamingStrategy\n) => {\n\tconst helper = platform.getSchemaHelper();\n\n\tif (!helper) throw new Error('cannot connect to database');\n\n\tconst metadata = schema\n\t\t.getTables()\n\t\t.sort((a, b) => a.name.localeCompare(b.name))\n\t\t.map((table) => {\n\t\t\tassertUniqueForeignKeys(table);\n\t\t\treturn table.getEntityDeclaration(namingStrategy, helper, 'never');\n\t\t});\n\n\tif (metadata.length === 0) {\n\t\tthrow new IntrospectionError(\n\t\t\t`Warning: No tables found, this database is empty.`,\n\t\t\t`Make sure you have tables in this database and then try again.`\n\t\t);\n\t}\n\n\tconvertToCamelCasePropertyNames(metadata);\n\tdetectManyToManyRelations(metadata);\n\tgenerateIdentifiedReferences(metadata);\n\tgenerateBidirectionalRelations(metadata);\n\tgenerateSingularTypeReferences(metadata);\n\n\treturn metadata;\n};\n\nconst openConnection = async (type: DatabaseType, options: ConnectionOptions) => {\n\t// eslint-disable-next-line @typescript-eslint/no-var-requires\n\tconst module = require(`@mikro-orm/${type}`);\n\tconst PLATFORMS = {\n\t\tmysql: 'MySqlDriver',\n\t\tpostgresql: 'PostgreSqlDriver',\n\t\tsqlite: 'SqliteDriver',\n\t};\n\tawait ConnectionManager.connect(CONNECTION_MANAGER_ID, {\n\t\tmikroOrmConfig: {\n\t\t\tdriver: module[PLATFORMS[type]],\n\t\t\t...options.mikroOrmConfig,\n\t\t},\n\t});\n};\n\nconst closeConnection = async () => {\n\tconsole.log('Closing database connection...');\n\tawait ConnectionManager.close(CONNECTION_MANAGER_ID);\n\tconsole.log('Database connection closed.');\n};\n\ntype File =\n\t| DataEntityFile\n\t| SchemaEntityFile\n\t| SchemaIndexFile\n\t| DataEntityIndexFile\n\t| DataSourceIndexFile\n\t| DatabaseFile;\n\nexport const generate = async (databaseType: DatabaseType, options: ConnectionOptions) => {\n\ttry {\n\t\tawait openConnection(databaseType, options);\n\n\t\tconst database = ConnectionManager.database(CONNECTION_MANAGER_ID);\n\t\tif (!database)\n\t\t\tthrow new IntrospectionError(\n\t\t\t\t`Warning: Unable to connect to database.`,\n\t\t\t\t'Please check the connection settings and try again'\n\t\t\t);\n\n\t\tconst config = database.em.config;\n\t\tconst driver = database.em.getDriver();\n\t\tconst platform = driver.getPlatform();\n\t\tconst namingStrategy = config.getNamingStrategy();\n\t\tconst connection = driver.getConnection();\n\n\t\tconsole.log('Fetching database schema...');\n\t\tconst schema = await DatabaseSchema.create(connection, platform, config);\n\t\tconsole.log('Building metadata...');\n\t\tconst metadata = await convertSchemaToMetadata(schema, platform, namingStrategy);\n\n\t\t// Build a lookup for efficient cross-referencing later.\n\t\tconst entityLookup = new Map<string, EntityMetadata<any>>();\n\t\tfor (const meta of metadata) {\n\t\t\tentityLookup.set(meta.className, meta);\n\t\t}\n\n\t\tconst source: File[] = [];\n\n\t\tconst summaryOfEntities: { name: string; entityFilePath: string; schemaFilePath: string }[] =\n\t\t\t[];\n\n\t\tfor (const meta of metadata) {\n\t\t\tif (!meta.pivotTable) {\n\t\t\t\tconst dataEntityFile = new DataEntityFile(meta, namingStrategy, platform, databaseType);\n\t\t\t\tconst schemaEntityFile = new SchemaEntityFile(meta, namingStrategy, platform, entityLookup);\n\t\t\t\tsource.push(dataEntityFile, schemaEntityFile);\n\t\t\t\tsummaryOfEntities.push({\n\t\t\t\t\tname: meta.className,\n\t\t\t\t\tentityFilePath: `${dataEntityFile.getBasePath()}${dataEntityFile.getBaseName()}`,\n\t\t\t\t\tschemaFilePath: `${schemaEntityFile.getBasePath()}${schemaEntityFile.getBaseName()}`,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\t// Export all the entities from the data source directory\n\t\tsource.push(new DataEntityIndexFile(metadata, databaseType));\n\t\t// Export the data source from the entities directory\n\t\tsource.push(new DataSourceIndexFile(databaseType));\n\t\t// Export the data source from the entities directory\n\t\tsource.push(new SchemaIndexFile(metadata));\n\t\t// Export the database connection to its own file\n\t\tsource.push(new DatabaseFile(databaseType, options));\n\n\t\tconst files = source.map((file) => {\n\t\t\treturn {\n\t\t\t\tpath: file.getBasePath(),\n\t\t\t\tname: file.getBaseName(),\n\t\t\t\tcontents: file.generate(),\n\t\t\t\tneedOverwriteWarning: !![DatabaseFile, SchemaIndexFile].some((cls) => file instanceof cls),\n\t\t\t};\n\t\t});\n\n\t\tawait closeConnection();\n\n\t\tconsole.log('\\nImport Summary:');\n\t\tconsole.table(summaryOfEntities);\n\t\tconsole.log(\n\t\t\t`\\nImported ${summaryOfEntities.length} entities, creating the above files in your Graphweaver project. \\n`\n\t\t);\n\n\t\treturn files;\n\t} catch (err) {\n\t\tif (err instanceof IntrospectionError) throw err;\n\n\t\tthrow new IntrospectionError(\n\t\t\t`Warning: Unable to connect to database.`,\n\t\t\thasErrorMessage(err) ? err.message : 'Please check the connection settings and try again'\n\t\t);\n\t}\n};\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,kB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B,CAAC,CAAC,CAAC,2BAAc,4BAAe,EAAE,KAAK,CAAC,QAAQ,gBAAgB,GAAG;AAAA,MAC1F;AAAA,IACD,CAAC;AAED,UAAM,gBAAgB;AAEtB,YAAQ,IAAI,mBAAmB;AAC/B,YAAQ,MAAM,iBAAiB;AAC/B,YAAQ;AAAA,MACP;AAAA,WAAc,kBAAkB,MAAM;AAAA;AAAA,IACvC;AAEA,WAAO;AAAA,EACR,SAAS,KAAK;AACb,QAAI,eAAe,mBAAoB,OAAM;AAE7C,UAAM,IAAI;AAAA,MACT;AAAA,MACA,gBAAgB,GAAG,IAAI,IAAI,UAAU;AAAA,IACtC;AAAA,EACD;AACD;",
4
+ "sourcesContent": ["import { DatabaseSchema, AbstractSqlPlatform, DatabaseTable } from '@mikro-orm/knex';\nimport {\n\tEntityMetadata,\n\tEntityProperty,\n\tNamingStrategy,\n\tReferenceKind,\n\tUtils,\n} from '@mikro-orm/core';\nimport pluralize from 'pluralize';\n\nimport { ConnectionManager, ConnectionOptions, DatabaseType } from '../database';\nimport {\n\tDataEntityFile,\n\tDataEntityIndexFile,\n\tDataSourceIndexFile,\n\tSchemaEntityFile,\n\tSchemaIndexFile,\n\tDatabaseFile,\n} from './files';\nimport { pascalToCamelCaseString } from './utils';\n\nconst CONNECTION_MANAGER_ID = 'generate';\n\nexport class IntrospectionError extends Error {\n\tprotected type: string;\n\tconstructor(\n\t\tprotected title = '',\n\t\tmessage = ''\n\t) {\n\t\tsuper(message);\n\t\tthis.type = 'IntrospectionError';\n\t\tthis.title = title;\n\t\tthis.message = message;\n\t}\n}\n\nconst hasErrorMessage = (error: any): error is { message: string } => error.message;\n\nconst generateBidirectionalRelations = (metadata: EntityMetadata[]): void => {\n\tfor (const meta of metadata.filter((m) => !m.pivotTable)) {\n\t\tfor (const prop of meta.relations) {\n\t\t\tif (!prop.name.includes('Inverse')) {\n\t\t\t\tconst targetMeta = metadata.find((m) => m.className === prop.type);\n\t\t\t\tconst newProp = {\n\t\t\t\t\tname: prop.name + 'Inverse',\n\t\t\t\t\ttype: meta.className,\n\t\t\t\t\tjoinColumns: prop.fieldNames,\n\t\t\t\t\treferencedTableName: meta.tableName,\n\t\t\t\t\treferencedColumnNames: Utils.flatten(\n\t\t\t\t\t\t(targetMeta?.getPrimaryProps() ?? []).map((pk) => pk.fieldNames)\n\t\t\t\t\t),\n\t\t\t\t\tmappedBy: prop.name,\n\t\t\t\t} as EntityProperty;\n\n\t\t\t\t// Add reference to the inverse entity\n\t\t\t\tconst inverseMeta = metadata.find((m) => m.className === meta.className);\n\t\t\t\tconst inverseProp = inverseMeta?.props.find((p) => p.name === newProp.mappedBy);\n\t\t\t\tif (inverseProp) inverseProp.inversedBy = newProp.name;\n\n\t\t\t\tif (prop.kind === ReferenceKind.MANY_TO_ONE) {\n\t\t\t\t\tconst name = pascalToCamelCaseString(meta.className);\n\t\t\t\t\tnewProp.name = pluralize(name);\n\t\t\t\t\tnewProp.kind = ReferenceKind.ONE_TO_MANY;\n\t\t\t\t} else if (prop.kind === ReferenceKind.ONE_TO_ONE && !prop.mappedBy) {\n\t\t\t\t\tnewProp.kind = ReferenceKind.ONE_TO_ONE;\n\t\t\t\t\tnewProp.nullable = true;\n\t\t\t\t} else if (prop.kind === ReferenceKind.MANY_TO_MANY && !prop.mappedBy) {\n\t\t\t\t\tconst name = pascalToCamelCaseString(meta.className);\n\t\t\t\t\tnewProp.name = pluralize(name);\n\t\t\t\t\tnewProp.kind = ReferenceKind.MANY_TO_MANY;\n\t\t\t\t} else {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\ttargetMeta?.addProperty(newProp);\n\t\t\t}\n\t\t}\n\t}\n};\n\nconst detectManyToManyRelations = (metadata: EntityMetadata[]) => {\n\tfor (const meta of metadata) {\n\t\tif (\n\t\t\tmeta.compositePK && // needs to have composite PK\n\t\t\tmeta.primaryKeys.length === meta.relations.length && // all relations are PKs\n\t\t\tmeta.relations.length === 2 && // there are exactly two relation properties\n\t\t\tmeta.relations.length === meta.props.length && // all properties are relations\n\t\t\tmeta.relations.every((prop) => prop.kind === ReferenceKind.MANY_TO_ONE) // all relations are m:1\n\t\t) {\n\t\t\tmeta.pivotTable = true;\n\t\t\tconst owner = metadata.find((m) => m.className === meta.relations[0].type);\n\t\t\tif (!owner) throw new Error('No Owner');\n\t\t\tconst name = pascalToCamelCaseString(meta.relations?.[1]?.type);\n\t\t\towner.addProperty({\n\t\t\t\tname: pluralize(name),\n\t\t\t\tkind: ReferenceKind.MANY_TO_MANY,\n\t\t\t\tpivotTable: meta.tableName,\n\t\t\t\ttype: meta.relations[1].type,\n\t\t\t\tjoinColumns: meta.relations[0].fieldNames,\n\t\t\t\tinverseJoinColumns: meta.relations[1].fieldNames,\n\t\t\t} as EntityProperty);\n\t\t}\n\t}\n};\n\nconst generateIdentifiedReferences = (metadata: EntityMetadata[]): void => {\n\tfor (const meta of metadata.filter((m) => !m.pivotTable)) {\n\t\tfor (const prop of meta.relations) {\n\t\t\tif ([ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind)) {\n\t\t\t\tconst name = pascalToCamelCaseString(prop.type);\n\t\t\t\tprop.name = pluralize.singular(name);\n\t\t\t\tprop.ref = true;\n\t\t\t}\n\t\t}\n\t}\n};\n\nconst generateSingularTypeReferences = (metadata: EntityMetadata[]): void => {\n\tfor (const meta of metadata.filter((m) => !m.pivotTable)) {\n\t\tmeta.className = pluralize.singular(meta.className);\n\t\tfor (const prop of meta.relations) {\n\t\t\tprop.type = pluralize.singular(prop.type);\n\t\t}\n\t}\n};\n\n// Convert properties like FirstName to firstName\nconst convertToCamelCasePropertyNames = (metadata: EntityMetadata[]): void => {\n\tfor (const meta of metadata.filter((m) => !m.pivotTable)) {\n\t\tconst props = Object.values(meta.properties);\n\t\tprops.forEach((prop) => {\n\t\t\tprop.name = pascalToCamelCaseString(prop.name);\n\t\t});\n\t}\n};\n\nconst assertUniqueForeignKeys = (table: DatabaseTable): void => {\n\tconst uniqueForeignKeys = new Set();\n\tconst definedForeignKeys = Object.values(table.getForeignKeys());\n\n\tfor (const foreignKey of definedForeignKeys) {\n\t\tconst { localTableName, referencedTableName, columnNames, referencedColumnNames } = foreignKey;\n\t\tconst serializedValue = JSON.stringify({\n\t\t\tlocalTableName,\n\t\t\tcolumnNames: columnNames.sort(),\n\t\t\treferencedTableName,\n\t\t\treferencedColumnNames: referencedColumnNames.sort(),\n\t\t});\n\n\t\tif (uniqueForeignKeys.has(serializedValue)) {\n\t\t\tthrow new Error(\n\t\t\t\t`\\n\\nImport Failed: Duplicate foreign keys detected on column/s (${columnNames.toString()}) in table \"${\n\t\t\t\t\ttable.name\n\t\t\t\t}\".`\n\t\t\t);\n\t\t}\n\n\t\tuniqueForeignKeys.add(serializedValue);\n\t}\n};\n\nconst convertSchemaToMetadata = async (\n\tschema: DatabaseSchema,\n\tplatform: AbstractSqlPlatform,\n\tnamingStrategy: NamingStrategy\n) => {\n\tconst helper = platform.getSchemaHelper();\n\n\tif (!helper) throw new Error('cannot connect to database');\n\n\tconst metadata = schema\n\t\t.getTables()\n\t\t.sort((a, b) => a.name.localeCompare(b.name))\n\t\t.map((table) => {\n\t\t\tassertUniqueForeignKeys(table);\n\t\t\treturn table.getEntityDeclaration(namingStrategy, helper, 'never');\n\t\t});\n\n\tif (metadata.length === 0) {\n\t\tthrow new IntrospectionError(\n\t\t\t`Warning: No tables found, this database is empty.`,\n\t\t\t`Make sure you have tables in this database and then try again.`\n\t\t);\n\t}\n\n\tconvertToCamelCasePropertyNames(metadata);\n\tdetectManyToManyRelations(metadata);\n\tgenerateIdentifiedReferences(metadata);\n\tgenerateBidirectionalRelations(metadata);\n\tgenerateSingularTypeReferences(metadata);\n\n\treturn metadata;\n};\n\nconst openConnection = async (type: DatabaseType, options: ConnectionOptions) => {\n\t// eslint-disable-next-line @typescript-eslint/no-var-requires\n\tconst module = require(`@mikro-orm/${type}`);\n\tconst PLATFORMS = {\n\t\tmysql: 'MySqlDriver',\n\t\tpostgresql: 'PostgreSqlDriver',\n\t\tsqlite: 'SqliteDriver',\n\t};\n\tawait ConnectionManager.connect(CONNECTION_MANAGER_ID, {\n\t\tmikroOrmConfig: {\n\t\t\tdriver: module[PLATFORMS[type]],\n\t\t\t...options.mikroOrmConfig,\n\t\t},\n\t});\n};\n\nconst closeConnection = async () => {\n\tconsole.log('Closing database connection...');\n\tawait ConnectionManager.close(CONNECTION_MANAGER_ID);\n\tconsole.log('Database connection closed.');\n};\n\ntype File =\n\t| DataEntityFile\n\t| SchemaEntityFile\n\t| SchemaIndexFile\n\t| DataEntityIndexFile\n\t| DataSourceIndexFile\n\t| DatabaseFile;\n\nexport const generate = async (databaseType: DatabaseType, options: ConnectionOptions) => {\n\ttry {\n\t\tawait openConnection(databaseType, options);\n\n\t\tconst database = ConnectionManager.database(CONNECTION_MANAGER_ID);\n\t\tif (!database)\n\t\t\tthrow new IntrospectionError(\n\t\t\t\t`Warning: Unable to connect to database.`,\n\t\t\t\t'Please check the connection settings and try again'\n\t\t\t);\n\n\t\tconst config = database.em.config;\n\t\tconst driver = database.em.getDriver();\n\t\tconst platform = driver.getPlatform();\n\t\tconst namingStrategy = config.getNamingStrategy();\n\t\tconst connection = driver.getConnection();\n\n\t\tconsole.log('Fetching database schema...');\n\t\tconst schema = await DatabaseSchema.create(connection, platform, config);\n\t\tconsole.log('Building metadata...');\n\t\tconst metadata = await convertSchemaToMetadata(schema, platform, namingStrategy);\n\n\t\t// Build a lookup for efficient cross-referencing later.\n\t\tconst entityLookup = new Map<string, EntityMetadata<any>>();\n\t\tfor (const meta of metadata) {\n\t\t\tentityLookup.set(meta.className, meta);\n\t\t}\n\n\t\tconst source: File[] = [];\n\n\t\tconst summaryOfEntities: { name: string; entityFilePath: string; schemaFilePath: string }[] =\n\t\t\t[];\n\n\t\tfor (const meta of metadata) {\n\t\t\tif (!meta.pivotTable) {\n\t\t\t\tconst dataEntityFile = new DataEntityFile(meta, namingStrategy, platform, databaseType);\n\t\t\t\tconst schemaEntityFile = new SchemaEntityFile(meta, namingStrategy, platform, entityLookup);\n\t\t\t\tsource.push(dataEntityFile, schemaEntityFile);\n\t\t\t\tsummaryOfEntities.push({\n\t\t\t\t\tname: meta.className,\n\t\t\t\t\tentityFilePath: `${dataEntityFile.getBasePath()}${dataEntityFile.getBaseName()}`,\n\t\t\t\t\tschemaFilePath: `${schemaEntityFile.getBasePath()}${schemaEntityFile.getBaseName()}`,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\t// Export all the entities from the data source directory\n\t\tsource.push(new DataEntityIndexFile(metadata, databaseType));\n\t\t// Export the data source from the entities directory\n\t\tsource.push(new DataSourceIndexFile(databaseType));\n\t\t// Export the data source from the entities directory\n\t\tsource.push(new SchemaIndexFile(metadata));\n\t\t// Export the database connection to its own file\n\t\tsource.push(new DatabaseFile(databaseType, options));\n\n\t\tconst files = source.map((file) => {\n\t\t\treturn {\n\t\t\t\tpath: file.getBasePath(),\n\t\t\t\tname: file.getBaseName(),\n\t\t\t\tcontents: file.generate(),\n\t\t\t\tneedOverwriteWarning: !![DatabaseFile, SchemaIndexFile].some((cls) => file instanceof cls),\n\t\t\t};\n\t\t});\n\n\t\tawait closeConnection();\n\n\t\tconsole.log('\\nImport Summary:');\n\t\tconsole.table(summaryOfEntities);\n\t\tconsole.log(\n\t\t\t`\\nImported ${summaryOfEntities.length} entities, creating the above files in your Graphweaver project. \\n`\n\t\t);\n\n\t\treturn files;\n\t} catch (err) {\n\t\tif (err instanceof IntrospectionError) throw err;\n\n\t\tconsole.error('Got error during introspection:');\n\t\tconsole.error(err);\n\n\t\tthrow new IntrospectionError(\n\t\t\t`Warning: Unable to connect to database.`,\n\t\t\thasErrorMessage(err) ? err.message : 'Please check the connection settings and try again'\n\t\t);\n\t}\n};\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,kBAAmE;AACnE,kBAMO;AACP,uBAAsB;AAEtB,s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KAAK,CAAC,QAAQ,gBAAgB,GAAG;AAAA,MAC1F;AAAA,IACD,CAAC;AAED,UAAM,gBAAgB;AAEtB,YAAQ,IAAI,mBAAmB;AAC/B,YAAQ,MAAM,iBAAiB;AAC/B,YAAQ;AAAA,MACP;AAAA,WAAc,kBAAkB,MAAM;AAAA;AAAA,IACvC;AAEA,WAAO;AAAA,EACR,SAAS,KAAK;AACb,QAAI,eAAe,mBAAoB,OAAM;AAE7C,YAAQ,MAAM,iCAAiC;AAC/C,YAAQ,MAAM,GAAG;AAEjB,UAAM,IAAI;AAAA,MACT;AAAA,MACA,gBAAgB,GAAG,IAAI,IAAI,UAAU;AAAA,IACtC;AAAA,EACD;AACD;",
6
6
  "names": ["pluralize", "module"]
7
7
  }
@@ -1,3 +1,4 @@
1
1
  export declare const pascalToKebabCaseString: (value: string) => string;
2
2
  export declare const snakeToCamelCaseString: (value: string) => string;
3
3
  export declare const pascalToCamelCaseString: (value: string) => string;
4
+ export declare const identifierForEnumValue: (value: string) => string;
@@ -18,6 +18,7 @@ var __copyProps = (to, from, except, desc) => {
18
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
19
  var utils_exports = {};
20
20
  __export(utils_exports, {
21
+ identifierForEnumValue: () => identifierForEnumValue,
21
22
  pascalToCamelCaseString: () => pascalToCamelCaseString,
22
23
  pascalToKebabCaseString: () => pascalToKebabCaseString,
23
24
  snakeToCamelCaseString: () => snakeToCamelCaseString
@@ -34,8 +35,10 @@ const pascalToCamelCaseString = (value) => {
34
35
  const restOfString = value.slice(1);
35
36
  return firstChar + restOfString;
36
37
  };
38
+ const identifierForEnumValue = (value) => value.replace(/[^a-z0-9_]/gi, "_").toUpperCase();
37
39
  // Annotate the CommonJS export names for ESM import in node:
38
40
  0 && (module.exports = {
41
+ identifierForEnumValue,
39
42
  pascalToCamelCaseString,
40
43
  pascalToKebabCaseString,
41
44
  snakeToCamelCaseString
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/introspection/utils.ts"],
4
- "sourcesContent": ["export const pascalToKebabCaseString = (value: string) => {\n\treturn value.replace(/([a-z0\u20139])([A-Z])/g, '$1-$2').toLowerCase();\n};\n\nexport const snakeToCamelCaseString = (value: string) => {\n\treturn value.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase());\n};\n\nexport const pascalToCamelCaseString = (value: string) => {\n\tconst firstChar = value.charAt(0).toLowerCase();\n\tconst restOfString = value.slice(1);\n\treturn firstChar + restOfString;\n};\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAO,MAAM,0BAA0B,CAAC,UAAkB;AACzD,SAAO,MAAM,QAAQ,sBAAsB,OAAO,EAAE,YAAY;AACjE;AAEO,MAAM,yBAAyB,CAAC,UAAkB;AACxD,SAAO,MAAM,QAAQ,aAAa,CAAC,GAAG,WAAW,OAAO,YAAY,CAAC;AACtE;AAEO,MAAM,0BAA0B,CAAC,UAAkB;AACzD,QAAM,YAAY,MAAM,OAAO,CAAC,EAAE,YAAY;AAC9C,QAAM,eAAe,MAAM,MAAM,CAAC;AAClC,SAAO,YAAY;AACpB;",
4
+ "sourcesContent": ["export const pascalToKebabCaseString = (value: string) => {\n\treturn value.replace(/([a-z0\u20139])([A-Z])/g, '$1-$2').toLowerCase();\n};\n\nexport const snakeToCamelCaseString = (value: string) => {\n\treturn value.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase());\n};\n\nexport const pascalToCamelCaseString = (value: string) => {\n\tconst firstChar = value.charAt(0).toLowerCase();\n\tconst restOfString = value.slice(1);\n\treturn firstChar + restOfString;\n};\n\n// Anything that is not alphanumeric or an underscore is replaced with an underscore, then the value is uppercased\nexport const identifierForEnumValue = (value: string) =>\n\tvalue.replace(/[^a-z0-9_]/gi, '_').toUpperCase();\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAO,MAAM,0BAA0B,CAAC,UAAkB;AACzD,SAAO,MAAM,QAAQ,sBAAsB,OAAO,EAAE,YAAY;AACjE;AAEO,MAAM,yBAAyB,CAAC,UAAkB;AACxD,SAAO,MAAM,QAAQ,aAAa,CAAC,GAAG,WAAW,OAAO,YAAY,CAAC;AACtE;AAEO,MAAM,0BAA0B,CAAC,UAAkB;AACzD,QAAM,YAAY,MAAM,OAAO,CAAC,EAAE,YAAY;AAC9C,QAAM,eAAe,MAAM,MAAM,CAAC;AAClC,SAAO,YAAY;AACpB;AAGO,MAAM,yBAAyB,CAAC,UACtC,MAAM,QAAQ,gBAAgB,GAAG,EAAE,YAAY;",
6
6
  "names": []
7
7
  }
@@ -1,2 +1 @@
1
- export { ClearDatabaseContext } from './clear-database-context';
2
1
  export { connectToDatabase } from './connect-to-database';
@@ -18,15 +18,12 @@ var __copyProps = (to, from, except, desc) => {
18
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
19
  var plugins_exports = {};
20
20
  __export(plugins_exports, {
21
- ClearDatabaseContext: () => import_clear_database_context.ClearDatabaseContext,
22
21
  connectToDatabase: () => import_connect_to_database.connectToDatabase
23
22
  });
24
23
  module.exports = __toCommonJS(plugins_exports);
25
- var import_clear_database_context = require("./clear-database-context");
26
24
  var import_connect_to_database = require("./connect-to-database");
27
25
  // Annotate the CommonJS export names for ESM import in node:
28
26
  0 && (module.exports = {
29
- ClearDatabaseContext,
30
27
  connectToDatabase
31
28
  });
32
29
  //# sourceMappingURL=index.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/plugins/index.ts"],
4
- "sourcesContent": ["export { ClearDatabaseContext } from './clear-database-context';\nexport { connectToDatabase } from './connect-to-database';\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oCAAqC;AACrC,iCAAkC;",
4
+ "sourcesContent": ["export { connectToDatabase } from './connect-to-database';\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,iCAAkC;",
6
6
  "names": []
7
7
  }
@@ -1,6 +1,5 @@
1
1
  import { BackendProvider, PaginationOptions, Filter, BackendProviderConfig, FieldMetadata, AggregationResult, AggregationType, TraceOptions } from '@exogee/graphweaver';
2
2
  import { IsolationLevel, ConnectionOptions } from '..';
3
- import { ApolloServerPlugin, BaseContext } from '@apollo/server';
4
3
  export declare const gqlToMikro: (filter: any) => any;
5
4
  export declare class MikroBackendProvider<D> implements BackendProvider<D> {
6
5
  private _backendId;
@@ -16,6 +15,8 @@ export declare class MikroBackendProvider<D> implements BackendProvider<D> {
16
15
  withTransaction<T>(callback: () => Promise<T>): Promise<T>;
17
16
  get em(): import("@mikro-orm/postgresql").EntityManager<import("@mikro-orm/postgresql").PostgreSqlDriver> | import("@mikro-orm/postgresql").EntityManager<import("@mikro-orm/mysql").MySqlDriver> | import("@mikro-orm/postgresql").EntityManager<import("@mikro-orm/sqlite").SqliteDriver>;
18
17
  constructor(mikroType: new () => D, connection: ConnectionOptions, transactionIsolationLevel?: IsolationLevel);
18
+ private connectToDatabase;
19
+ private addRequestContext;
19
20
  private mapAndAssignKeys;
20
21
  private applyExternalIdFields;
21
22
  visitPathForPopulate: (entityName: string, updateArgBranch: any, populateBranch?: string) => Set<string>;
@@ -37,5 +38,4 @@ export declare class MikroBackendProvider<D> implements BackendProvider<D> {
37
38
  deleteMany(filter: Filter<D>, trace?: TraceOptions): Promise<boolean>;
38
39
  foreignKeyForRelationshipField?(field: FieldMetadata, dataEntity: D): any;
39
40
  aggregate(filter: Filter<D>, requestedAggregations: Set<AggregationType>, trace?: TraceOptions): Promise<AggregationResult>;
40
- get plugins(): ApolloServerPlugin<BaseContext>[];
41
41
  }
@@ -32,10 +32,11 @@ __export(provider_exports, {
32
32
  module.exports = __toCommonJS(provider_exports);
33
33
  var import_graphweaver = require("@exogee/graphweaver");
34
34
  var import_logger = require("@exogee/logger");
35
+ var import_core = require("@mikro-orm/core");
36
+ var import_graphweaver_server = require("@exogee/graphweaver-server");
35
37
  var import__ = require("..");
36
38
  var import_errors = require("../utils/errors");
37
39
  var import_assign = require("./assign");
38
- var import_core = require("@mikro-orm/core");
39
40
  const objectOperations = /* @__PURE__ */ new Set(["_and", "_or", "_not"]);
40
41
  const mikroObjectOperations = /* @__PURE__ */ new Set(["$and", "$or", "$not"]);
41
42
  const appendPath = (path, newPath) => path.length ? `${path}.${newPath}` : newPath;
@@ -75,6 +76,30 @@ class MikroBackendProvider {
75
76
  sort: false,
76
77
  supportedAggregationTypes: /* @__PURE__ */ new Set([import_graphweaver.AggregationType.COUNT])
77
78
  };
79
+ this.connectToDatabase = async () => {
80
+ const connectionManagerId = this.connectionManagerId;
81
+ if (!connectionManagerId) {
82
+ throw new Error("Expected connectionManagerId to be defined when calling addRequestContext.");
83
+ }
84
+ import_graphweaver_server.apolloPluginManager.addPlugin(connectionManagerId, (0, import__.connectToDatabase)(this.connection));
85
+ };
86
+ this.addRequestContext = () => {
87
+ const connectionManagerId = this.connectionManagerId;
88
+ if (!connectionManagerId) {
89
+ throw new Error("Expected connectionManagerId to be defined when calling addRequestContext.");
90
+ }
91
+ const connectionPlugin = {
92
+ name: connectionManagerId,
93
+ event: import_graphweaver.GraphweaverRequestEvent.OnRequest,
94
+ next: (_, _next) => {
95
+ import_logger.logger.trace(`Graphweaver OnRequest plugin called`);
96
+ const connection = import__.ConnectionManager.database(connectionManagerId);
97
+ if (!connection) throw new Error("No database connection found");
98
+ return import_core.RequestContext.create(connection.orm.em, _next, {});
99
+ }
100
+ };
101
+ import_graphweaver_server.pluginManager.addPlugin(connectionPlugin);
102
+ };
78
103
  this.mapAndAssignKeys = (result, entityType, inputArgs) => {
79
104
  const assignmentObj = this.applyExternalIdFields(entityType, inputArgs);
80
105
  return (0, import_assign.assign)(result, assignmentObj, void 0, void 0, this.database.em);
@@ -155,6 +180,8 @@ class MikroBackendProvider {
155
180
  this._backendId = `mikro-orm-${connection.connectionManagerId || ""}`;
156
181
  this.transactionIsolationLevel = transactionIsolationLevel;
157
182
  this.connection = connection;
183
+ this.addRequestContext();
184
+ this.connectToDatabase();
158
185
  }
159
186
  get backendId() {
160
187
  return this._backendId;
@@ -454,9 +481,6 @@ class MikroBackendProvider {
454
481
  }
455
482
  return result;
456
483
  }
457
- get plugins() {
458
- return [import__.ClearDatabaseContext, (0, import__.connectToDatabase)(this.connection)];
459
- }
460
484
  }
461
485
  __decorateClass([
462
486
  (0, import_graphweaver.TraceMethod)()
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/provider/provider.ts"],
4
- "sourcesContent": ["import {\n\tBackendProvider,\n\tPaginationOptions,\n\tSort,\n\tFilter,\n\tBackendProviderConfig,\n\tFieldMetadata,\n\tAggregationResult,\n\tAggregationType,\n\tTraceMethod,\n\tTraceOptions,\n\ttraceSync,\n\ttrace as startTrace,\n} from '@exogee/graphweaver';\nimport { logger } from '@exogee/logger';\n\nimport {\n\tLockMode,\n\tQueryFlag,\n\tReferenceKind,\n\tConnectionManager,\n\texternalIdFieldMap,\n\tAnyEntity,\n\tIsolationLevel,\n\tConnectionOptions,\n\tClearDatabaseContext,\n\tconnectToDatabase,\n} from '..';\n\nimport { OptimisticLockError } from '../utils/errors';\nimport { assign } from './assign';\n\nimport { Reference } from '@mikro-orm/core';\nimport { AutoPath, PopulateHint } from '@mikro-orm/postgresql';\nimport { ApolloServerPlugin, BaseContext } from '@apollo/server';\n\ntype PostgresError = {\n\tcode: string;\n\troutine: string;\n};\n\nconst objectOperations = new Set(['_and', '_or', '_not']);\nconst mikroObjectOperations = new Set(['$and', '$or', '$not']);\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> implements BackendProvider<D> {\n\tprivate _backendId: string;\n\n\tprivate connection: ConnectionOptions;\n\n\tpublic entityType: new () => D;\n\tpublic connectionManagerId?: string;\n\tprivate transactionIsolationLevel!: IsolationLevel;\n\n\tpublic readonly supportsInFilter = true;\n\n\t// Default backend provider config\n\tpublic readonly backendProviderConfig: BackendProviderConfig = {\n\t\tfilter: true,\n\t\tpagination: false,\n\t\torderBy: false,\n\t\tsort: false,\n\t\tsupportedAggregationTypes: new Set<AggregationType>([AggregationType.COUNT]),\n\t};\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\tpublic constructor(\n\t\tmikroType: new () => D,\n\t\tconnection: ConnectionOptions,\n\t\ttransactionIsolationLevel: IsolationLevel = IsolationLevel.REPEATABLE_READ\n\t) {\n\t\tthis.entityType = mikroType;\n\t\tthis.connectionManagerId = connection.connectionManagerId;\n\t\tthis._backendId = `mikro-orm-${connection.connectionManagerId || ''}`;\n\t\tthis.transactionIsolationLevel = transactionIsolationLevel;\n\t\tthis.connection = connection;\n\t}\n\n\tprivate mapAndAssignKeys = (result: D, entityType: new () => D, inputArgs: Partial<D>) => {\n\t\t// Clean the input and remove any GraphQL classes from the object\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]?.kind === ReferenceKind.ONE_TO_ONE ||\n\t\t\t\tproperties[key]?.kind === ReferenceKind.ONE_TO_MANY ||\n\t\t\t\tproperties[key]?.kind === ReferenceKind.MANY_TO_ONE ||\n\t\t\t\tproperties[key]?.kind === ReferenceKind.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\t@TraceMethod()\n\tpublic async find(\n\t\tfilter: Filter<D>,\n\t\tpagination?: PaginationOptions,\n\t\ttrace?: TraceOptions\n\t): Promise<D[]> {\n\t\t// If we have a span, update the name\n\t\ttrace?.span.updateName(`Mikro-Orm - Find ${this.entityType.name}`);\n\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 = traceSync((trace?: TraceOptions) => {\n\t\t\ttrace?.span.updateName('Convert filter to Mikro-Orm format');\n\t\t\treturn filter ? gqlToMikro(JSON.parse(JSON.stringify(filter))) : undefined;\n\t\t})();\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 = where\n\t\t\t? this.applyExternalIdFields(this.entityType, where)\n\t\t\t: {};\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.em.createQueryBuilder(this.entityType);\n\t\tif (Object.keys(whereWithAppliedExternalIdFields).length > 0) {\n\t\t\tquery.andWhere(whereWithAppliedExternalIdFields);\n\t\t}\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\ttry {\n\t\t\tconst result = await startTrace(async (trace?: TraceOptions) => {\n\t\t\t\ttrace?.span.updateName('Mikro-Orm - Fetch Data');\n\t\t\t\treturn query.getResult();\n\t\t\t})();\n\n\t\t\tlogger.trace(`find ${this.entityType.name} result: ${result.length} rows`);\n\n\t\t\treturn result;\n\t\t} catch (err) {\n\t\t\tlogger.error(`find ${this.entityType.name} error: ${JSON.stringify(err)}`);\n\n\t\t\tif ((err as PostgresError)?.routine === 'InitializeSessionUserId') {\n\t\t\t\t// Throw if the user credentials are incorrect\n\t\t\t\tthrow new Error(\n\t\t\t\t\t'Database connection failed, please check you are using the correct user credentials for the database.'\n\t\t\t\t);\n\t\t\t} else if ((err as PostgresError)?.code === 'ECONNREFUSED') {\n\t\t\t\t// Throw if the database address or port is incorrect\n\t\t\t\tthrow new Error(\n\t\t\t\t\t'Database connection failed, please check you are using the correct address and port for the database.'\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t}\n\t}\n\n\t@TraceMethod()\n\tpublic async findOne(filter: Filter<D>, trace?: TraceOptions): Promise<D | null> {\n\t\ttrace?.span.updateName(`Mikro-Orm - FindOne ${this.entityType.name}`);\n\t\tlogger.trace(`Running findOne ${this.entityType.name} with filter ${filter}`);\n\n\t\tconst metadata = this.em.getMetadata().get(this.entityType.name);\n\t\tif (metadata.primaryKeys.length !== 1) {\n\t\t\tthrow new Error(\n\t\t\t\t`Entity ${this.entityType.name} has ${metadata.primaryKeys.length} primary keys. We only support entities with a single primary key at this stage.`\n\t\t\t);\n\t\t}\n\n\t\tconst [result] = await this.find(filter, {\n\t\t\torderBy: { [metadata.primaryKeys[0]]: Sort.DESC },\n\t\t\toffset: 0,\n\t\t\tlimit: 1,\n\t\t});\n\n\t\tlogger.trace(`findOne ${this.entityType.name} result`, { result });\n\n\t\treturn result;\n\t}\n\n\t@TraceMethod()\n\tpublic async findByRelatedId(\n\t\tentity: any,\n\t\trelatedField: string,\n\t\trelatedFieldIds: string[],\n\t\tfilter?: any,\n\t\ttrace?: TraceOptions\n\t): Promise<D[]> {\n\t\ttrace?.span.updateName(`Mikro-Orm - findByRelatedId ${this.entityType.name}`);\n\t\tconst queryFilter = {\n\t\t\t$and: [{ [relatedField]: { $in: relatedFieldIds } }, ...[gqlToMikro(filter) ?? []]],\n\t\t};\n\n\t\tconst populate = [relatedField as AutoPath<typeof entity, PopulateHint>];\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\t@TraceMethod()\n\tpublic async updateOne(\n\t\tid: string | number,\n\t\tupdateArgs: Partial<D & { version?: number }>,\n\t\ttrace?: TraceOptions\n\t): Promise<D> {\n\t\ttrace?.span.updateName(`Mikro-Orm - updateOne ${this.entityType.name}`);\n\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\tconst { version, ...updateArgsWithoutVersion } = updateArgs;\n\n\t\t// If a version has been sent, let's check it\n\t\tif (version) {\n\t\t\ttry {\n\t\t\t\tawait this.database.em.lock(entity, LockMode.OPTIMISTIC, 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, updateArgsWithoutVersion as Partial<D>);\n\t\tawait this.database.em.persistAndFlush(entity);\n\n\t\tlogger.trace(`update ${this.entityType.name} entity`, entity);\n\n\t\treturn entity;\n\t}\n\n\t@TraceMethod()\n\tpublic async updateMany(\n\t\tupdateItems: (Partial<D> & { id: string })[],\n\t\ttrace?: TraceOptions\n\t): Promise<D[]> {\n\t\ttrace?.span.updateName(`Mikro-Orm - updateMany ${this.entityType.name}`);\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\t@TraceMethod()\n\tpublic async createOrUpdateMany(items: Partial<D>[], trace?: TraceOptions): Promise<D[]> {\n\t\ttrace?.span.updateName(`Mikro-Orm - createOrUpdateMany ${this.entityType.name}`);\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\t@TraceMethod()\n\tpublic async createOne(createArgs: Partial<D>, trace?: TraceOptions): Promise<D> {\n\t\ttrace?.span.updateName(`Mikro-Orm - createOne ${this.entityType.name}`);\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.database.em.persistAndFlush(entity as Partial<D>);\n\n\t\tlogger.trace(`create ${this.entityType.name} result`, entity);\n\n\t\treturn entity;\n\t}\n\n\t@TraceMethod()\n\tpublic async createMany(createItems: Partial<D>[], trace?: TraceOptions): Promise<D[]> {\n\t\ttrace?.span.updateName(`Mikro-Orm - createMany ${this.entityType.name}`);\n\t\treturn this._createMany(createItems);\n\t}\n\n\tpublic async createTraces(createItems: Partial<D>[]): Promise<D[]> {\n\t\treturn this._createMany(createItems);\n\t}\n\n\tprivate async _createMany(createItems: Partial<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 as Partial<D>);\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\t@TraceMethod()\n\tpublic async deleteOne(filter: Filter<D>, trace?: TraceOptions): Promise<boolean> {\n\t\ttrace?.span.updateName(`Mikro-Orm - deleteOne ${this.entityType.name}`);\n\t\tlogger.trace(filter, `Running delete ${this.entityType.name} with 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.database.em.nativeDelete(\n\t\t\tthis.entityType,\n\t\t\twhereWithAppliedExternalIdFields\n\t\t);\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\t@TraceMethod()\n\tpublic async deleteMany(filter: Filter<D>, trace?: TraceOptions): Promise<boolean> {\n\t\ttrace?.span.updateName(`Mikro-Orm - deleteMany ${this.entityType.name}`);\n\t\tlogger.trace(`Running delete ${this.entityType.name}`);\n\n\t\tconst deletedRows = await this.database.transactional<number>(async () => {\n\t\t\tconst where = filter ? gqlToMikro(JSON.parse(JSON.stringify(filter))) : undefined;\n\t\t\tconst whereWithAppliedExternalIdFields =\n\t\t\t\twhere && this.applyExternalIdFields(this.entityType, where);\n\n\t\t\tconst toDelete = await this.database.em.count(\n\t\t\t\tthis.entityType,\n\t\t\t\twhereWithAppliedExternalIdFields\n\t\t\t);\n\t\t\tconst deletedCount = await this.database.em.nativeDelete(\n\t\t\t\tthis.entityType,\n\t\t\t\twhereWithAppliedExternalIdFields\n\t\t\t);\n\n\t\t\tif (deletedCount !== toDelete) {\n\t\t\t\tthrow new Error('We did not delete any 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 true;\n\t}\n\n\tpublic foreignKeyForRelationshipField?(field: FieldMetadata, dataEntity: D) {\n\t\tconst value = dataEntity[field.name as keyof D];\n\n\t\tif (Reference.isReference(value)) {\n\t\t\tconst { properties } = this.database.em.getMetadata().get(this.entityType);\n\t\t\tconst property = properties[field.name];\n\t\t\tconst [primaryKey] = property.targetMeta?.primaryKeys ?? [];\n\t\t\tif (!primaryKey) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Could not determine primary key for ${field.name} on ${this.entityType.name}`\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst foreignKey = (value.unwrap() as any)[primaryKey];\n\t\t\tif (foreignKey === undefined || foreignKey === null) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Could not read foreign key from reference: ${value.unwrap()} with primary key name ${primaryKey}`\n\t\t\t\t);\n\t\t\t}\n\n\t\t\treturn foreignKey;\n\t\t}\n\n\t\treturn null;\n\t}\n\n\t@TraceMethod()\n\tpublic async aggregate(\n\t\tfilter: Filter<D>,\n\t\trequestedAggregations: Set<AggregationType>,\n\t\ttrace?: TraceOptions\n\t): Promise<AggregationResult> {\n\t\ttrace?.span.updateName(`Mikro-Orm - aggregate ${this.entityType.name}`);\n\t\tlogger.trace(`Running aggregate ${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 = where\n\t\t\t? this.applyExternalIdFields(this.entityType, where)\n\t\t\t: {};\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.em.createQueryBuilder(this.entityType);\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\tif (Object.keys(whereWithAppliedExternalIdFields).length > 0) {\n\t\t\tquery.andWhere(whereWithAppliedExternalIdFields);\n\t\t}\n\n\t\tconst result: AggregationResult = {};\n\n\t\ttry {\n\t\t\tif (requestedAggregations.has(AggregationType.COUNT)) {\n\t\t\t\tconst meta = this.database.em.getMetadata().get(this.entityType.name);\n\t\t\t\tresult.count = await query.getCount(meta.primaryKeys);\n\t\t\t}\n\t\t} catch (err) {\n\t\t\tlogger.error(`find ${this.entityType.name} error: ${JSON.stringify(err)}`);\n\n\t\t\tif ((err as PostgresError)?.routine === 'InitializeSessionUserId') {\n\t\t\t\t// Throw if the user credentials are incorrect\n\t\t\t\tthrow new Error(\n\t\t\t\t\t'Database connection failed, please check you are using the correct user credentials for the database.'\n\t\t\t\t);\n\t\t\t} else if ((err as PostgresError)?.code === 'ECONNREFUSED') {\n\t\t\t\t// Throw if the database address or port is incorrect\n\t\t\t\tthrow new Error(\n\t\t\t\t\t'Database connection failed, please check you are using the correct address and port for the database.'\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t}\n\n\t\treturn result;\n\t}\n\n\tpublic get plugins(): ApolloServerPlugin<BaseContext>[] {\n\t\treturn [ClearDatabaseContext, connectToDatabase(this.connection)];\n\t}\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,yBAaO;AACP,oBAAuB;AAEvB,eAWO;AAEP,oBAAoC;AACpC,oBAAuB;AAEvB,kBAA0B;AAS1B,MAAM,mBAAmB,oBAAI,IAAI,CAAC,QAAQ,OAAO,MAAM,CAAC;AACxD,MAAM,wBAAwB,oBAAI,IAAI,CAAC,QAAQ,OAAO,MAAM,CAAC;AAE7D,MAAM,aAAa,CAAC,MAAc,YACjC,KAAK,SAAS,GAAG,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AAElE,cAAM,IAAI;AAAA,UACT;AAAA,QACD;AAAA,MACD,WAAY,KAAuB,SAAS,gBAAgB;AAE3D,cAAM,IAAI;AAAA,UACT;AAAA,QACD;AAAA,MACD,OAAO;AACN,cAAM;AAAA,MACP;AAAA,IACD;AAEA,WAAO;AAAA,EACR;AAAA,EAEA,IAAW,UAA6C;AACvD,WAAO,CAAC,mCAAsB,4BAAkB,KAAK,UAAU,CAAC;AAAA,EACjE;AACD;AArbc;AAAA,MADZ,gCAAY;AAAA,GA1JD,qBA2JC;AAoFA;AAAA,MADZ,gCAAY;AAAA,GA9OD,qBA+OC;AAuBA;AAAA,MADZ,gCAAY;AAAA,GArQD,qBAsQC;AAqBA;AAAA,MADZ,gCAAY;AAAA,GA1RD,qBA2RC;AAyCA;AAAA,MADZ,gCAAY;AAAA,GAnUD,qBAoUC;AA+BA;AAAA,MADZ,gCAAY;AAAA,GAlWD,qBAmWC;AAwCA;AAAA,MADZ,gCAAY;AAAA,GA1YD,qBA2YC;AAgBA;AAAA,MADZ,gCAAY;AAAA,GA1ZD,qBA2ZC;AA+BA;AAAA,MADZ,gCAAY;AAAA,GAzbD,qBA0bC;AAsBA;AAAA,MADZ,gCAAY;AAAA,GA/cD,qBAgdC;AAyDA;AAAA,MADZ,gCAAY;AAAA,GAxgBD,qBAygBC;",
4
+ "sourcesContent": ["import {\n\tBackendProvider,\n\tPaginationOptions,\n\tSort,\n\tFilter,\n\tBackendProviderConfig,\n\tFieldMetadata,\n\tAggregationResult,\n\tAggregationType,\n\tTraceMethod,\n\tTraceOptions,\n\ttraceSync,\n\ttrace as startTrace,\n\tGraphweaverRequestEvent,\n\tGraphweaverPluginNextFunction,\n} from '@exogee/graphweaver';\nimport { logger } from '@exogee/logger';\nimport { Reference, RequestContext } from '@mikro-orm/core';\nimport { AutoPath, PopulateHint } from '@mikro-orm/postgresql';\nimport { pluginManager, apolloPluginManager } from '@exogee/graphweaver-server';\n\nimport {\n\tLockMode,\n\tQueryFlag,\n\tReferenceKind,\n\tConnectionManager,\n\texternalIdFieldMap,\n\tAnyEntity,\n\tIsolationLevel,\n\tConnectionOptions,\n\tconnectToDatabase,\n} from '..';\n\nimport { OptimisticLockError } from '../utils/errors';\nimport { assign } from './assign';\n\ntype PostgresError = {\n\tcode: string;\n\troutine: string;\n};\n\nconst objectOperations = new Set(['_and', '_or', '_not']);\nconst mikroObjectOperations = new Set(['$and', '$or', '$not']);\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> implements BackendProvider<D> {\n\tprivate _backendId: string;\n\n\tprivate connection: ConnectionOptions;\n\n\tpublic entityType: new () => D;\n\tpublic connectionManagerId?: string;\n\tprivate transactionIsolationLevel!: IsolationLevel;\n\n\tpublic readonly supportsInFilter = true;\n\n\t// Default backend provider config\n\tpublic readonly backendProviderConfig: BackendProviderConfig = {\n\t\tfilter: true,\n\t\tpagination: false,\n\t\torderBy: false,\n\t\tsort: false,\n\t\tsupportedAggregationTypes: new Set<AggregationType>([AggregationType.COUNT]),\n\t};\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\tpublic constructor(\n\t\tmikroType: new () => D,\n\t\tconnection: ConnectionOptions,\n\t\ttransactionIsolationLevel: IsolationLevel = IsolationLevel.REPEATABLE_READ\n\t) {\n\t\tthis.entityType = mikroType;\n\t\tthis.connectionManagerId = connection.connectionManagerId;\n\t\tthis._backendId = `mikro-orm-${connection.connectionManagerId || ''}`;\n\t\tthis.transactionIsolationLevel = transactionIsolationLevel;\n\t\tthis.connection = connection;\n\t\tthis.addRequestContext();\n\t\tthis.connectToDatabase();\n\t}\n\n\tprivate connectToDatabase = async () => {\n\t\tconst connectionManagerId = this.connectionManagerId;\n\t\tif (!connectionManagerId) {\n\t\t\tthrow new Error('Expected connectionManagerId to be defined when calling addRequestContext.');\n\t\t}\n\n\t\tapolloPluginManager.addPlugin(connectionManagerId, connectToDatabase(this.connection));\n\t};\n\n\tprivate addRequestContext = () => {\n\t\tconst connectionManagerId = this.connectionManagerId;\n\t\tif (!connectionManagerId) {\n\t\t\tthrow new Error('Expected connectionManagerId to be defined when calling addRequestContext.');\n\t\t}\n\n\t\tconst connectionPlugin = {\n\t\t\tname: connectionManagerId,\n\t\t\tevent: GraphweaverRequestEvent.OnRequest,\n\t\t\tnext: (_: GraphweaverRequestEvent, _next: GraphweaverPluginNextFunction) => {\n\t\t\t\tlogger.trace(`Graphweaver OnRequest plugin called`);\n\n\t\t\t\tconst connection = ConnectionManager.database(connectionManagerId);\n\t\t\t\tif (!connection) throw new Error('No database connection found');\n\n\t\t\t\treturn RequestContext.create(connection.orm.em, _next, {});\n\t\t\t},\n\t\t};\n\t\tpluginManager.addPlugin(connectionPlugin);\n\t};\n\n\tprivate mapAndAssignKeys = (result: D, entityType: new () => D, inputArgs: Partial<D>) => {\n\t\t// Clean the input and remove any GraphQL classes from the object\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]?.kind === ReferenceKind.ONE_TO_ONE ||\n\t\t\t\tproperties[key]?.kind === ReferenceKind.ONE_TO_MANY ||\n\t\t\t\tproperties[key]?.kind === ReferenceKind.MANY_TO_ONE ||\n\t\t\t\tproperties[key]?.kind === ReferenceKind.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\t@TraceMethod()\n\tpublic async find(\n\t\tfilter: Filter<D>,\n\t\tpagination?: PaginationOptions,\n\t\ttrace?: TraceOptions\n\t): Promise<D[]> {\n\t\t// If we have a span, update the name\n\t\ttrace?.span.updateName(`Mikro-Orm - Find ${this.entityType.name}`);\n\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 = traceSync((trace?: TraceOptions) => {\n\t\t\ttrace?.span.updateName('Convert filter to Mikro-Orm format');\n\t\t\treturn filter ? gqlToMikro(JSON.parse(JSON.stringify(filter))) : undefined;\n\t\t})();\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 = where\n\t\t\t? this.applyExternalIdFields(this.entityType, where)\n\t\t\t: {};\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.em.createQueryBuilder(this.entityType);\n\t\tif (Object.keys(whereWithAppliedExternalIdFields).length > 0) {\n\t\t\tquery.andWhere(whereWithAppliedExternalIdFields);\n\t\t}\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\ttry {\n\t\t\tconst result = await startTrace(async (trace?: TraceOptions) => {\n\t\t\t\ttrace?.span.updateName('Mikro-Orm - Fetch Data');\n\t\t\t\treturn query.getResult();\n\t\t\t})();\n\n\t\t\tlogger.trace(`find ${this.entityType.name} result: ${result.length} rows`);\n\n\t\t\treturn result;\n\t\t} catch (err) {\n\t\t\tlogger.error(`find ${this.entityType.name} error: ${JSON.stringify(err)}`);\n\n\t\t\tif ((err as PostgresError)?.routine === 'InitializeSessionUserId') {\n\t\t\t\t// Throw if the user credentials are incorrect\n\t\t\t\tthrow new Error(\n\t\t\t\t\t'Database connection failed, please check you are using the correct user credentials for the database.'\n\t\t\t\t);\n\t\t\t} else if ((err as PostgresError)?.code === 'ECONNREFUSED') {\n\t\t\t\t// Throw if the database address or port is incorrect\n\t\t\t\tthrow new Error(\n\t\t\t\t\t'Database connection failed, please check you are using the correct address and port for the database.'\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t}\n\t}\n\n\t@TraceMethod()\n\tpublic async findOne(filter: Filter<D>, trace?: TraceOptions): Promise<D | null> {\n\t\ttrace?.span.updateName(`Mikro-Orm - FindOne ${this.entityType.name}`);\n\t\tlogger.trace(`Running findOne ${this.entityType.name} with filter ${filter}`);\n\n\t\tconst metadata = this.em.getMetadata().get(this.entityType.name);\n\t\tif (metadata.primaryKeys.length !== 1) {\n\t\t\tthrow new Error(\n\t\t\t\t`Entity ${this.entityType.name} has ${metadata.primaryKeys.length} primary keys. We only support entities with a single primary key at this stage.`\n\t\t\t);\n\t\t}\n\n\t\tconst [result] = await this.find(filter, {\n\t\t\torderBy: { [metadata.primaryKeys[0]]: Sort.DESC },\n\t\t\toffset: 0,\n\t\t\tlimit: 1,\n\t\t});\n\n\t\tlogger.trace(`findOne ${this.entityType.name} result`, { result });\n\n\t\treturn result;\n\t}\n\n\t@TraceMethod()\n\tpublic async findByRelatedId(\n\t\tentity: any,\n\t\trelatedField: string,\n\t\trelatedFieldIds: string[],\n\t\tfilter?: any,\n\t\ttrace?: TraceOptions\n\t): Promise<D[]> {\n\t\ttrace?.span.updateName(`Mikro-Orm - findByRelatedId ${this.entityType.name}`);\n\t\tconst queryFilter = {\n\t\t\t$and: [{ [relatedField]: { $in: relatedFieldIds } }, ...[gqlToMikro(filter) ?? []]],\n\t\t};\n\n\t\tconst populate = [relatedField as AutoPath<typeof entity, PopulateHint>];\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\t@TraceMethod()\n\tpublic async updateOne(\n\t\tid: string | number,\n\t\tupdateArgs: Partial<D & { version?: number }>,\n\t\ttrace?: TraceOptions\n\t): Promise<D> {\n\t\ttrace?.span.updateName(`Mikro-Orm - updateOne ${this.entityType.name}`);\n\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\tconst { version, ...updateArgsWithoutVersion } = updateArgs;\n\n\t\t// If a version has been sent, let's check it\n\t\tif (version) {\n\t\t\ttry {\n\t\t\t\tawait this.database.em.lock(entity, LockMode.OPTIMISTIC, 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, updateArgsWithoutVersion as Partial<D>);\n\t\tawait this.database.em.persistAndFlush(entity);\n\n\t\tlogger.trace(`update ${this.entityType.name} entity`, entity);\n\n\t\treturn entity;\n\t}\n\n\t@TraceMethod()\n\tpublic async updateMany(\n\t\tupdateItems: (Partial<D> & { id: string })[],\n\t\ttrace?: TraceOptions\n\t): Promise<D[]> {\n\t\ttrace?.span.updateName(`Mikro-Orm - updateMany ${this.entityType.name}`);\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\t@TraceMethod()\n\tpublic async createOrUpdateMany(items: Partial<D>[], trace?: TraceOptions): Promise<D[]> {\n\t\ttrace?.span.updateName(`Mikro-Orm - createOrUpdateMany ${this.entityType.name}`);\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\t@TraceMethod()\n\tpublic async createOne(createArgs: Partial<D>, trace?: TraceOptions): Promise<D> {\n\t\ttrace?.span.updateName(`Mikro-Orm - createOne ${this.entityType.name}`);\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.database.em.persistAndFlush(entity as Partial<D>);\n\n\t\tlogger.trace(`create ${this.entityType.name} result`, entity);\n\n\t\treturn entity;\n\t}\n\n\t@TraceMethod()\n\tpublic async createMany(createItems: Partial<D>[], trace?: TraceOptions): Promise<D[]> {\n\t\ttrace?.span.updateName(`Mikro-Orm - createMany ${this.entityType.name}`);\n\t\treturn this._createMany(createItems);\n\t}\n\n\tpublic async createTraces(createItems: Partial<D>[]): Promise<D[]> {\n\t\treturn this._createMany(createItems);\n\t}\n\n\tprivate async _createMany(createItems: Partial<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 as Partial<D>);\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\t@TraceMethod()\n\tpublic async deleteOne(filter: Filter<D>, trace?: TraceOptions): Promise<boolean> {\n\t\ttrace?.span.updateName(`Mikro-Orm - deleteOne ${this.entityType.name}`);\n\t\tlogger.trace(filter, `Running delete ${this.entityType.name} with 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.database.em.nativeDelete(\n\t\t\tthis.entityType,\n\t\t\twhereWithAppliedExternalIdFields\n\t\t);\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\t@TraceMethod()\n\tpublic async deleteMany(filter: Filter<D>, trace?: TraceOptions): Promise<boolean> {\n\t\ttrace?.span.updateName(`Mikro-Orm - deleteMany ${this.entityType.name}`);\n\t\tlogger.trace(`Running delete ${this.entityType.name}`);\n\n\t\tconst deletedRows = await this.database.transactional<number>(async () => {\n\t\t\tconst where = filter ? gqlToMikro(JSON.parse(JSON.stringify(filter))) : undefined;\n\t\t\tconst whereWithAppliedExternalIdFields =\n\t\t\t\twhere && this.applyExternalIdFields(this.entityType, where);\n\n\t\t\tconst toDelete = await this.database.em.count(\n\t\t\t\tthis.entityType,\n\t\t\t\twhereWithAppliedExternalIdFields\n\t\t\t);\n\t\t\tconst deletedCount = await this.database.em.nativeDelete(\n\t\t\t\tthis.entityType,\n\t\t\t\twhereWithAppliedExternalIdFields\n\t\t\t);\n\n\t\t\tif (deletedCount !== toDelete) {\n\t\t\t\tthrow new Error('We did not delete any 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 true;\n\t}\n\n\tpublic foreignKeyForRelationshipField?(field: FieldMetadata, dataEntity: D) {\n\t\tconst value = dataEntity[field.name as keyof D];\n\n\t\tif (Reference.isReference(value)) {\n\t\t\tconst { properties } = this.database.em.getMetadata().get(this.entityType);\n\t\t\tconst property = properties[field.name];\n\t\t\tconst [primaryKey] = property.targetMeta?.primaryKeys ?? [];\n\t\t\tif (!primaryKey) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Could not determine primary key for ${field.name} on ${this.entityType.name}`\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst foreignKey = (value.unwrap() as any)[primaryKey];\n\t\t\tif (foreignKey === undefined || foreignKey === null) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Could not read foreign key from reference: ${value.unwrap()} with primary key name ${primaryKey}`\n\t\t\t\t);\n\t\t\t}\n\n\t\t\treturn foreignKey;\n\t\t}\n\n\t\treturn null;\n\t}\n\n\t@TraceMethod()\n\tpublic async aggregate(\n\t\tfilter: Filter<D>,\n\t\trequestedAggregations: Set<AggregationType>,\n\t\ttrace?: TraceOptions\n\t): Promise<AggregationResult> {\n\t\ttrace?.span.updateName(`Mikro-Orm - aggregate ${this.entityType.name}`);\n\t\tlogger.trace(`Running aggregate ${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 = where\n\t\t\t? this.applyExternalIdFields(this.entityType, where)\n\t\t\t: {};\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.em.createQueryBuilder(this.entityType);\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\tif (Object.keys(whereWithAppliedExternalIdFields).length > 0) {\n\t\t\tquery.andWhere(whereWithAppliedExternalIdFields);\n\t\t}\n\n\t\tconst result: AggregationResult = {};\n\n\t\ttry {\n\t\t\tif (requestedAggregations.has(AggregationType.COUNT)) {\n\t\t\t\tconst meta = this.database.em.getMetadata().get(this.entityType.name);\n\t\t\t\tresult.count = await query.getCount(meta.primaryKeys);\n\t\t\t}\n\t\t} catch (err) {\n\t\t\tlogger.error(`find ${this.entityType.name} error: ${JSON.stringify(err)}`);\n\n\t\t\tif ((err as PostgresError)?.routine === 'InitializeSessionUserId') {\n\t\t\t\t// Throw if the user credentials are incorrect\n\t\t\t\tthrow new Error(\n\t\t\t\t\t'Database connection failed, please check you are using the correct user credentials for the database.'\n\t\t\t\t);\n\t\t\t} else if ((err as PostgresError)?.code === 'ECONNREFUSED') {\n\t\t\t\t// Throw if the database address or port is incorrect\n\t\t\t\tthrow new Error(\n\t\t\t\t\t'Database connection failed, please check you are using the correct address and port for the database.'\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t}\n\n\t\treturn result;\n\t}\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,yBAeO;AACP,oBAAuB;AACvB,kBAA0C;AAE1C,gCAAmD;AAEnD,eAUO;AAEP,oBAAoC;AACpC,oBAAuB;AAOvB,MAAM,mBAAmB,oBAAI,IAAI,CAAC,QAAQ,OAAO,MAAM,CAAC;AACxD,MAAM,wBAAwB,oBAAI,IAAI,CAAC,QAAQ,OAAO,MAAM,CAAC;AAE7D,MAAM,aAAa,CAAC,MAAc,YACjC,KAAK,SAAS,GAAG,IAAI,IAAI,OAAO,KAAK;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,U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AAAA,GAxiBD,qBAyiBC;",
6
6
  "names": ["trace", "startTrace"]
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@exogee/graphweaver-mikroorm",
3
- "version": "2.0.5",
3
+ "version": "2.0.7",
4
4
  "description": "MikroORM backend for @exogee/graphweaver",
5
5
  "license": "MIT",
6
6
  "main": "lib/index.js",
@@ -12,39 +12,40 @@
12
12
  "lib"
13
13
  ],
14
14
  "dependencies": {
15
- "@apollo/server": "4.10.4",
16
- "@aws-sdk/client-secrets-manager": "3.614.0",
15
+ "@apollo/server": "4.10.5",
16
+ "@aws-sdk/client-secrets-manager": "3.621.0",
17
17
  "dataloader": "2.2.2",
18
18
  "decimal.js": "10.4.3",
19
19
  "dotenv": "16.4.5",
20
20
  "graphql": "16.9.0",
21
21
  "pluralize": "8.0.0",
22
22
  "reflect-metadata": "0.2.2",
23
- "@exogee/graphweaver": "2.0.5",
24
- "@exogee/logger": "2.0.5"
23
+ "@exogee/logger": "2.0.7",
24
+ "@exogee/graphweaver": "2.0.7",
25
+ "@exogee/graphweaver-server": "2.0.7"
25
26
  },
26
27
  "devDependencies": {
27
- "@mikro-orm/core": "6.2.9",
28
- "@mikro-orm/knex": "6.2.9",
29
- "@mikro-orm/mysql": "6.2.9",
30
- "@mikro-orm/postgresql": "6.2.9",
31
- "@mikro-orm/sqlite": "6.2.9",
32
- "@types/node": "20.14.11",
28
+ "@mikro-orm/core": "6.3.1",
29
+ "@mikro-orm/knex": "6.3.1",
30
+ "@mikro-orm/mysql": "6.3.1",
31
+ "@mikro-orm/postgresql": "6.3.1",
32
+ "@mikro-orm/sqlite": "6.3.1",
33
+ "@types/node": "22.0.0",
33
34
  "@types/pluralize": "0.0.33",
34
35
  "esbuild": "0.23.0",
35
36
  "glob": "10.4.3",
36
37
  "ts-node": "10.9.2",
37
- "typescript": "5.5.3"
38
+ "typescript": "5.5.4"
38
39
  },
39
40
  "optionalDependencies": {
40
- "@mikro-orm/knex": "6.2.9",
41
- "@mikro-orm/mysql": "6.2.9",
42
- "@mikro-orm/postgresql": "6.2.9",
43
- "@mikro-orm/sqlite": "6.2.9"
41
+ "@mikro-orm/knex": "6.3.1",
42
+ "@mikro-orm/mysql": "6.3.1",
43
+ "@mikro-orm/postgresql": "6.3.1",
44
+ "@mikro-orm/sqlite": "6.3.1"
44
45
  },
45
46
  "peerDependencies": {
46
- "@mikro-orm/core": "6.2.9",
47
- "@mikro-orm/knex": "6.2.9"
47
+ "@mikro-orm/core": "6.3.1",
48
+ "@mikro-orm/knex": "6.3.1"
48
49
  },
49
50
  "keywords": [
50
51
  "graphql",
@@ -1,2 +0,0 @@
1
- import { ApolloServerPlugin } from '@apollo/server';
2
- export declare const ClearDatabaseContext: ApolloServerPlugin;
@@ -1,42 +0,0 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
- var clear_database_context_exports = {};
20
- __export(clear_database_context_exports, {
21
- ClearDatabaseContext: () => ClearDatabaseContext
22
- });
23
- module.exports = __toCommonJS(clear_database_context_exports);
24
- var import_logger = require("@exogee/logger");
25
- var import_database = require("../database");
26
- const ClearDatabaseContext = {
27
- // We need to ensure the Entity Manager is clear on each request
28
- async requestDidStart() {
29
- try {
30
- for (const connection of import_database.ConnectionManager.getConnections()) {
31
- connection.em.clear();
32
- }
33
- } catch (err) {
34
- import_logger.logger.trace("failed to clear default database.");
35
- }
36
- }
37
- };
38
- // Annotate the CommonJS export names for ESM import in node:
39
- 0 && (module.exports = {
40
- ClearDatabaseContext
41
- });
42
- //# sourceMappingURL=clear-database-context.js.map
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../src/plugins/clear-database-context.ts"],
4
- "sourcesContent": ["import { ApolloServerPlugin } from '@apollo/server';\nimport { logger } from '@exogee/logger';\n\nimport { ConnectionManager } from '../database';\n\nexport const ClearDatabaseContext: ApolloServerPlugin = {\n\t// We need to ensure the Entity Manager is clear on each request\n\tasync requestDidStart() {\n\t\ttry {\n\t\t\tfor (const connection of ConnectionManager.getConnections()) {\n\t\t\t\tconnection.em.clear();\n\t\t\t}\n\t\t} catch (err) {\n\t\t\tlogger.trace('failed to clear default database.');\n\t\t}\n\t},\n};\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,oBAAuB;AAEvB,sBAAkC;AAE3B,MAAM,uBAA2C;AAAA;AAAA,EAEvD,MAAM,kBAAkB;AACvB,QAAI;AACH,iBAAW,cAAc,kCAAkB,eAAe,GAAG;AAC5D,mBAAW,GAAG,MAAM;AAAA,MACrB;AAAA,IACD,SAAS,KAAK;AACb,2BAAO,MAAM,mCAAmC;AAAA,IACjD;AAAA,EACD;AACD;",
6
- "names": []
7
- }