Skip to content

Instantly share code, notes, and snippets.

@danmo
Created September 3, 2019 07:31
Show Gist options
  • Save danmo/b925b54d2eff39ba733738b88fd8886a to your computer and use it in GitHub Desktop.
Save danmo/b925b54d2eff39ba733738b88fd8886a to your computer and use it in GitHub Desktop.
/* eslint-disable class-methods-use-this */
import Joi from 'joi';
/**
* ENUM TYPES
*/
const OperationType = {
EQUALS: 'EQUALS',
NOT_EQUALS: 'NOT_EQUALS',
NOT_INCLUDED: 'NOT_INCLUDED',
REGEX: 'REGEX',
GREATER: 'GREATER',
LOWER: 'LOWER',
GREATER_OR_EQUAL: 'GREATER_OR_EQUAL',
LOWER_OR_EQUAL: 'LOWER_OR_EQUAL',
RANGE: 'RANGE',
};
const RelationType = {
AND: 'AND',
OR: 'OR',
};
/**
* ENTITY SCHEMAS
*/
const GenericQueryItemSchema = Joi.object().keys({
field: Joi.string(),
operation: Joi.string().valid(Object.keys(OperationType)),
value: Joi.any(),
});
const GenericQuerySchema = {
relation: Joi.string().valid(Object.keys(RelationType)),
items: Joi.alternatives().try(
GenericQueryItemSchema,
Joi.lazy(() => GenericQuerySchema), // recursive schema check
),
};
/**
* GenericQuery class definition
*/
class GenericQuery {
// relation = RelationType.AND;
// items = [];
GenericQuery(stringQuery) {
try {
const { relation, items } = JSON.parse(stringQuery);
this.relation = relation;
this.items = items;
} catch (e) {
throw new Error(`invalid string query provided ${e.message}`);
}
}
toKnex() {
// should build and return a knex query
// will be used by objection models mostly
}
}
const query = {
relation: 'AND',
items: [{
field: 'name',
operation: 'EQUALS',
value: 'test',
}, {
field: 'date',
operation: 'RANGE',
value: {
from: '',
to: '',
},
}],
};
const stringQuery = JSON.stringify(query);
console.log(new GenericQuery(stringQuery));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment