Skip to content

Instantly share code, notes, and snippets.

@KATT
Created June 18, 2019 10:05
Show Gist options
  • Save KATT/dafb4ebe0025246b9425d0b4efe0d338 to your computer and use it in GitHub Desktop.
Save KATT/dafb4ebe0025246b9425d0b4efe0d338 to your computer and use it in GitHub Desktop.
import { transformWhereInput } from './transformWhereInput'
test('basic', () => {
expect(
transformWhereInput({
status: 'ACTIVE',
}),
).toEqual({
status: {
$eq: 'ACTIVE',
},
})
})
test('neq', () => {
expect(
transformWhereInput({
status__neq: 'ACTIVE',
}),
).toEqual({
status: {
$neq: 'ACTIVE',
},
})
})
test('OR', () => {
expect(
transformWhereInput({
OR: [
{
status: 'PENDING',
},
{
status: 'LOADING',
},
],
}),
).toEqual({
$or: [
{
status: {
$eq: 'PENDING',
},
},
{
status: {
$eq: 'LOADING',
},
},
],
})
})
test('AND', () => {
expect(
transformWhereInput({
AND: [
{
status: 'PENDING',
},
{
status: 'LOADING',
},
],
}),
).toEqual({
$and: [
{
status: {
$eq: 'PENDING',
},
},
{
status: {
$eq: 'LOADING',
},
},
],
})
})
test('blacklist', () => {
expect(
transformWhereInput(
{
included: '1',
excluded: '1',
excluded__eq: '1',
OR: [{ excluded: '1' }],
AND: [{ excluded: '1' }],
},
{
blacklist: ['excluded'],
},
),
).toEqual({
included: {
$eq: '1',
},
})
})
test('whitelist', () => {
expect(
transformWhereInput(
{
included: '1',
foo: '1',
bar: '1',
},
{
whitelist: ['included'],
},
),
).toEqual({
included: {
$eq: '1',
},
})
})
/* eslint-disable @typescript-eslint/no-use-before-define */
/* eslint-disable no-use-before-define */
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable @typescript-eslint/explicit-function-return-type */
export interface WhereInput {
[key: string]: any;
OR?: WhereInput[];
AND?: WhereInput[];
}
export interface SequelizeWhere {
[key: string]: any;
$or?: SequelizeWhere[];
$and?: SequelizeWhere[];
}
export interface TransformWhereInputOptions {
blacklist?: string[];
whitelist?: string[];
separator?: string;
}
export function transformAndOr(fields: WhereInput[], opts: TransformWhereInputOptions) {
return fields.map(w => transformWhereInput(w, opts)).filter(obj => Object.keys(obj).length > 0)
}
export function transformWhereInput(raw: WhereInput, opts: TransformWhereInputOptions = {}): SequelizeWhere {
const { blacklist, whitelist, separator = '__' } = opts
const newWhere: SequelizeWhere = {}
const { OR, AND, ...fields } = raw
Object.keys(fields).forEach((key) => {
const [fieldName, op = 'eq'] = key.split(separator)
if (blacklist && blacklist.includes(fieldName)) {
return
}
if (whitelist && !whitelist.includes(fieldName)) {
return
}
newWhere[fieldName] = newWhere[fieldName] || {}
newWhere[fieldName][`$${op}`] = fields[key]
})
if (OR) {
const $or = transformAndOr(OR, opts)
if ($or.length > 0) {
newWhere.$or = $or
}
}
if (AND) {
const $and = transformAndOr(AND, opts)
if ($and.length > 0) {
newWhere.$and = $and
}
}
return newWhere
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment