(
modelClass,
{ parentBuilder = null, knex = null, force = false, table = null } = {},
)
| 6 | const TABLE_METADATA = '$$tableMetadata'; |
| 7 | |
| 8 | function fetchTableMetadata( |
| 9 | modelClass, |
| 10 | { parentBuilder = null, knex = null, force = false, table = null } = {}, |
| 11 | ) { |
| 12 | // The table isn't necessarily same as `modelClass.getTableName()` for example if |
| 13 | // a view is queried instead. |
| 14 | if (!table) { |
| 15 | if (parentBuilder) { |
| 16 | table = parentBuilder.tableNameFor(modelClass); |
| 17 | } else { |
| 18 | table = modelClass.getTableName(); |
| 19 | } |
| 20 | } |
| 21 | |
| 22 | // Call tableMetadata first instead of accessing the cache directly beause |
| 23 | // tableMetadata may have been overriden. |
| 24 | let metadata = modelClass.tableMetadata({ table }); |
| 25 | |
| 26 | if (!force && metadata) { |
| 27 | return Promise.resolve(metadata); |
| 28 | } |
| 29 | |
| 30 | // Memoize metadata but only for modelClass. The hasOwnProperty check |
| 31 | // will fail for subclasses and the value gets recreated. |
| 32 | if (!modelClass.hasOwnProperty(TABLE_METADATA)) { |
| 33 | defineNonEnumerableProperty(modelClass, TABLE_METADATA, new Map()); |
| 34 | } |
| 35 | |
| 36 | // The cache needs to be checked in addition to calling tableMetadata |
| 37 | // because the cache may contain a temporary promise in which case |
| 38 | // tableMetadata returns null. |
| 39 | metadata = modelClass[TABLE_METADATA].get(table); |
| 40 | |
| 41 | if (!force && metadata) { |
| 42 | return Promise.resolve(metadata); |
| 43 | } else { |
| 44 | const promise = modelClass |
| 45 | .query(knex) |
| 46 | .childQueryOf(parentBuilder) |
| 47 | .columnInfo({ table }) |
| 48 | .then((columnInfo) => { |
| 49 | const metadata = { |
| 50 | columns: Object.keys(columnInfo), |
| 51 | }; |
| 52 | |
| 53 | modelClass[TABLE_METADATA].set(table, metadata); |
| 54 | return metadata; |
| 55 | }) |
| 56 | .catch((err) => { |
| 57 | modelClass[TABLE_METADATA].delete(table); |
| 58 | throw err; |
| 59 | }); |
| 60 | |
| 61 | modelClass[TABLE_METADATA].set(table, promise); |
| 62 | return promise; |
| 63 | } |
| 64 | } |
| 65 |
no test coverage detected