2019-09-20 12:44:24 +02:00
|
|
|
'use strict';
|
|
|
|
|
2020-03-05 17:24:46 +01:00
|
|
|
const { replaceIdByPrimaryKey } = require('../utils/primary-key');
|
2020-04-23 18:14:12 +02:00
|
|
|
const { executeBeforeHook, executeAfterHook } = require('../utils/hooks');
|
2020-03-05 17:24:46 +01:00
|
|
|
|
2019-12-17 20:59:57 +01:00
|
|
|
module.exports = function createQuery(opts) {
|
2020-04-23 18:14:12 +02:00
|
|
|
const { model, connectorQuery } = opts;
|
|
|
|
|
|
|
|
return {
|
|
|
|
get model() {
|
|
|
|
return model;
|
|
|
|
},
|
|
|
|
|
|
|
|
get orm() {
|
|
|
|
return model.orm;
|
|
|
|
},
|
|
|
|
|
|
|
|
get primaryKey() {
|
|
|
|
return model.primaryKey;
|
|
|
|
},
|
|
|
|
|
|
|
|
get associations() {
|
|
|
|
return model.associations;
|
|
|
|
},
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Run custom database logic
|
|
|
|
*/
|
|
|
|
custom(mapping) {
|
|
|
|
if (typeof mapping === 'function') {
|
|
|
|
return mapping.bind(this, { model: this.model });
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!mapping[this.orm]) {
|
|
|
|
throw new Error(`Missing mapping for orm ${this.orm}`);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (typeof mapping[this.orm] !== 'function') {
|
|
|
|
throw new Error(`Custom queries must be functions received ${typeof mapping[this.orm]}`);
|
|
|
|
}
|
|
|
|
|
|
|
|
return mapping[this.model.orm].call(this, { model: this.model });
|
|
|
|
},
|
|
|
|
|
|
|
|
create: wrapQuery({ hook: 'create', model, connectorQuery }),
|
|
|
|
update: wrapQuery({ hook: 'update', model, connectorQuery }),
|
|
|
|
delete: wrapQuery({ hook: 'delete', model, connectorQuery }),
|
|
|
|
find: wrapQuery({ hook: 'find', model, connectorQuery }),
|
|
|
|
findOne: wrapQuery({ hook: 'findOne', model, connectorQuery }),
|
|
|
|
count: wrapQuery({ hook: 'count', model, connectorQuery }),
|
|
|
|
search: wrapQuery({ hook: 'search', model, connectorQuery }),
|
|
|
|
countSearch: wrapQuery({ hook: 'countSearch', model, connectorQuery }),
|
|
|
|
};
|
2019-09-20 12:44:24 +02:00
|
|
|
};
|
|
|
|
|
2020-04-23 18:14:12 +02:00
|
|
|
// wraps a connectorQuery call with:
|
|
|
|
// - param substitution
|
|
|
|
// - lifecycle hooks
|
|
|
|
const wrapQuery = ({ hook, model, connectorQuery }) => async (params, ...rest) => {
|
|
|
|
// substite id for primaryKey value in params
|
|
|
|
const newParams = replaceIdByPrimaryKey(params, model);
|
2020-04-20 22:27:20 +02:00
|
|
|
|
2020-04-23 18:14:12 +02:00
|
|
|
// execute before hook
|
|
|
|
await executeBeforeHook(hook, model, newParams, ...rest);
|
2020-04-20 22:27:20 +02:00
|
|
|
|
2020-04-23 18:14:12 +02:00
|
|
|
// execute query
|
|
|
|
const result = await connectorQuery[hook](newParams, ...rest);
|
2020-04-20 22:27:20 +02:00
|
|
|
|
2020-04-23 18:14:12 +02:00
|
|
|
// execute after hook
|
|
|
|
await executeAfterHook(hook, model, result);
|
2019-09-20 12:44:24 +02:00
|
|
|
|
2020-04-23 18:14:12 +02:00
|
|
|
// return result
|
|
|
|
return result;
|
|
|
|
};
|