nestjs-paginate
Version:
Pagination and filtering helper method for TypeORM repositories or query builders using Nest.js framework.
252 lines • 11.9 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.positiveNumberOrDefault = void 0;
exports.isEntityKey = isEntityKey;
exports.getPropertiesByColumnName = getPropertiesByColumnName;
exports.extractVirtualProperty = extractVirtualProperty;
exports.includesAllPrimaryKeyColumns = includesAllPrimaryKeyColumns;
exports.getPrimaryKeyColumns = getPrimaryKeyColumns;
exports.getMissingPrimaryKeyColumns = getMissingPrimaryKeyColumns;
exports.hasColumnWithPropertyPath = hasColumnWithPropertyPath;
exports.checkIsRelation = checkIsRelation;
exports.checkIsNestedRelation = checkIsNestedRelation;
exports.checkIsEmbedded = checkIsEmbedded;
exports.checkIsArray = checkIsArray;
exports.checkIsJsonb = checkIsJsonb;
exports.fixColumnAlias = fixColumnAlias;
exports.getQueryUrlComponents = getQueryUrlComponents;
exports.isISODate = isISODate;
exports.isRepository = isRepository;
exports.isFindOperator = isFindOperator;
exports.createRelationSchema = createRelationSchema;
exports.mergeRelationSchema = mergeRelationSchema;
exports.getPaddedExpr = getPaddedExpr;
exports.isDateColumnType = isDateColumnType;
exports.quoteVirtualColumn = quoteVirtualColumn;
const lodash_1 = require("lodash");
const typeorm_1 = require("typeorm");
const OrmUtils_1 = require("typeorm/util/OrmUtils");
function isEntityKey(entityColumns, column) {
return !!entityColumns.find((c) => c === column);
}
const positiveNumberOrDefault = (value, defaultValue, minValue = 0) => value === undefined || value < minValue ? defaultValue : value;
exports.positiveNumberOrDefault = positiveNumberOrDefault;
function getPropertiesByColumnName(column) {
const propertyPath = column.split('.');
if (propertyPath.length > 1) {
const propertyNamePath = propertyPath.slice(1);
let isNested = false, propertyName = propertyNamePath.join('.');
if (!propertyName.startsWith('(') && propertyNamePath.length > 1) {
isNested = true;
}
propertyName = propertyName.replace('(', '').replace(')', '');
return {
propertyPath: propertyPath[0],
propertyName, // the join is in case of an embedded entity
isNested,
column: `${propertyPath[0]}.${propertyName}`,
};
}
else {
return { propertyName: propertyPath[0], isNested: false, column: propertyPath[0] };
}
}
function extractVirtualProperty(qb, columnProperties) {
var _a, _b, _c, _d, _e, _f, _g, _h;
const metadata = columnProperties.propertyPath
? (_e = (_d = (_c = (_b = (_a = qb === null || qb === void 0 ? void 0 : qb.expressionMap) === null || _a === void 0 ? void 0 : _a.mainAlias) === null || _b === void 0 ? void 0 : _b.metadata) === null || _c === void 0 ? void 0 : _c.findColumnWithPropertyPath(columnProperties.propertyPath)) === null || _d === void 0 ? void 0 : _d.referencedColumn) === null || _e === void 0 ? void 0 : _e.entityMetadata // on relation
: (_g = (_f = qb === null || qb === void 0 ? void 0 : qb.expressionMap) === null || _f === void 0 ? void 0 : _f.mainAlias) === null || _g === void 0 ? void 0 : _g.metadata;
return (((_h = metadata === null || metadata === void 0 ? void 0 : metadata.columns) === null || _h === void 0 ? void 0 : _h.find((column) => column.propertyName === columnProperties.propertyName)) || {
isVirtualProperty: false,
query: undefined,
});
}
function includesAllPrimaryKeyColumns(qb, propertyPath) {
var _a, _b;
if (!qb || !propertyPath) {
return false;
}
return (_b = (_a = qb.expressionMap.mainAlias) === null || _a === void 0 ? void 0 : _a.metadata) === null || _b === void 0 ? void 0 : _b.primaryColumns.map((column) => column.propertyPath).every((column) => propertyPath.includes(column));
}
function getPrimaryKeyColumns(qb, entityName) {
var _a, _b;
return (_b = (_a = qb.expressionMap.mainAlias) === null || _a === void 0 ? void 0 : _a.metadata) === null || _b === void 0 ? void 0 : _b.primaryColumns.map((column) => entityName ? `${entityName}.${column.propertyName}` : column.propertyName);
}
function getMissingPrimaryKeyColumns(qb, transformedCols) {
if (!transformedCols || transformedCols.length === 0)
return [];
const mainEntityPrimaryKeys = getPrimaryKeyColumns(qb);
const missingPrimaryKeys = [];
for (const pk of mainEntityPrimaryKeys) {
const columnProperties = getPropertiesByColumnName(pk);
const pkAlias = fixColumnAlias(columnProperties, qb.alias, false);
if (!transformedCols.includes(pkAlias)) {
missingPrimaryKeys.push(pkAlias);
}
}
return missingPrimaryKeys;
}
function hasColumnWithPropertyPath(qb, columnProperties) {
var _a, _b;
if (!qb || !columnProperties) {
return false;
}
return !!((_b = (_a = qb.expressionMap.mainAlias) === null || _a === void 0 ? void 0 : _a.metadata) === null || _b === void 0 ? void 0 : _b.hasColumnWithPropertyPath(columnProperties.propertyName));
}
function checkIsRelation(qb, propertyPath) {
var _a, _b, _c;
if (!qb || !propertyPath) {
return false;
}
return !!((_c = (_b = (_a = qb === null || qb === void 0 ? void 0 : qb.expressionMap) === null || _a === void 0 ? void 0 : _a.mainAlias) === null || _b === void 0 ? void 0 : _b.metadata) === null || _c === void 0 ? void 0 : _c.hasRelationWithPropertyPath(propertyPath));
}
function checkIsNestedRelation(qb, propertyPath) {
var _a, _b;
let metadata = (_b = (_a = qb === null || qb === void 0 ? void 0 : qb.expressionMap) === null || _a === void 0 ? void 0 : _a.mainAlias) === null || _b === void 0 ? void 0 : _b.metadata;
for (const relationName of propertyPath.split('.')) {
const relation = metadata === null || metadata === void 0 ? void 0 : metadata.relations.find((relation) => relation.propertyPath === relationName);
if (!relation) {
return false;
}
metadata = relation.inverseEntityMetadata;
}
return true;
}
function checkIsEmbedded(qb, propertyPath) {
var _a, _b, _c;
if (!qb || !propertyPath) {
return false;
}
return !!((_c = (_b = (_a = qb === null || qb === void 0 ? void 0 : qb.expressionMap) === null || _a === void 0 ? void 0 : _a.mainAlias) === null || _b === void 0 ? void 0 : _b.metadata) === null || _c === void 0 ? void 0 : _c.hasEmbeddedWithPropertyPath(propertyPath));
}
function checkIsArray(qb, propertyName) {
var _a, _b, _c;
if (!qb || !propertyName) {
return false;
}
return !!((_c = (_b = (_a = qb === null || qb === void 0 ? void 0 : qb.expressionMap) === null || _a === void 0 ? void 0 : _a.mainAlias) === null || _b === void 0 ? void 0 : _b.metadata.findColumnWithPropertyName(propertyName)) === null || _c === void 0 ? void 0 : _c.isArray);
}
function checkIsJsonb(qb, propertyName) {
var _a, _b, _c, _d, _e, _f;
if (!qb || !propertyName) {
return false;
}
if (propertyName.includes('.')) {
const parts = propertyName.split('.');
const dbColumnName = parts[parts.length - 2];
return ((_c = (_b = (_a = qb === null || qb === void 0 ? void 0 : qb.expressionMap) === null || _a === void 0 ? void 0 : _a.mainAlias) === null || _b === void 0 ? void 0 : _b.metadata.findColumnWithPropertyName(dbColumnName)) === null || _c === void 0 ? void 0 : _c.type) === 'jsonb';
}
return ((_f = (_e = (_d = qb === null || qb === void 0 ? void 0 : qb.expressionMap) === null || _d === void 0 ? void 0 : _d.mainAlias) === null || _e === void 0 ? void 0 : _e.metadata.findColumnWithPropertyName(propertyName)) === null || _f === void 0 ? void 0 : _f.type) === 'jsonb';
}
// This function is used to fix the column alias when using relation, embedded or virtual properties
function fixColumnAlias(properties, alias, isRelation = false, isVirtualProperty = false, isEmbedded = false, query) {
if (isRelation) {
if (isVirtualProperty && query) {
return `(${query(`${alias}_${properties.propertyPath}_rel`)})`; // () is needed to avoid parameter conflict
}
else if ((isVirtualProperty && !query) || properties.isNested) {
if (properties.propertyName.includes('.')) {
const propertyPath = properties.propertyName.split('.');
const nestedRelations = propertyPath
.slice(0, -1)
.map((v) => `${v}_rel`)
.join('_');
const nestedCol = propertyPath[propertyPath.length - 1];
return `${alias}_${properties.propertyPath}_rel_${nestedRelations}.${nestedCol}`;
}
else {
return `${alias}_${properties.propertyPath}_rel_${properties.propertyName}`;
}
}
else {
return `${alias}_${properties.propertyPath}_rel.${properties.propertyName}`;
}
}
else if (isVirtualProperty) {
return query ? `(${query(`${alias}`)})` : `${alias}_${properties.propertyName}`;
}
else if (isEmbedded) {
return `${alias}.${properties.propertyPath}.${properties.propertyName}`;
}
else {
return `${alias}.${properties.propertyName}`;
}
}
function getQueryUrlComponents(path) {
const r = new RegExp('^(?:[a-z+]+:)?//', 'i');
let queryOrigin = '';
let queryPath = '';
if (r.test(path)) {
const url = new URL(path);
queryOrigin = url.origin;
queryPath = url.pathname;
}
else {
queryPath = path;
}
return { queryOrigin, queryPath };
}
const isoDateRegExp = new RegExp(/(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))/);
function isISODate(str) {
return isoDateRegExp.test(str);
}
function isRepository(repo) {
if (repo instanceof typeorm_1.Repository)
return true;
try {
if (Object.getPrototypeOf(repo).constructor.name === 'Repository')
return true;
return typeof repo === 'object' && !('connection' in repo) && 'manager' in repo;
}
catch (_a) {
return false;
}
}
function isFindOperator(value) {
if (value instanceof typeorm_1.FindOperator)
return true;
try {
if (Object.getPrototypeOf(value).constructor.name === 'FindOperator')
return true;
return typeof value === 'object' && '_type' in value && '_value' in value;
}
catch (_a) {
return false;
}
}
function createRelationSchema(configurationRelations) {
return Array.isArray(configurationRelations)
? OrmUtils_1.OrmUtils.propertyPathsToTruthyObject(configurationRelations)
: configurationRelations;
}
function mergeRelationSchema(...schemas) {
const noTrueOverride = (obj, source) => (source === true && obj !== undefined ? obj : undefined);
return (0, lodash_1.mergeWith)({}, ...schemas, noTrueOverride);
}
function getPaddedExpr(valueExpr, length, dbType) {
const lengthStr = String(length);
if (dbType === 'postgres' || dbType === 'cockroachdb') {
return `LPAD((${valueExpr})::bigint::text, ${lengthStr}, '0')`;
}
else if (dbType === 'mysql' || dbType === 'mariadb') {
return `LPAD(${valueExpr}, ${lengthStr}, '0')`;
}
else {
// sqlite
const padding = '0'.repeat(length);
return `SUBSTR('${padding}' || CAST(${valueExpr} AS INTEGER), -${lengthStr}, ${lengthStr})`;
}
}
function isDateColumnType(type) {
const dateTypes = [
Date, // JavaScript Date class
'datetime',
'timestamp',
'timestamptz',
];
return dateTypes.includes(type);
}
function quoteVirtualColumn(columnName, isMySqlOrMariaDb) {
return isMySqlOrMariaDb ? `\`${columnName}\`` : `"${columnName}"`;
}
//# sourceMappingURL=helper.js.map