1 import {
2 MedusaError,
3 RuleOperator,
4 isObject,
5 isString,
6 pickValueFromObject,
7 } from "@medusajs/framework/utils"
8
9 /**
10 * The rule engine here is kept inside the module as of now, but it could be moved
11 * to the utils package and be used across the different modules that provides context
12 * based rule filtering.
13 *
14 * TODO: discussion around that should happen at some point
15 */
16
17 export type Rule = {
18 attribute: string
19 operator: Lowercase<keyof typeof RuleOperator> | (string & {})
20 value: string | string[] | null
21 }
22
23 export const availableOperators = Object.values(RuleOperator)
24
25 const isDate = (str: string) => {
26 return isNaN(Number(str)) && !isNaN(Date.parse(str))
27 }
28
29 const operatorsPredicate = {
30 in: (contextValue: string, ruleValue: string[]) =>
31 ruleValue.includes(contextValue),
32 nin: (contextValue: string, ruleValue: string[]) =>
33 !ruleValue.includes(contextValue),
34 eq: (contextValue: string, ruleValue: string) => contextValue === ruleValue,
35 ne: (contextValue: string, ruleValue: string) => contextValue !== ruleValue,
36 gt: (contextValue: string, ruleValue: string) => {
37 if (isDate(contextValue) && isDate(ruleValue)) {
38 return new Date(contextValue) > new Date(ruleValue)
39 }
40 return Number(contextValue) > Number(ruleValue)
41 },
42 gte: (contextValue: string, ruleValue: string) => {
43 if (isDate(contextValue) && isDate(ruleValue)) {
44 return new Date(contextValue) >= new Date(ruleValue)
45 }
46 return Number(contextValue) >= Number(ruleValue)
47 },
48 lt: (contextValue: string, ruleValue: string) => {
49 if (isDate(contextValue) && isDate(ruleValue)) {
50 return new Date(contextValue) < new Date(ruleValue)
51 }
52 return Number(contextValue) < Number(ruleValue)
53 },
54 lte: (contextValue: string, ruleValue: string) => {
55 if (isDate(contextValue) && isDate(ruleValue)) {
56 return new Date(contextValue) <= new Date(ruleValue)
57 }
58 return Number(contextValue) <= Number(ruleValue)
59 },
60 }
61
62 /**
63 * Validate contextValue context object from contextValue set of rules.
64 * By default, all rules must be valid to return true unless the option atLeastOneValidRule is set to true.
65 * @param context
66 * @param rules
67 * @param options
68 */
69 export function isContextValid(
70 context: Record<string, any>,
71 rules: Rule[],
72 options: {
73 someAreValid: boolean
74 } = {
75 someAreValid: false,
76 }
77 ): boolean {
78 const { someAreValid } = options
79
80 const loopComparator = someAreValid ? rules.some : rules.every
81 const predicate = (rule) => {
82 const { attribute, operator, value } = rule
83 const contextValue = pickValueFromObject(attribute, context)
84
85 return operatorsPredicate[operator](
86 `${contextValue}`,
87 value as string & string[]
88 )
89 }
90
91 return loopComparator.apply(rules, [predicate])
92 }
93
94 /**
95 * Validate contextValue rule object
96 * @param rule
97 */
98 export function validateRule(rule: Record<string, unknown>): boolean {
99 if (!rule.attribute || !rule.operator || !rule.value) {
100 throw new MedusaError(
101 MedusaError.Types.INVALID_DATA,
102 "Rule must have an attribute, an operator and a value"
103 )
104 }
105
106 if (!isString(rule.attribute)) {
107 throw new MedusaError(
108 MedusaError.Types.INVALID_DATA,
109 "Rule attribute must be a string"
110 )
111 }
112
113 if (!isString(rule.operator)) {
114 throw new MedusaError(
115 MedusaError.Types.INVALID_DATA,
116 "Rule operator must be a string"
117 )
118 }
119
120 if (!availableOperators.includes(rule.operator as RuleOperator)) {
121 throw new MedusaError(
122 MedusaError.Types.INVALID_DATA,
123 `Rule operator ${
124 rule.operator
125 } is not supported. Must be one of ${availableOperators.join(", ")}`
126 )
127 }
128
129 if (rule.operator === RuleOperator.IN || rule.operator === RuleOperator.NIN) {
130 if (!Array.isArray(rule.value)) {
131 throw new MedusaError(
132 MedusaError.Types.INVALID_DATA,
133 "Rule value must be an array for in/nin operators"
134 )
135 }
136 } else {
137 if (Array.isArray(rule.value) || isObject(rule.value)) {
138 throw new MedusaError(
139 MedusaError.Types.INVALID_DATA,
140 `Rule value must be a string, bool, number value for the selected operator ${rule.operator}`
141 )
142 }
143 }
144
145 return true
146 }
147
148 export function normalizeRulesValue<T extends Partial<Rule>>(rules: T[]): void {
149 rules.forEach((rule: any) => {
150 /**
151 * If a boolean is provided, then we convert to string
152 */
153 if (rule.value === true || rule.value === false) {
154 rule.value = rule.value === true ? "true" : "false"
155 }
156
157 return rule
158 })
159 }
160
161 export function validateAndNormalizeRules<T extends Partial<Rule>>(rules: T[]) {
162 rules.forEach(validateRule)
163 normalizeRulesValue(rules)
164 }
165
166 /**
167 * Validate contextValue set of rules
168 * @param rules
169 */
170 export function validateRules(rules: Record<string, unknown>[]): boolean {
171 rules.forEach(validateRule)
172 return true
173 }