/
ruleString.ts
29 lines (24 loc) · 950 Bytes
/
ruleString.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import { toJSONString } from './ruleSerialisation'
import { PrimitiveOrExpression, RuleString } from './types'
/**
* A representation of a Firebase Rule String.
*
* https://firebase.google.com/docs/reference/security/database#string_properties
*/
const createRuleString = (name: string): RuleString => {
const str = (): string => name
str.matches = (regex: RegExp) => () => `${name}.matches(${regex.toString()})`
str.contains = (substr: PrimitiveOrExpression<string>) => () => `${name}.contains(${toJSONString(substr)})`
// .length is a readonly value, so force it.
Object.defineProperty(str, 'length', {
get: () => () => `${name}.length`
})
return str as RuleString
}
const createRuleStringArray = (name: string): RuleString[] => {
const arr: RuleString[] = []
return new Proxy(arr, {
get: (_target, index) => createRuleString(`${name}[${String(index)}]`)
})
}
export { createRuleString, createRuleStringArray }