Last active
June 6, 2024 16:25
-
-
Save adrien2p/9c9000f1da244e27d22afd9d24086cf1 to your computer and use it in GitHub Desktop.
This is a quick and dirty POC to show how it can be achieve to create dynamically generated entity. The end code will not look at all like this
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function buildEntity(entityName: string, properties: [{ name: string, type: string, columnType: string, index?: boolean }]) { | |
class DMLEntity { | |
[key: string]: any | |
constructor() { | |
for (const property of properties) { | |
this[property.name] = undefined | |
} | |
} | |
} | |
Object.defineProperty(DMLEntity,'name', { | |
get : function () { | |
return upperCaseFirst(entityName); | |
} | |
}); | |
const tableName = camelToSnakeCase(entityName) | |
for (const property of properties) { | |
if (property.index) { | |
const index = createPsqlIndexStatementHelper({ | |
tableName, | |
columns: property.name, | |
}) | |
index.MikroORMIndex()(DMLEntity.prototype, property.name) | |
} | |
Property({ | |
type: property.type, | |
columnType: property.columnType, | |
})(DMLEntity.prototype, property.name) | |
} | |
return Entity({ tableName })(DMLEntity) | |
} | |
const Currency = buildEntity("currency", [{ | |
name: 'code', | |
type: 'string', | |
columnType: 'text', | |
index: true, | |
}]) | |
const metadata = MetadataStorage.getMetadataFromDecorator(Currency); | |
console.log(Currency) | |
console.log(new Currency()) | |
console.log(metadata) | |
/* | |
[class Currency] | |
Currency { code: undefined } | |
EntityMetadata { | |
propertyOrder: Map(0) {}, | |
properties: { | |
code: { | |
reference: 'scalar', | |
type: 'string', | |
columnType: 'text', | |
name: 'code', | |
getter: false, | |
setter: false | |
} | |
}, | |
props: [], | |
primaryKeys: [], | |
filters: {}, | |
hooks: {}, | |
indexes: [ | |
{ | |
name: 'IDX_currency_code', | |
expression: 'CREATE INDEX IF NOT EXISTS "IDX_currency_code" ON "currency" (code)', | |
properties: 'code' | |
} | |
], | |
uniques: [], | |
checks: [], | |
referencingProperties: [], | |
concurrencyCheckKeys: Set(0) {}, | |
className: 'Currency', | |
path: 'Currency', | |
collection: 'currency', | |
class: [class Currency], | |
name: 'Currency' | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment