11import type { Knex } from 'knex' ;
22import _ from 'lodash' ;
3- import { Model } from 'objection' ;
3+ import { type Constructor , Model } from 'objection' ;
44
55import { defaultDispatcherOptions , defaultExLogger , defaultKnexOptions } from './constants' ;
66import { PGDispatcher } from './dispatcher' ;
@@ -13,16 +13,22 @@ export interface CoreDBDispatcherOptions {
1313 beforeTerminate ?: ( ) => Promise < void > ;
1414}
1515
16+ export type GetModelParams = { cancelOnTimeout ?: boolean ; useLimitInFirst ?: boolean } ;
17+
1618export interface CoreDBConstructorArgs {
1719 connectionString : string ;
1820 dispatcherOptions ?: CoreDBDispatcherOptions ;
1921 knexOptions ?: Knex . Config ;
2022 logger ?: ExLogger ;
23+ modelParams ?: GetModelParams ;
2124}
2225
23- export function getModel ( ) : typeof BaseModel {
26+ export function getModel ( params : GetModelParams = { } ) : typeof BaseModel {
2427 let _db : PGDispatcher ;
2528
29+ const cancelOnTimeout = Boolean ( params . cancelOnTimeout ) ;
30+ const useLimitInFirst = Boolean ( params . useLimitInFirst ) ;
31+
2632 class CoreBaseModel extends Model {
2733 static set db ( value : PGDispatcher ) {
2834 if ( ! _db ) {
@@ -45,6 +51,28 @@ export function getModel(): typeof BaseModel {
4551 get replica ( ) {
4652 return _db . replica ;
4753 }
54+
55+ static query < M extends Model > (
56+ this : Constructor < M > ,
57+ ...args : Parameters < typeof Model . query < M > >
58+ ) : ReturnType < typeof Model . query < M > > {
59+ const query = super . query < M > ( ...args ) ;
60+
61+ if ( cancelOnTimeout ) {
62+ const originalTimeout = query . timeout ;
63+
64+ query . timeout = ( ms , options ) => {
65+ const optionsWithCancel = { cancel : true , ...( options ?? { } ) } ;
66+ return originalTimeout . apply ( query , [ ms , optionsWithCancel ] ) ;
67+ } ;
68+ }
69+
70+ return query ;
71+ }
72+
73+ static get useLimitInFirst ( ) {
74+ return useLimitInFirst ;
75+ }
4876 }
4977
5078 return CoreBaseModel ;
@@ -55,6 +83,7 @@ export function initDB({
5583 dispatcherOptions,
5684 knexOptions = { } ,
5785 logger = defaultExLogger ,
86+ modelParams,
5887} : CoreDBConstructorArgs ) {
5988 if ( ! connectionString ) {
6089 throw new Error ( 'Empty connection string' ) ;
@@ -83,7 +112,7 @@ export function initDB({
83112
84113 process . on ( 'SIGINT' , terminate ) ;
85114
86- const CoreBaseModel = getModel ( ) ;
115+ const CoreBaseModel = getModel ( modelParams ) ;
87116 CoreBaseModel . db = db ;
88117
89118 const helpers = {
0 commit comments