Skip to content

Commit

Permalink
feat(filters): add better way to filter/keep based on undefined attr
Browse files Browse the repository at this point in the history
Makes it possible for entity whitelist rules to take the value `true` or `false` to mean "keep if present" or "discard if present".
  • Loading branch information
thibaudcolas committed Jan 17, 2018
1 parent 8d003aa commit f836563
Show file tree
Hide file tree
Showing 2 changed files with 96 additions and 18 deletions.
11 changes: 8 additions & 3 deletions src/lib/filters/entities.js
Original file line number Diff line number Diff line change
Expand Up @@ -91,10 +91,15 @@ export const shouldKeepEntityByAttribute = (
}

const isValid = Object.keys(whitelist).every((attr) => {
const regex = new RegExp(whitelist[attr])
const hasData = data.hasOwnProperty(attr)
const check = whitelist[attr]

return hasData && regex.test(data[attr])
if (typeof check === "boolean") {
const hasData = data.hasOwnProperty(attr)

return check ? hasData : !hasData
}

return new RegExp(check).test(data[attr])
})

return isValid
Expand Down
103 changes: 88 additions & 15 deletions src/lib/filters/entities.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,25 @@ describe("entities", () => {
).toBe(false)
})

it("attribute not defined on entities", () => {
expect(
shouldKeepEntityByAttribute(
[
{
type: "LINK",
whitelist: {
href: "^(?!#)",
},
},
],
"LINK",
{
url: "http://example.com",
},
),
).toBe(true)
})

describe("multiple attributes", () => {
it("valid", () => {
expect(
Expand Down Expand Up @@ -224,24 +243,78 @@ describe("entities", () => {
})
})

it("attribute not defined on entities", () => {
expect(
shouldKeepEntityByAttribute(
[
describe("attribute presence", () => {
it("requested, absent", () => {
expect(
shouldKeepEntityByAttribute(
[
{
type: "LINK",
whitelist: {
id: true,
},
},
],
"LINK",
{},
),
).toBe(false)
})

it("requested, present", () => {
expect(
shouldKeepEntityByAttribute(
[
{
type: "LINK",
whitelist: {
id: true,
},
},
],
"LINK",
{
type: "LINK",
whitelist: {
id: ".*",
id: "5",
},
),
).toBe(true)
})

it("requested out, absent", () => {
expect(
shouldKeepEntityByAttribute(
[
{
type: "LINK",
whitelist: {
id: false,
},
},
],
"LINK",
{},
),
).toBe(true)
})

it("requested out, present", () => {
expect(
shouldKeepEntityByAttribute(
[
{
type: "LINK",
whitelist: {
id: false,
},
},
],
"LINK",
{
id: "5",
},
],
"LINK",
{
href: "#_msocom_1",
target: "_blank",
},
),
).toBe(false)
),
).toBe(false)
})
})

describe("defaults", () => {
Expand Down

0 comments on commit f836563

Please sign in to comment.