All files / lib/objection-utils objection-utils.lib.ts

80% Statements 24/30
50% Branches 6/12
100% Functions 5/5
79.31% Lines 23/29

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 704x                   4x     4x 16x   4x 4x 16x 16x 16x 4x   16x 20x   20x     20x     20x   16x 1x   1x     1x     1x   16x   4x   4x                                        
import { loadFolderFilesSync } from "../file-utils/file-utils.lib";
import Knex from "knex";
import Objection, {
  Transaction,
  ModelClass,
  QueryBuilderType,
  TransactionOrKnex,
  SingleQueryBuilder,
} from "objection";
 
const modelFileRegex = /.*\.model\.(js|ts)$/;
 
// Initialize models in a folder
export const loadModels = (masterKnex: Knex, slaveKnex: Knex, folderPath: string) => {
  const models = loadFolderFilesSync(folderPath, fileName => modelFileRegex.test(fileName));
 
  process.stdout.write("loaded model:");
  for (const modelName of Object.keys(models)) {
    const model = models[modelName];
    model.default.knex(slaveKnex);
    model.default.knexOfMaster = function() {
      return masterKnex;
    };
    model.default.queryOnMaster = function(trx?: Knex.Transaction | boolean) {
      Iif (trx === true) {
        return model.default.query(masterKnex);
      } else Iif (trx === false) {
        return model.default.query();
      }
      Iif (trx) {
        return model.default.query(trx);
      }
      return model.default.query(masterKnex);
    };
    model.default.prototype.$queryOnMaster = function(trx?: Knex.Transaction | boolean) {
      Iif (trx === true) {
        return this.$query(masterKnex);
      } else Iif (trx === false) {
        return this.$query();
      }
      Iif (trx) {
        return this.$query(trx);
      }
      return this.$query(masterKnex);
    };
    process.stdout.write(`${modelName} `);
  }
  process.stdout.write("\n");
 
  return models;
};
 
declare module "objection" {
  namespace Model {
    // Get the knex connection which connect to the master node of a mySQL cluster
    export function knexOfMaster(): Knex;
 
    // Return an Objection.QueryBuilder which will be run on the master node of a mySQL cluster
    // when trx is false, will return a query run on the slave
    export function queryOnMaster<M extends Objection.Model>(
      this: ModelClass<M>,
      trx?: Transaction | boolean,
    ): QueryBuilderType<M>;
  }
 
  interface Model {
    $queryOnMaster(trx?: Transaction | boolean): SingleQueryBuilder<QueryBuilderType<this>>;
  }
}