@nsilly/repository
Version:
NF Repository is a abstract layer of Sequelize Application, that make application more easy to understand and flexible to maintain.
1,807 lines (1,515 loc) • 47.3 kB
JavaScript
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
exports.__esModule = true;
exports.Repository = void 0;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
var _lodash = _interopRequireDefault(require("lodash"));
var _exceptions = require("@nsilly/exceptions");
var _QueryBuilder = require("./Utils/QueryBuilder");
var _response = require("@nsilly/response");
var _support = require("@nsilly/support");
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { keys.push.apply(keys, Object.getOwnPropertySymbols(object)); } if (enumerableOnly) keys = keys.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { (0, _defineProperty2["default"])(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
var Repository =
/*#__PURE__*/
function () {
function Repository() {
this.builder = new _QueryBuilder.QueryBuilder();
this.paranoid = true;
this.raw = null;
}
/**
* Set Raw option
*
* @param {Boolean} raw Allow get raw data from database
*
* @return this
*/
var _proto = Repository.prototype;
_proto.setRaw = function setRaw(raw) {
if (!_lodash["default"].isBoolean(raw)) {
throw new _exceptions.Exception('Raw option can be boolean only');
}
this.raw = raw;
return this;
}
/**
* Create or update a record matching the attributes, and fill it with values
*
* @param {Object} attributes params to find resource
* @param {Object} values params to update or create new resource
*
* @return Object
*/
;
_proto.updateOrCreate =
/*#__PURE__*/
function () {
var _updateOrCreate = (0, _asyncToGenerator2["default"])(
/*#__PURE__*/
_regenerator["default"].mark(function _callee(attributes, values) {
var item, result;
return _regenerator["default"].wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
if (!_lodash["default"].isNil(attributes)) {
_context.next = 2;
break;
}
throw new _exceptions.Exception('attributes should not empty', 1000);
case 2:
_context.next = 4;
return this.Models().findOne({
where: attributes
});
case 4:
item = _context.sent;
if (!item) {
_context.next = 11;
break;
}
_context.next = 8;
return item.update(values);
case 8:
result = _context.sent;
_context.next = 14;
break;
case 11:
_context.next = 13;
return this.Models().create(values);
case 13:
result = _context.sent;
case 14:
return _context.abrupt("return", result);
case 15:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function updateOrCreate(_x, _x2) {
return _updateOrCreate.apply(this, arguments);
}
return updateOrCreate;
}()
/**
* Save a new model and return the instance.
*
* @param {Object} attributes create new resource with given params
*
* @return Object
*/
;
_proto.create =
/*#__PURE__*/
function () {
var _create = (0, _asyncToGenerator2["default"])(
/*#__PURE__*/
_regenerator["default"].mark(function _callee2(attributes) {
var result, associations, manyToManyAssociations, n, attributeKey, attributeVal, i;
return _regenerator["default"].wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
if (!_lodash["default"].isNil(attributes)) {
_context2.next = 2;
break;
}
throw new _exceptions.Exception('attributes should not empty', 1000);
case 2:
_context2.next = 4;
return this.Models().sequelize.transaction(function (t) {
return this.Models().create(attributes, {
transaction: t
});
}.bind(this));
case 4:
result = _context2.sent;
// add many to many associations before saving if there is
associations = this.Models().associations;
manyToManyAssociations = Object.keys(associations).filter(function (association) {
return associations[association].associationType === 'BelongsToMany';
});
n = 0;
case 8:
if (!(n < Object.keys(attributes).length)) {
_context2.next = 23;
break;
}
attributeKey = Object.keys(attributes)[n];
attributeVal = attributes[attributeKey];
if (!(manyToManyAssociations.indexOf(attributeKey) > -1)) {
_context2.next = 20;
break;
}
if (!attributeVal) {
_context2.next = 20;
break;
}
i = 0;
case 14:
if (!(i < attributeVal.length)) {
_context2.next = 20;
break;
}
_context2.next = 17;
return result['add' + _lodash["default"].capitalize(attributeKey)](attributeVal[i]);
case 17:
i++;
_context2.next = 14;
break;
case 20:
n++;
_context2.next = 8;
break;
case 23:
if (!_lodash["default"].isNil(result)) {
_context2.next = 25;
break;
}
throw new _exceptions.Exception('Can not create resource', 1004);
case 25:
return _context2.abrupt("return", result);
case 26:
case "end":
return _context2.stop();
}
}
}, _callee2, this);
}));
function create(_x3) {
return _create.apply(this, arguments);
}
return create;
}()
/**
* Find the first resource that match with given params or create new one if not exist
*
* @param {Object} attributes find or create new resource with given params
*
* @return Object
*/
;
_proto.firstOrCreate =
/*#__PURE__*/
function () {
var _firstOrCreate = (0, _asyncToGenerator2["default"])(
/*#__PURE__*/
_regenerator["default"].mark(function _callee3(attributes) {
var result, associations, manyToManyAssociations, n, attributeKey, attributeVal, i;
return _regenerator["default"].wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
if (!_lodash["default"].isNil(attributes)) {
_context3.next = 2;
break;
}
throw new _exceptions.Exception('attributes should not empty', 1000);
case 2:
_context3.next = 4;
return this.Models().findOne({
where: attributes
});
case 4:
result = _context3.sent;
if (result) {
_context3.next = 29;
break;
}
_context3.next = 8;
return this.Models().sequelize.transaction(function (t) {
return this.Models().create(attributes, {
transaction: t
});
}.bind(this));
case 8:
result = _context3.sent;
associations = this.Models().associations;
manyToManyAssociations = Object.keys(associations).filter(function (association) {
return associations[association].associationType === 'BelongsToMany';
});
n = 0;
case 12:
if (!(n < Object.keys(attributes).length)) {
_context3.next = 27;
break;
}
attributeKey = Object.keys(attributes)[n];
attributeVal = attributes[attributeKey];
if (!(manyToManyAssociations.indexOf(attributeKey) > -1)) {
_context3.next = 24;
break;
}
if (!attributeVal) {
_context3.next = 24;
break;
}
i = 0;
case 18:
if (!(i < attributeVal.length)) {
_context3.next = 24;
break;
}
_context3.next = 21;
return result['add' + _lodash["default"].capitalize(attributeKey)](attributeVal[i]);
case 21:
i++;
_context3.next = 18;
break;
case 24:
n++;
_context3.next = 12;
break;
case 27:
if (!_lodash["default"].isNil(result)) {
_context3.next = 29;
break;
}
throw new _exceptions.Exception('Can not create resource', 1004);
case 29:
return _context3.abrupt("return", result);
case 30:
case "end":
return _context3.stop();
}
}
}, _callee3, this);
}));
function firstOrCreate(_x4) {
return _firstOrCreate.apply(this, arguments);
}
return firstOrCreate;
}()
/**
* Update multiple instances that match the where options
*
* @param {Object} attributes values to update resource
* @param {Integer} id Update resource with given ID
*
* @return Object
*/
;
_proto.update =
/*#__PURE__*/
function () {
var _update = (0, _asyncToGenerator2["default"])(
/*#__PURE__*/
_regenerator["default"].mark(function _callee4(attributes, id) {
var result, item;
return _regenerator["default"].wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
if (id === void 0) {
id = undefined;
}
if (!_lodash["default"].isNil(attributes)) {
_context4.next = 3;
break;
}
throw new _exceptions.Exception('attributes should not empty', 1000);
case 3:
if (!_lodash["default"].isUndefined(id)) {
_context4.next = 9;
break;
}
_context4.next = 6;
return this.Models().update(attributes, {
where: this.getWheres()
});
case 6:
result = _context4.sent;
_context4.next = 15;
break;
case 9:
_context4.next = 11;
return this.findById(id);
case 11:
item = _context4.sent;
_context4.next = 14;
return item.update(attributes);
case 14:
result = _context4.sent;
case 15:
return _context4.abrupt("return", result);
case 16:
case "end":
return _context4.stop();
}
}
}, _callee4, this);
}));
function update(_x5, _x6) {
return _update.apply(this, arguments);
}
return update;
}();
_proto.bulkCreate =
/*#__PURE__*/
function () {
var _bulkCreate = (0, _asyncToGenerator2["default"])(
/*#__PURE__*/
_regenerator["default"].mark(function _callee5(attributesArr, individual) {
var result;
return _regenerator["default"].wrap(function _callee5$(_context5) {
while (1) {
switch (_context5.prev = _context5.next) {
case 0:
if (individual === void 0) {
individual = false;
}
_context5.next = 3;
return this.Models().bulkCreate(attributesArr, {
individualHooks: individual
});
case 3:
result = _context5.sent;
return _context5.abrupt("return", result);
case 5:
case "end":
return _context5.stop();
}
}
}, _callee5, this);
}));
function bulkCreate(_x7, _x8) {
return _bulkCreate.apply(this, arguments);
}
return bulkCreate;
}();
_proto.bulkUpsert = function bulkUpsert(attributes) {
var _this = this;
if (Array.isArray(attributes)) {
return Promise.all(attributes.map(function (attribute) {
return _this.singleUpsert(attribute);
}));
} else {
return this.singleUpsert(attributes);
}
};
_proto.replaceRelations =
/*#__PURE__*/
function () {
var _replaceRelations = (0, _asyncToGenerator2["default"])(
/*#__PURE__*/
_regenerator["default"].mark(function _callee6(result, attributes, extraInfo) {
var associations, n, attributeKey, attributeVal, data, i, x;
return _regenerator["default"].wrap(function _callee6$(_context6) {
while (1) {
switch (_context6.prev = _context6.next) {
case 0:
if (extraInfo === void 0) {
extraInfo = {};
}
associations = Object.keys(this.Models().associations);
n = 0;
case 3:
if (!(n < Object.keys(attributes).length)) {
_context6.next = 42;
break;
}
attributeKey = Object.keys(attributes)[n];
attributeVal = attributes[attributeKey];
if (!(associations.indexOf(attributeKey) > -1)) {
_context6.next = 39;
break;
}
if (!attributeVal) {
_context6.next = 39;
break;
}
_context6.next = 10;
return result['get' + _lodash["default"].capitalize(attributeKey)]();
case 10:
data = _context6.sent;
if (!(Array.isArray(data) && Array.isArray(attributeVal))) {
_context6.next = 20;
break;
}
i = 0;
case 13:
if (!(i < data.length)) {
_context6.next = 20;
break;
}
if (!(attributeVal.indexOf(data[i].id) === -1)) {
_context6.next = 17;
break;
}
_context6.next = 17;
return data[i].destroy();
case 17:
i++;
_context6.next = 13;
break;
case 20:
if (!(typeof extraInfo[attributeKey] !== 'undefined')) {
_context6.next = 37;
break;
}
if (!Array.isArray(extraInfo[attributeKey])) {
_context6.next = 33;
break;
}
_context6.next = 24;
return result['set' + _lodash["default"].capitalize(attributeKey)](null);
case 24:
x = 0;
case 25:
if (!(x < extraInfo[attributeKey].length)) {
_context6.next = 31;
break;
}
_context6.next = 28;
return result['add' + _lodash["default"].capitalize(attributeKey)]([attributeVal[x]], {
through: extraInfo[attributeKey][x]
});
case 28:
x++;
_context6.next = 25;
break;
case 31:
_context6.next = 35;
break;
case 33:
_context6.next = 35;
return result['set' + _lodash["default"].capitalize(attributeKey)](attributeVal, {
through: extraInfo[attributeKey]
});
case 35:
_context6.next = 39;
break;
case 37:
_context6.next = 39;
return result['set' + _lodash["default"].capitalize(attributeKey)](attributeVal);
case 39:
n++;
_context6.next = 3;
break;
case 42:
return _context6.abrupt("return", result);
case 43:
case "end":
return _context6.stop();
}
}
}, _callee6, this);
}));
function replaceRelations(_x9, _x10, _x11) {
return _replaceRelations.apply(this, arguments);
}
return replaceRelations;
}();
_proto.getNonRelationAttribute = function getNonRelationAttribute(attributes) {
var associations = Object.keys(this.Models().associations);
var newAttribute = {};
for (var n = 0; n < Object.keys(attributes).length; n++) {
var attributeKey = Object.keys(attributes)[n];
var attributeVal = attributes[attributeKey];
if (associations.indexOf(attributeKey) === -1) {
newAttribute[attributeKey] = attributeVal;
}
}
return newAttribute;
};
_proto.singleUpsert =
/*#__PURE__*/
function () {
var _singleUpsert = (0, _asyncToGenerator2["default"])(
/*#__PURE__*/
_regenerator["default"].mark(function _callee7(attribute) {
var identifier, attributeParsed, additionalRelationInfo, result, item;
return _regenerator["default"].wrap(function _callee7$(_context7) {
while (1) {
switch (_context7.prev = _context7.next) {
case 0:
identifier = {};
attributeParsed = {};
additionalRelationInfo = {};
Object.keys(attribute).forEach(function (key) {
if (key.indexOf('__relation_info__') === -1) {
if (key.indexOf('__unique__') > -1) {
if (attribute[key]) {
identifier[key.replace('__unique__', '')] = attribute[key];
}
} else {
attributeParsed[key] = attribute[key];
}
} else {
additionalRelationInfo[key.replace('__relation_info__', '')] = attribute[key];
}
});
if (!(Object.keys(identifier).length > 0)) {
_context7.next = 23;
break;
}
_context7.next = 7;
return this.Models().findOne({
where: identifier
});
case 7:
item = _context7.sent;
if (!item) {
_context7.next = 16;
break;
}
_context7.next = 11;
return item.update(this.getNonRelationAttribute(attributeParsed));
case 11:
result = _context7.sent;
_context7.next = 14;
return this.replaceRelations(result, attributeParsed, additionalRelationInfo);
case 14:
_context7.next = 21;
break;
case 16:
_context7.next = 18;
return this.Models().create(_objectSpread({}, this.getNonRelationAttribute(attributeParsed), {}, identifier));
case 18:
result = _context7.sent;
_context7.next = 21;
return this.replaceRelations(result, attributeParsed, additionalRelationInfo);
case 21:
_context7.next = 28;
break;
case 23:
_context7.next = 25;
return this.Models().create(this.getNonRelationAttribute(attributeParsed));
case 25:
result = _context7.sent;
_context7.next = 28;
return this.replaceRelations(result, attributeParsed, additionalRelationInfo);
case 28:
return _context7.abrupt("return", result);
case 29:
case "end":
return _context7.stop();
}
}
}, _callee7, this);
}));
function singleUpsert(_x12) {
return _singleUpsert.apply(this, arguments);
}
return singleUpsert;
}();
_proto.bulkDelete = function bulkDelete(attributes) {
var _this2 = this;
if (Array.isArray(attributes)) {
return Promise.all(attributes.map(function (attribute) {
return _this2.Models().destroy({
where: attribute
});
}));
} else {
return this.Models().destroy({
where: attributes
});
}
}
/**
* Get the first record
*
* @return Object
*/
;
_proto.first =
/*#__PURE__*/
function () {
var _first = (0, _asyncToGenerator2["default"])(
/*#__PURE__*/
_regenerator["default"].mark(function _callee8() {
var params, model, result;
return _regenerator["default"].wrap(function _callee8$(_context8) {
while (1) {
switch (_context8.prev = _context8.next) {
case 0:
params = {
where: this.getWheres(),
include: this.getIncludes(),
order: this.getOrders()
};
if (_lodash["default"].isBoolean(this.raw)) {
params = _objectSpread({}, params, {}, {
raw: this.raw
});
}
if (_lodash["default"].isArray(this.getAttributes()) && this.getAttributes().length > 0) {
params = _lodash["default"].assign(params, {
attributes: this.getAttributes()
});
}
model = this.Models();
if (this.getScopes().length > 0) {
model = model.scope(this.getScopes());
}
_context8.next = 7;
return model.findOne(params);
case 7:
result = _context8.sent;
return _context8.abrupt("return", result);
case 9:
case "end":
return _context8.stop();
}
}
}, _callee8, this);
}));
function first() {
return _first.apply(this, arguments);
}
return first;
}()
/**
* Execute the query and get the first result or throw an exception
*
* @return Object
*/
;
_proto.firstOrFail =
/*#__PURE__*/
function () {
var _firstOrFail = (0, _asyncToGenerator2["default"])(
/*#__PURE__*/
_regenerator["default"].mark(function _callee9() {
var result;
return _regenerator["default"].wrap(function _callee9$(_context9) {
while (1) {
switch (_context9.prev = _context9.next) {
case 0:
result = this.first();
if (result) {
_context9.next = 3;
break;
}
throw new _exceptions.NotFoundException('Resource');
case 3:
return _context9.abrupt("return", result);
case 4:
case "end":
return _context9.stop();
}
}
}, _callee9, this);
}));
function firstOrFail() {
return _firstOrFail.apply(this, arguments);
}
return firstOrFail;
}()
/**
* Find a model by its primary key.
*
* @param {Integer} ID find resource with given ID
*
* @return Boolean
* @throws Exception
*/
;
_proto.findById =
/*#__PURE__*/
function () {
var _findById = (0, _asyncToGenerator2["default"])(
/*#__PURE__*/
_regenerator["default"].mark(function _callee10(id) {
var params, model, result;
return _regenerator["default"].wrap(function _callee10$(_context10) {
while (1) {
switch (_context10.prev = _context10.next) {
case 0:
params = {
where: {
id: id
},
include: this.getIncludes(),
paranoid: this.paranoid
};
if (_lodash["default"].isArray(this.getAttributes()) && this.getAttributes().length > 0) {
params = _lodash["default"].assign(params, {
attributes: this.getAttributes()
});
}
model = this.Models();
if (this.getScopes().length > 0) {
model = model.scope(this.getScopes());
}
_context10.next = 6;
return model.findOne(params);
case 6:
result = _context10.sent;
if (result) {
_context10.next = 9;
break;
}
throw new _exceptions.NotFoundException('Resource');
case 9:
return _context10.abrupt("return", result);
case 10:
case "end":
return _context10.stop();
}
}
}, _callee10, this);
}));
function findById(_x13) {
return _findById.apply(this, arguments);
}
return findById;
}()
/**
* Delete a model by its primary key.
*
* @param {Integer} id delete resource with given ID
*
* @return Boolean
* @throws Exception
*/
;
_proto.deleteById =
/*#__PURE__*/
function () {
var _deleteById = (0, _asyncToGenerator2["default"])(
/*#__PURE__*/
_regenerator["default"].mark(function _callee11(id, options) {
var item, result;
return _regenerator["default"].wrap(function _callee11$(_context11) {
while (1) {
switch (_context11.prev = _context11.next) {
case 0:
if (options === void 0) {
options = {};
}
_context11.next = 3;
return this.findById(id);
case 3:
item = _context11.sent;
if (!(!_lodash["default"].isUndefined(options.force) && options.force === true)) {
_context11.next = 8;
break;
}
_context11.next = 7;
return item.destroy({
force: true
});
case 7:
result = _context11.sent;
case 8:
_context11.next = 10;
return item.destroy();
case 10:
result = _context11.sent;
if (!(result === false)) {
_context11.next = 13;
break;
}
throw new _exceptions.Exception('can not delete resource', 1002);
case 13:
return _context11.abrupt("return", result);
case 14:
case "end":
return _context11.stop();
}
}
}, _callee11, this);
}));
function deleteById(_x14, _x15) {
return _deleteById.apply(this, arguments);
}
return deleteById;
}()
/**
* Delete resources by given condition
*
* @return Boolean
* @throws Exception
*/
;
_proto["delete"] =
/*#__PURE__*/
function () {
var _delete2 = (0, _asyncToGenerator2["default"])(
/*#__PURE__*/
_regenerator["default"].mark(function _callee12(options) {
var result;
return _regenerator["default"].wrap(function _callee12$(_context12) {
while (1) {
switch (_context12.prev = _context12.next) {
case 0:
if (options === void 0) {
options = {};
}
if (!(!_lodash["default"].isUndefined(options.force) && options.force === true)) {
_context12.next = 7;
break;
}
_context12.next = 4;
return this.Models().destroy({
where: this.getWheres(),
force: true
});
case 4:
result = _context12.sent;
_context12.next = 10;
break;
case 7:
_context12.next = 9;
return this.Models().destroy({
where: this.getWheres()
});
case 9:
result = _context12.sent;
case 10:
return _context12.abrupt("return", result);
case 11:
case "end":
return _context12.stop();
}
}
}, _callee12, this);
}));
function _delete(_x16) {
return _delete2.apply(this, arguments);
}
return _delete;
}()
/**
* Execute the query as a "select" statement.
*
* @return Array
*/
;
_proto.get =
/*#__PURE__*/
function () {
var _get = (0, _asyncToGenerator2["default"])(
/*#__PURE__*/
_regenerator["default"].mark(function _callee13() {
var params, limit, offset, model, result;
return _regenerator["default"].wrap(function _callee13$(_context13) {
while (1) {
switch (_context13.prev = _context13.next) {
case 0:
params = {
where: this.getWheres(),
include: this.getIncludes(),
order: this.getOrders(),
group: this.getGroup(),
paranoid: this.paranoid,
limit: this.getLimit(),
offset: this.getOffset()
};
limit = this.getLimit();
if (!_lodash["default"].isUndefined(limit)) {
params = _lodash["default"].assign(params, {
limit: limit
});
}
offset = this.getOffset();
if (!_lodash["default"].isUndefined(offset)) {
params = _lodash["default"].assign(params, {
offset: offset
});
}
if (_lodash["default"].isBoolean(this.raw)) {
params = _objectSpread({}, params, {}, {
raw: this.raw
});
}
if (_lodash["default"].isArray(this.getAttributes()) && this.getAttributes().length > 0) {
params = _lodash["default"].assign(params, {
attributes: this.getAttributes()
});
}
model = this.Models();
if (this.getScopes().length > 0) {
model = model.scope(this.getScopes());
}
_context13.next = 11;
return model.findAll(params);
case 11:
result = _context13.sent;
return _context13.abrupt("return", result);
case 13:
case "end":
return _context13.stop();
}
}
}, _callee13, this);
}));
function get() {
return _get.apply(this, arguments);
}
return get;
}()
/**
* Retrieve the "count" result of the query.
*
* @return int
*/
;
_proto.count =
/*#__PURE__*/
function () {
var _count = (0, _asyncToGenerator2["default"])(
/*#__PURE__*/
_regenerator["default"].mark(function _callee14() {
var params, model, result;
return _regenerator["default"].wrap(function _callee14$(_context14) {
while (1) {
switch (_context14.prev = _context14.next) {
case 0:
params = {
where: this.getWheres(),
include: this.getIncludes(),
order: this.getOrders(),
distinct: true
};
model = this.Models();
if (this.getScopes().length > 0) {
model = model.scope(this.getScopes());
}
_context14.next = 5;
return model.count(params);
case 5:
result = _context14.sent;
return _context14.abrupt("return", result);
case 7:
case "end":
return _context14.stop();
}
}
}, _callee14, this);
}));
function count() {
return _count.apply(this, arguments);
}
return count;
}()
/**
* Paginate the given query.
*
* @param {Integer} per_page number item per page
* @param {Integer|null} page page number
*
* @return LengthAwarePaginator
*/
;
_proto.paginate =
/*#__PURE__*/
function () {
var _paginate = (0, _asyncToGenerator2["default"])(
/*#__PURE__*/
_regenerator["default"].mark(function _callee15(per_page, page) {
var params, model, result, paginator;
return _regenerator["default"].wrap(function _callee15$(_context15) {
while (1) {
switch (_context15.prev = _context15.next) {
case 0:
if (per_page === void 0) {
per_page = null;
}
if (page === void 0) {
page = null;
}
if (!_lodash["default"].isNil(per_page)) {
per_page = parseInt(per_page);
} else {
if (_support.Request.has('per_page')) {
per_page = parseInt(_support.Request.get('per_page'));
} else {
per_page = 20;
}
}
if (!_lodash["default"].isNil(page)) {
page = parseInt(page);
} else {
if (_support.Request.has('page')) {
page = parseInt(_support.Request.get('page'));
} else {
page = 1;
}
}
params = {
offset: (page - 1) * per_page,
limit: per_page,
where: this.getWheres(),
include: this.getIncludes(),
order: this.getOrders(),
distinct: true,
paranoid: this.paranoid
};
if (_lodash["default"].isBoolean(this.raw)) {
params = _objectSpread({}, params, {}, {
raw: this.raw
});
}
if (_lodash["default"].isArray(this.getAttributes()) && this.getAttributes().length > 0) {
params = _lodash["default"].assign(params, {
attributes: this.getAttributes()
});
}
model = this.Models();
if (this.getScopes().length > 0) {
model = model.scope(this.getScopes());
}
_context15.next = 11;
return model.findAndCountAll(params);
case 11:
result = _context15.sent;
paginator = new _response.LengthAwarePaginator(result.rows, result.count, per_page, page);
return _context15.abrupt("return", paginator);
case 14:
case "end":
return _context15.stop();
}
}
}, _callee15, this);
}));
function paginate(_x17, _x18) {
return _paginate.apply(this, arguments);
}
return paginate;
}();
_proto.fromPagination =
/*#__PURE__*/
function () {
var _fromPagination = (0, _asyncToGenerator2["default"])(
/*#__PURE__*/
_regenerator["default"].mark(function _callee16(pagination) {
var paginationObj;
return _regenerator["default"].wrap(function _callee16$(_context16) {
while (1) {
switch (_context16.prev = _context16.next) {
case 0:
paginationObj = pagination.getData();
paginationObj.operation.forEach(function (op) {
this[op.type].apply(this, op.content);
}.bind(this));
return _context16.abrupt("return", pagination.result(this.paginate.bind(this)));
case 3:
case "end":
return _context16.stop();
}
}
}, _callee16, this);
}));
function fromPagination(_x19) {
return _fromPagination.apply(this, arguments);
}
return fromPagination;
}()
/**
* Add a basic "WHERE" clause to the query.
*
* @param {String} column Column name
* @param {mixed} operator Operator or Value
* @param {mixed} value Value
*
* @return this
*/
;
_proto.where = function where() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
if (args.length === 1) {
var raw = false;
if (args[0].constructor) {
if (args[0].constructor.name === 'Where') {
raw = true;
} else if (args[0].constructor.name === 'Literal') {
raw = true;
}
}
if (raw) {
this.builder.where.apply(this.builder, [].concat(args));
} else {
var callable = args[0];
var builder = new _QueryBuilder.QueryBuilder();
var query = callable(builder);
this.builder.scopeQuery.apply(this.builder, [query]);
}
} else {
this.builder.where.apply(this.builder, [].concat(args));
}
return this;
}
/**
* Add an "OR WHERE" clause to the query.
*
* @param {String} column Column name
* @param {String|null} operator Operator or Value
* @param {mixed} value Value
*
* @return this
*/
;
_proto.orWhere = function orWhere() {
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
this.builder.orWhere.apply(this.builder, [].concat(args));
return this;
}
/**
* Add an "WHERE IN" clause to the query.
*
* @param {String} column Column name
* @param {Array} value Array of values
*
* @return this
*/
;
_proto.whereIn = function whereIn(column, value) {
this.builder.whereIn(column, value);
return this;
}
/**
* Add an "OR WHERE IN" clause to the query.
*
* @param {String} column Column name
* @param {Array} value Array of values
*
* @return this
*/
;
_proto.orWhereIn = function orWhereIn(column, value) {
this.builder.orWhereIn(column, value);
return this;
}
/**
* Add an "WHERE NOT IN" clause to the query.
*
* @param {String} column Column name
* @param array value
*
* @return this
*/
;
_proto.whereNotIn = function whereNotIn(column, value) {
this.builder.whereNotIn(column, value);
return this;
}
/**
* Add a basic where clause with relation to the query.
*
* @param {String} relation Relation
* @param {Callable} callable Callback
*
* @return this
*/
;
_proto.whereHas = function whereHas(relation, callable, options) {
var builder = new _QueryBuilder.QueryBuilder();
builder = callable(builder);
this.builder.whereHas.apply(this.builder, [relation, builder, options]);
return this;
}
/**
* include another table that has many to many relationship with it
*
* @param {String} relation Relation
* @param {Callable} callable Callback
*
* @return this
*/
;
_proto.includeThroughWhere = function includeThroughWhere(relation, callable) {
var builder = new _QueryBuilder.QueryBuilder();
builder = callable(builder);
this.builder.whereHas.apply(this.builder, [relation, builder]);
return this;
}
/**
* Alias to set the "offset" value of the query.
*
* @param {Integer} value Number of record to skip
*
* @return self
*/
;
_proto.skip = function skip(offset) {
this.builder.skip(offset);
return this;
}
/**
* Alias to set the "limit" value of the query.
*
* @param {Integer} value Number of record to take
*
* @return this
*/
;
_proto.take = function take(limit) {
this.builder.take(limit);
return this;
}
/**
* Add an "order by" clause to the query.
*
* @param {String} column Column name to order
* @param {String} direction [ASC|DESC]
*
* @return this
*/
;
_proto.orderBy = function orderBy() {
var model;
var field;
var direction = 'ASC';
for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
args[_key3] = arguments[_key3];
}
if (args.length === 2) {
field = args[0];
direction = args[1];
this.builder.orderBy(field, direction);
}
if (args.length === 3) {
model = args[0];
field = args[1];
direction = args[2];
this.builder.orderBy(model, field, direction);
}
if (args.length === 1) {
field = args[0];
this.builder.orderBy(field);
}
return this;
}
/**
* Add an "GROUP BY" clause to the query.
*
* @param {String} column Column to group
*
* @return self
*/
;
_proto.groupBy = function groupBy(column) {
this.builder.groupBy(column);
return this;
}
/**
* Extract order param from request and apply the rule
*
* @param {Array} fields Supported fields to order
*
* @return Repository
*/
;
_proto.applyOrderFromRequest = function applyOrderFromRequest(fields, functions) {
var _this3 = this;
if (fields === void 0) {
fields = [];
}
if (functions === void 0) {
functions = {};
}
if (_support.Request.has('sort') && _support.Request.get('sort') !== '') {
var orderBy = _support.Request.get('sort').split(',');
orderBy.forEach(function (field) {
var direction = 'ASC';
if (field.charAt(0) === '-') {
direction = 'DESC';
field = field.slice(1);
}
if (field.charAt(0) === '+') {
field = field.slice(1);
}
if (fields.length === 0 || fields.length > 0 && _lodash["default"].includes(fields, field)) {
// custom functions to be given aligned with field name
if (typeof functions[field] !== 'undefined') {
functions[field](direction);
} else {
_this3.orderBy(field, direction);
}
}
});
}
return this;
}
/**
* Extract search param from request and apply the rule
*
* @param {Array} fields Supported fields to search
*
* @return Repository
*/
;
_proto.applySearchFromRequest = function applySearchFromRequest(fields, match) {
if (match === void 0) {
match = null;
}
if (_support.Request.has('search') && _support.Request.get('search') !== '') {
if (_lodash["default"].isNull(match)) {
match = "%" + _support.Request.get('search') + "%";
}
this.where(function (q) {
_lodash["default"].forEach(fields, function (field) {
q.orWhere(field, 'like', match);
});
return q;
});
}
return this;
}
/**
* Extract constraints param from request and apply the rule
* when supplied custom, it will check from the custom object for its implementation function instead of default where
*
* @param {Object} custom object consisting key of entity type with custom implementation as the value
*
* @return Repository
*/
;
_proto.applyConstraintsFromRequest = function applyConstraintsFromRequest(custom) {
if (custom === void 0) {
custom = {};
}
if (_support.Request.has('constraints') || _support.Request.get('constraints') !== '') {
var data = _support.Request.get('constraints', {});
var constraints = {};
if (typeof data === 'object') {
constraints = _support.Request.get('constraints');
} else {
constraints = JSON.parse(_support.Request.get('constraints'));
}
for (var key in constraints) {
if (typeof custom[key] !== 'undefined') {
custom[key](constraints[key]);
} else {
this.where(key, constraints[key]);
}
}
return this;
}
}
/**
* Begin querying a model with eager loading.
*
* @param {Array|String} relation Relation name
*
* @return this
*/
;
_proto["with"] = function _with() {
for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
args[_key4] = arguments[_key4];
}
this.builder["with"].apply(this.builder, args);
return this;
}
/**
* Include deleted records
*
* @return this
*/
;
_proto.withTrashed = function withTrashed() {
this.paranoid = false;
return this;
}
/**
* Add scope to the query
*
* @param {String} scope Scope to include
*
* @return this
*/
;
_proto.withScope = function withScope(scope) {
this.builder.withScope(scope);
return this;
}
/**
* Set the columns to be selected.
*
* @param {Array|mixed} columns Columns to select
*
* @return this
*/
;
_proto.select = function select(columns) {
this.builder.select.apply(this.builder, [columns]);
return this;
}
/**
* Get the sequilize where condition
*
* @return Object
*/
;
_proto.getWheres = function getWheres() {
return this.builder.buildWhereQuery();
}
/**
* Get the limit value of the builder
*
* @return int
*/
;
_proto.getLimit = function getLimit() {
return this.builder.limit;
}
/**
* Get the offset value of the builder
*
* @return int
*/
;
_proto.getOffset = function getOffset() {
return this.builder.offset;
}
/**
* Get the orders value of the builder
*
* @return array
*/
;
_proto.getOrders = function getOrders() {
return this.builder.orders;
}
/**
* Get the group value of the builder
*
* @return array
*/
;
_proto.getGroup = function getGroup() {
return this.builder.group;
}
/**
* Get the includes value of the builder
*
* @return array
*/
;
_proto.getIncludes = function getIncludes() {
return this.builder.includes;
}
/**
* Get the scopes value of the builder
*
* @return array
*/
;
_proto.getScopes = function getScopes() {
return this.builder.scopes;
}
/**
* Get the attributes value of the builder
*
* @return array
*/
;
_proto.getAttributes = function getAttributes() {
return this.builder.attributes;
};
return Repository;
}();
exports.Repository = Repository;