@@ -17,6 +17,19 @@ import { jsonCompare } from './helpers.js';
1717export default class Engine < R = unknown > {
1818 //database connection
1919 public readonly connection : Connection < R > ;
20+ //A hook used for logging purposes. Can also manipulate the final
21+ // query before execution. Can also provide the results of the query,
22+ // in which case the database will not be queried.
23+ protected _before : < R = unknown > (
24+ request : QueryObject
25+ ) => Promise < R [ ] | void > = async ( _request : QueryObject ) => { } ;
26+
27+ /**
28+ * Returns the before hook
29+ */
30+ public get before ( ) {
31+ return this . _before ;
32+ }
2033
2134 /**
2235 * Returns sql dialect
@@ -25,6 +38,15 @@ export default class Engine<R = unknown> {
2538 return this . connection . dialect ;
2639 }
2740
41+ /**
42+ * Sets the before hook
43+ */
44+ public set before ( before : < R = unknown > (
45+ request : QueryObject
46+ ) => Promise < R [ ] | void > ) {
47+ this . _before = before ;
48+ }
49+
2850 /**
2951 * Sets the query callback
3052 */
@@ -183,13 +205,19 @@ export default class Engine<R = unknown> {
183205 * native database engine connection. Any code that uses
184206 * this library should not care about the kind of database.
185207 */
186- public query < R = unknown > ( query : QueryObject ) : Promise < R [ ] > ;
187- public query < R = unknown > ( query : string , values ?: Value [ ] ) : Promise < R [ ] > ;
188- public query < R = unknown > ( query : string | QueryObject , values : Value [ ] = [ ] ) {
208+ public async query < R = unknown > ( query : QueryObject ) : Promise < R [ ] > ;
209+ public async query < R = unknown > ( query : string , values ?: Value [ ] ) : Promise < R [ ] > ;
210+ public async query < R = unknown > ( query : string | QueryObject , values : Value [ ] = [ ] ) {
189211 if ( typeof query === 'string' ) {
190212 query = { query, values } ;
191213 }
192- return this . connection . query < R > ( query ) ;
214+ //allow last minute request manipulation and
215+ // possibly short circuit the query with results
216+ const results = await this . _before ( query ) ;
217+ //if results were provided, return them
218+ if ( results ) return results ;
219+ //otherwise, query the database
220+ return await this . connection . query < R > ( query ) ;
193221 }
194222
195223 /**
0 commit comments