UNPKG

rsql

Version:

RSQL query string generator

92 lines (91 loc) 3.15 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const expression_1 = require("./expression"); const types_1 = require("./types"); class Query { constructor() { this.projections = []; this.conditions = []; this.sorts = []; this.max = 100; this.select = (...args) => { this.projections = args; return this; }; this.filter = (...args) => { this.conditions = exports.and(...args); return this; }; this.sort = (...args) => { this.sorts = args; return this; }; this.limit = (num) => { this.max = num; return this; }; this.qs = () => { let querystr = ''; if (this.projections.length > 0) { querystr += querystr !== '' ? '&' : ''; querystr += `select=${this.projections.join(',')}`; } if (this.conditions.length > 0) { querystr += querystr !== '' ? '&' : ''; querystr += `filter=${this.conditions.reduce((acc, cur) => { if (typeof cur === 'string') { acc += cur; } else { acc += cur.string(); } return acc; }, '')}`; } if (this.sorts.length > 0) { querystr += querystr !== '' ? '&' : ''; querystr += `sort=${this.sorts.join(',')}`; } if (this.max > 0) { querystr += querystr !== '' ? '&' : ''; querystr += `limit=${this.max.toFixed(0)}`; } return querystr; }; } } exports.default = Query; const mapExpr = (optr) => (field, value) => new expression_1.Expression(field, optr, value); const groupBy = (seperator) => (...args) => { const length = args.length - 1; const result = args.reduce((acc, cur, i) => { if (cur instanceof expression_1.Expression) { acc.push(cur); } else { acc = acc.concat(cur); } if (i < length) { acc.push(seperator); } return acc; }, ['(']); result.push(')'); return result; }; exports.or = groupBy(','); exports.and = groupBy(';'); exports.eq = mapExpr(types_1.Operator.Equal); exports.ne = mapExpr(types_1.Operator.NotEqual); exports.gt = mapExpr(types_1.Operator.GreaterThan); exports.gte = mapExpr(types_1.Operator.GreaterEqual); exports.lt = mapExpr(types_1.Operator.LesserThan); exports.lte = mapExpr(types_1.Operator.LesserEqual); exports.like = mapExpr(types_1.Operator.Like); exports.notLike = mapExpr(types_1.Operator.NotLike); exports.includes = mapExpr(types_1.Operator.In); exports.notIncludes = mapExpr(types_1.Operator.NotIn); exports.select = (...args) => new Query().select(...args); exports.filter = (...args) => new Query().filter(...args); exports.sort = (...args) => new Query().sort(...args); exports.limit = (num) => new Query().limit(num);